Compare commits
34
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3205e7959 | ||
|
|
965f42e341 | ||
|
|
3750c0dd2f | ||
|
|
e9be2482bb | ||
|
|
2651bea9fe | ||
|
|
de4cb93788 | ||
|
|
a81d2a9ff9 | ||
|
|
3ab48eddf2 | ||
|
|
f7b60bd151 | ||
|
|
5a55a69cd1 | ||
|
|
23cc2c63dc | ||
|
|
1b98ba63dd | ||
|
|
8b3c774395 | ||
|
|
02fc7f000a | ||
|
|
cb09985ed6 | ||
|
|
c442731e95 | ||
|
|
7148c7f8c5 | ||
|
|
d954aeabfc | ||
|
|
5c9dd9972d | ||
|
|
233216e9f2 | ||
|
|
25a9c104f9 | ||
|
|
f573f7a9df | ||
|
|
785f07b0d1 | ||
|
|
1c0839ec50 | ||
|
|
b3fb3087f0 | ||
|
|
a59c9c0bc1 | ||
|
|
5ce100ca50 | ||
|
|
f673baef1b | ||
|
|
fbafccf86f | ||
|
|
2c87cd6501 | ||
|
|
b1bcb515dc | ||
|
|
68ab668373 | ||
|
|
43319e7330 | ||
|
|
54f99f67b7 |
@@ -89,6 +89,7 @@ Workflow examples are provided to help understand the basics.
|
||||
- If you want the Prompt Generator dropdowns to show only your local models, enable `Hide downloadable built-in models` in these settings.
|
||||
- Prompt Generator backend choices (llama.cpp, Ollama) and related options are configured there.
|
||||
- The Prompt Generator's system prompts are fully user-customizable. They're stored in `user/default/prompt_generator_data.json` and can be created and edited with the **Prompt Library Hub** (sidebar) — your custom prompts then show up directly in the Prompt Generator node.
|
||||
- **Edit / Generate Prompt MiniMax Outpaint** writes a MiniMax H3 Image outpaint prompt: connect the outpaint canvas (the picture on its gray-padded canvas, e.g. Load Image+'s `canvas` with Pad on) and optionally say what you want in the new area. Existing installs get it with the Prompt Library Hub's re-import of the default prompts.
|
||||
|
||||
## Documentation
|
||||
|
||||
|
||||
+13
-6
@@ -7,9 +7,12 @@ __author__ = "François Beaudry"
|
||||
__license__ = "MIT"
|
||||
|
||||
from .py.backup_manager import check_backup
|
||||
from .py.prompt_store import prompts_path
|
||||
from .py.prompt_composer_store import PromptComposerStore
|
||||
from .nodes.prompt_manager_adv import PromptManagerAdvanced
|
||||
from .nodes.prompt_manager_basic import PromptManager
|
||||
from .nodes.prompt_manager_v2 import PromptManagerV2
|
||||
from .nodes import prompt_library_routes # the routes on the shared prompt library
|
||||
from .nodes.prompt_composer import PromptComposer
|
||||
from .nodes.library_manager import LibraryManager
|
||||
from .nodes.prompt_generator import PromptGenerator, PromptGeneratorDataStore
|
||||
@@ -24,9 +27,10 @@ from .nodes.recipe_relay import WorkflowRelay as RecipeRelay
|
||||
from .nodes.recipe_model_loader import WorkflowModelLoader as RecipeModelLoader
|
||||
from .nodes.recipe_model_picker import RecipeModelPicker
|
||||
from .nodes.multi_prompt import RecipeBuilderMultiPrompts
|
||||
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine, MultiLoraSplitter, LoraStackCombine
|
||||
from .nodes.multi_lora_stacker import MultiLoraStackerLM, MultiLoraCombine, MultiLoraSplitter, MultiLoraRelay, LoraStackCombine
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"PromptManagerV2": PromptManagerV2,
|
||||
"PromptManagerAdvanced": PromptManagerAdvanced,
|
||||
"PromptManager": PromptManager,
|
||||
"PromptComposer": PromptComposer,
|
||||
@@ -47,12 +51,14 @@ NODE_CLASS_MAPPINGS = {
|
||||
"MultiLoraStackerLM": MultiLoraStackerLM,
|
||||
"MultiLoraCombine": MultiLoraCombine,
|
||||
"MultiLoraSplitter": MultiLoraSplitter,
|
||||
"MultiLoraRelay": MultiLoraRelay,
|
||||
"LoraStackCombine": LoraStackCombine,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"PromptManagerAdvanced": "Prompt Manager",
|
||||
"PromptManager": "Prompt Manager (Basic)",
|
||||
"PromptManagerV2": "Prompt Manager",
|
||||
"PromptManagerAdvanced": "Prompt Manager (legacy)",
|
||||
"PromptManager": "Prompt Manager (Basic, legacy)",
|
||||
"PromptComposer": "Prompt Composer",
|
||||
"LibraryManager": "Library Manager",
|
||||
"PromptGenerator": "Prompt Generator",
|
||||
@@ -69,8 +75,9 @@ NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"RecipeModelPicker": "Recipe Model Picker",
|
||||
"RecipeBuilderMultiPrompts": "Multi Prompts",
|
||||
"MultiLoraStackerLM": "Multi LoRA Stack",
|
||||
"MultiLoraCombine": "Multi LoRA Combine",
|
||||
"MultiLoraSplitter": "Multi LoRA Splitter",
|
||||
"MultiLoraCombine": "Multi LoRA Combine (legacy)",
|
||||
"MultiLoraSplitter": "Multi LoRA Splitter (legacy)",
|
||||
"MultiLoraRelay": "Multi LoRA Relay",
|
||||
"LoraStackCombine": "LoRA Stack Combine",
|
||||
}
|
||||
|
||||
@@ -79,7 +86,7 @@ __all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS', 'WEB_DIRECTORY']
|
||||
|
||||
# Ensure rotating backups exist for all prompt data files on ComfyUI startup.
|
||||
try:
|
||||
check_backup(PromptManager.get_prompts_path())
|
||||
check_backup(prompts_path())
|
||||
check_backup(PromptComposerStore.get_data_path())
|
||||
check_backup(PromptGeneratorDataStore.get_data_path())
|
||||
except Exception as e:
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
# FB UI rules
|
||||
|
||||
These rules apply to FBnodes, Prompt Manager and H3RefModPicker. Each pack ships an identical copy of `js/fbui/`; the canonical copy is in FBnodes, and `tools/sync_fbui.py` copies it into the other packs. Every pack still works on its own.
|
||||
|
||||
## Node faces
|
||||
- A converted node shows **one card** (`mountCard` in `fbui/card.js`). No stock widget rows stay visible on it.
|
||||
- Do not push plain-object widgets into `node.widgets`, do not draw UI in `onDrawForeground`/`onDrawBackground`, and do not override `widget.draw`. These do not render under Nodes 2.0.
|
||||
- Previews, players and editors are card `panel` rows. A panel that should take the node's spare height uses `grow: true`, and media sits `position:absolute` inside a `.fbui-stage`.
|
||||
|
||||
## Look
|
||||
- Every colour, radius and size comes from `fbui/theme.js`. Node files contain no hex literals.
|
||||
- Only `fbui/appearance.js` sets a node's colour. Individual nodes never set `color`/`bgcolor`.
|
||||
- Controls:
|
||||
- INT/FLOAT values use `scrub`, with any unit inside the box.
|
||||
- Booleans use an off | on pill.
|
||||
- Up to 4 short choices use a segmented pill; longer lists use a select.
|
||||
- Buttons use `button()` from `fbui/controls.js`.
|
||||
- A field that takes tokens or a syntax gets an (i) beside its label (`info:` on the card row) listing what it understands, instead of a long tooltip.
|
||||
- Toolbars over a preview go in `.fbui-stage-tools`.
|
||||
- **Media frame.** Pictures and videos sit in a `.fbui-stage`:
|
||||
- a neutral slate plate (`T.plate`) with a 1px trim (`T.plateEdge`) and rounded corners;
|
||||
- the media is fitted edge to edge, with the plate showing around it.
|
||||
- No dark well, no backdrop pattern.
|
||||
- **Footnote bar.** Every node that shows a picture or video ends its preview with a footnote bar: a card `panel` row of height `CAPTION_HEIGHT` holding a `.fbui-caption`. It uses the same plate and trim as the media frame. This covers Load Image+, Load Video+, Save Image+ and Save Video+.
|
||||
- It is always the **last row** of the card, below any frame picker or fold-out section.
|
||||
- It states the one size the node outputs: the cropped size when a crop is on, not "before → after".
|
||||
- It shows `—` when there is nothing loaded.
|
||||
- Never draw these numbers on the picture itself.
|
||||
- **Frame picker.** Choosing a video frame uses a rail with a white playhead (`rail()` in `fbui/controls.js`) above a line holding a `FRAME` tag, a frame-number scrub, and a readout (`6.88 s · of 240 frames`).
|
||||
- **Spacing.** Keep the kit's spacing; don't squeeze rows. Buttons in a row with a label use icon-only squares (Browse, flips) so the main control keeps its width.
|
||||
- Overlays drawn on a picture (crop outline, guides) are dotted while their tool is active.
|
||||
|
||||
## Review screens
|
||||
A run that pauses for a choice (Save Image+ review; Video Review next) uses the same screen:
|
||||
- It is full screen. The media fill the space as large as possible (`bestGrid` in `js/common/grid_math.js`).
|
||||
- A small floating panel holds the node's name, the pick count, the timer pill with its bar, and two buttons: **Send** (the picked ones; none picked sends none) and **Skip**.
|
||||
- A click picks. Space shows one item at full size (←/→ to step, Space or Esc back), and Enter sends.
|
||||
- Picking pauses the timer. A queue cancel ends the wait at once.
|
||||
|
||||
## Workflow compatibility
|
||||
- Never rename, reorder or remove Python inputs. Append new inputs at the end.
|
||||
- Widgets added in JS must have `serialize = false`. The frontend skips them when saving `widgets_values`, so adding or removing them never shifts saved values.
|
||||
- Hide widgets with `hideWidget`; never splice them out of `node.widgets`.
|
||||
- Prove each conversion with a fixture in `test/` that asserts `widgets_values` survives configure and serialize unchanged. Real saved workflows are checked by the maintainer; tools and agents never read ComfyUI's `user/` folder.
|
||||
- If a node's Python inputs really must change:
|
||||
- Keep the old class under its old key, with `DEPRECATED = True` and the display name `"… (legacy)"`.
|
||||
- Register the new class under a new key (such as `LoadImagePlusV2`), using the original display name.
|
||||
|
||||
## Nodes 2.0
|
||||
- Build UI from DOM only.
|
||||
- Growing panels use `fillNodeHeight`, and fixed panels use `pinHeight` (both in `fbui/layout.js`).
|
||||
- Set `node.hideOutputImages = true` when the node draws its own preview.
|
||||
- Do not reach into `app.canvas._*` internals.
|
||||
- Check every change in both the Classic and Nodes 2.0 renderers.
|
||||
|
||||
## Code
|
||||
- Shared modules (`js/fbui/`, `js/common/`) are `.js`, never `.mjs`. ComfyUI serves `.js` with `Cache-Control: no-store`, but sends `.mjs` with no cache header. The browser then keeps an old copy after an update, and a new module can import a name the stale one lacks, so the whole pack fails to load.
|
||||
- ComfyUI imports every `.js` in the web folder, so shared modules must do nothing at import time: only exports, with no registration and no DOM work.
|
||||
- Hook callbacks with `chainCallback`/`chainHandler`; never assign over an existing callback.
|
||||
- Show messages with `toast()` from `fbui/comfy.js`, never `alert()`. After a user edit, call `notifyChange()` so undo and the dirty flag see it.
|
||||
- Call server routes with `api.fetchApi`, never raw `fetch`.
|
||||
- Naming:
|
||||
- kit classes start with `fbui-`;
|
||||
- kit widget names start with `fbui_`;
|
||||
- extension names start with the pack (`FBnodes.*`, `PromptManager.*`, `H3RefModPicker.*`);
|
||||
- routes stay prefixed with their pack.
|
||||
- A call into another pack's routes must handle a 404 and hide the feature.
|
||||
- Bump `KIT_VERSION` in `fbui/theme.js` whenever the kit CSS changes, then sync the kit to every pack.
|
||||
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## Unreleased
|
||||
- **New node: Multi LoRA Relay**
|
||||
- Combines and splits LoRA stacks in one node, passing through on both ends like Recipe Relay: `lora_stacks` (a multi stack, or a plain stack as slot A) and `lora_stack_a`..`d` in; the same out. A stack wired to a slot is appended to it.
|
||||
- Multi LoRA Combine and Multi LoRA Splitter are now legacy; old workflows keep working.
|
||||
- **Fixes**
|
||||
- Saving a prompt in Prompt Manager (Basic) no longer wipes the LoRAs C/D, recipe data and negative prompt saved by the full Prompt Manager.
|
||||
- Importing a library keeps every field of a prompt (recipe data, negative prompt, extra fields) and the category base prompt / prefix.
|
||||
- Prompt Manager no longer resets its LoRA and trigger-word toggles on every run when no LoRAs are connected to its inputs.
|
||||
- Prompt Manager (Basic): the unsaved-changes warning works, and switching to an empty category no longer fails.
|
||||
- The prompt library is read once per load instead of about four times, and an unreadable library is never overwritten with the default prompts.
|
||||
- Library files can only be opened as JSON.
|
||||
|
||||
## version 3.0.1
|
||||
- **Prompt Generator: GPU detection fix for Windows (and recent llama.cpp builds)**
|
||||
- `--n-gpu-layers 0` is no longer forced just because GPU support could not be detected. On Windows the old check always failed (`ldd` does not exist there, `--version` no longer names the backend, and `-h` lists `--n-gpu-layers` on every build), which pushed CUDA users into CPU inference and printed a misleading "CPU-only build" error.
|
||||
|
||||
@@ -82,7 +82,7 @@ This node provides extra control to **Prompt Generator** and is NOT mandatory.
|
||||
|
||||
### Prompt Library Hub
|
||||
The **Prompts** button in ComfyUI's left sidebar opens the Prompt Library Hub (hide it with Settings > Prompt Manager > 4. Advanced Preferences > Show Prompts Sidebar Button): one place to browse, edit, import and export every Prompt Manager library. It has three sections:
|
||||
- **Saved Prompts**: pick the type with the Prompt Manager / Prompt Composer / Prompt Layout / Prompt Recipe buttons (saved through Prompt Manager or Library Manager).
|
||||
- **Saved Prompts**: everything saved through Prompt Manager or Library Manager (prompts, recipes, Composer setups and layouts); the Prompt Browser's **Type** button filters them.
|
||||
- **Saved Snippets**: the snippets used by Prompt Composer.
|
||||
- **Saved System Prompts**: the system prompts used by Prompt Generator.
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
// Solid node colours for every node of the pack that installs this, the one
|
||||
// thing that makes the packs read as one family on the canvas. Nodes without
|
||||
// any JS of their own get the colours too.
|
||||
//
|
||||
// A node follows the setting while it carries no colours or exactly one
|
||||
// scheme's pair; a colour picked in ComfyUI's own colour menu is the user's
|
||||
// and wins.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
import { chainCallback } from "./dom.js";
|
||||
|
||||
export const NODE_COLOR_SCHEMES = [
|
||||
{ name: "FB Blue", colors: { title: "#1b3350", body: "#161b22" } },
|
||||
{ name: "Theme default", colors: null },
|
||||
{ name: "Graphite", colors: { title: "#242424", body: "#2f2f2f" } },
|
||||
{ name: "Slate", colors: { title: "#1f2c38", body: "#2a3b4a" } },
|
||||
{ name: "Teal", colors: { title: "#14332f", body: "#1c453f" } },
|
||||
{ name: "Plum", colors: { title: "#2e1f38", body: "#3d2a4a" } },
|
||||
{ name: "Rust", colors: { title: "#3a2317", body: "#4c2f20" } },
|
||||
];
|
||||
const NAMES = NODE_COLOR_SCHEMES.map((scheme) => scheme.name);
|
||||
const norm = (value) => (typeof value === "string" ? value.trim().toLowerCase() : "");
|
||||
const schemeColors = (name) => NODE_COLOR_SCHEMES.find((scheme) => scheme.name === name)?.colors ?? null;
|
||||
const SCHEME_TITLES = new Set(NODE_COLOR_SCHEMES.flatMap((scheme) => (scheme.colors ? [scheme.colors.title] : [])));
|
||||
|
||||
// Our scheme titles are dark: the classic renderer's grey title text gets
|
||||
// lost on them. Marked on the node by nodeCreated (never saved).
|
||||
const MARK = Symbol.for("fbui.packNode");
|
||||
|
||||
function followsSetting(node) {
|
||||
const color = norm(node.color);
|
||||
const bgcolor = norm(node.bgcolor);
|
||||
if (!color && !bgcolor) return true;
|
||||
return NODE_COLOR_SCHEMES.some((scheme) => scheme.colors && color === scheme.colors.title && bgcolor === scheme.colors.body);
|
||||
}
|
||||
|
||||
function apply(node, colors) {
|
||||
// Assigning undefined (never `delete`) keeps Nodes 2.0 reactive.
|
||||
node.color = colors ? colors.title : undefined;
|
||||
node.bgcolor = colors ? colors.body : undefined;
|
||||
}
|
||||
|
||||
function allNodes(graph, seen = new Set()) {
|
||||
if (!graph || seen.has(graph)) return [];
|
||||
seen.add(graph);
|
||||
const out = [];
|
||||
for (const node of graph._nodes ?? graph.nodes ?? []) {
|
||||
out.push(node);
|
||||
if (node.subgraph) out.push(...allNodes(node.subgraph, seen));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Wrapping drawTitleText is the one place a prototype is patched directly: a
|
||||
// draw method must return through the original. Shared by every pack.
|
||||
function installTitleInk() {
|
||||
const proto = globalThis.LiteGraph?.LGraphNode?.prototype;
|
||||
if (typeof proto?.drawTitleText !== "function" || proto.drawTitleText[MARK]) return;
|
||||
const original = proto.drawTitleText;
|
||||
function drawTitleText(ctx, options, ...rest) {
|
||||
if (options && this?.[MARK] && SCHEME_TITLES.has(norm(this.color))) options = { ...options, default_title_color: "#ffffff" };
|
||||
return original.call(this, ctx, options, ...rest);
|
||||
}
|
||||
drawTitleText[MARK] = true;
|
||||
proto.drawTitleText = drawTitleText;
|
||||
}
|
||||
|
||||
// installAppearance({ settingsPrefix: "FBnodes", category: "FBnodes" }) from
|
||||
// the pack's fbui_setup.js. The pack is found from this file's own URL
|
||||
// (/extensions/<folder>/fbui/...), which matches the nodes' python_module
|
||||
// whatever the install folder is called.
|
||||
export function installAppearance({ settingsPrefix, category }) {
|
||||
const folder = decodeURIComponent(new URL(import.meta.url).pathname.split("/extensions/")[1]?.split("/")[0] ?? "");
|
||||
const module = `custom_nodes.${folder}`;
|
||||
const settingId = `${settingsPrefix}.Appearance.NodeColor`;
|
||||
const ours = (node) => node?.constructor?.nodeData?.python_module === module;
|
||||
let active = NAMES[0];
|
||||
|
||||
app.registerExtension({
|
||||
name: `${settingsPrefix}.Appearance`,
|
||||
settings: [
|
||||
{
|
||||
id: settingId,
|
||||
category: [category, "Appearance", "Node color"],
|
||||
name: "Node color",
|
||||
type: "combo",
|
||||
defaultValue: NAMES[0],
|
||||
options: NAMES,
|
||||
tooltip: "Colour scheme for this pack's nodes. Nodes you coloured by hand keep their own colours.",
|
||||
onChange(value) {
|
||||
active = NAMES.includes(value) ? value : NAMES[0];
|
||||
for (const node of allNodes(app.graph)) if (ours(node) && followsSetting(node)) apply(node, schemeColors(active));
|
||||
app.graph?.setDirtyCanvas?.(true, true);
|
||||
},
|
||||
},
|
||||
],
|
||||
setup() {
|
||||
const stored = app.ui?.settings?.getSettingValue?.(settingId);
|
||||
if (NAMES.includes(stored)) active = stored;
|
||||
installTitleInk();
|
||||
},
|
||||
nodeCreated(node) {
|
||||
if (!ours(node)) return;
|
||||
node[MARK] = true;
|
||||
if (followsSetting(node)) apply(node, schemeColors(active));
|
||||
// Native text boxes wear the kit's text-area colour: Classic draws the
|
||||
// widget's own textarea, Nodes 2.0 one carrying the widget's options.
|
||||
for (const widget of node.widgets ?? []) {
|
||||
if (widget.element?.tagName !== "TEXTAREA") continue;
|
||||
widget.element.classList.add("fbui-native-text");
|
||||
widget.options = { ...widget.options, "data-fbui-text": "true" };
|
||||
}
|
||||
// Saved colours arrive after construction: a workflow saved before the
|
||||
// pack had colours, or with another scheme, follows the setting now.
|
||||
chainCallback(node, "onConfigure", function () {
|
||||
if (followsSetting(this)) apply(this, schemeColors(active));
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
+435
@@ -0,0 +1,435 @@
|
||||
// The card: one DOM panel standing in for a node's stock widgets. Every row
|
||||
// mirrors a hidden widget (or a pair of them), so the widgets stay the source
|
||||
// of truth: save/load, undo, API format and links all keep working through
|
||||
// them. The card writes widget.value, runs the widget's callback, and re-reads
|
||||
// everything on configure, on connection changes and after any callback.
|
||||
//
|
||||
// Rows:
|
||||
// { widget, label?, kind?, suffix?, labels?, title?, info?, when?, group?, button? }
|
||||
// info: help lines shown from an (i) beside the label (see controls.info)
|
||||
// kind: scrub | segment | select | switch | text (default: from the widget)
|
||||
// labels: { value: text } or (value, values, node) => text
|
||||
// button: { text, icon?, title?, onClick(node, card) } (or a list) after the control
|
||||
// groups: (value, values, node) => heading, for a select's <optgroup>s
|
||||
// { pair: [a, b], label, sep?, when?, group? }
|
||||
// { section: "Caption", when? }
|
||||
// { label, control: (node, card) => ({ element, label?, sync?(values) }), widgets?, when?, group? }
|
||||
// a labelled row holding the node's own control; `widgets` names the
|
||||
// hidden widgets it drives; a returned `label` element replaces the text
|
||||
// { panel: (node, card) => ({ element, sync?(values) }), height, grow?, when? }
|
||||
// grow takes the node's spare height; a height function is read again
|
||||
// on every refresh (a panel whose content wraps)
|
||||
// { group: "more", label: "More", tools? } later rows with group: "more" fold under it
|
||||
// tools: (node, card) => ({ element, sync?(values) }) at the header's right
|
||||
// Options: minWidth, first (place before the node's other DOM widgets).
|
||||
import { chainCallback, el, keepDomWidgetWidthAuto, keepKeyInField } from "./dom.js";
|
||||
import { notifyChange } from "./comfy.js";
|
||||
import { button as makeButton, info as infoIcon, segmented } from "./controls.js";
|
||||
import { cardHeight, choiceLabel, isGroupHeader, rowHeight, rowKind, rowTops, socketWidgetY, visibleRows } from "./card_math.js";
|
||||
import { ensureNodeMinHeight, fillNodeHeight, pinHeight, WIDGET_FRAME } from "./layout.js";
|
||||
import { makeScrub, scrubSteps } from "./scrub.js";
|
||||
import { ensureKitCss, GROUP_HEIGHT, ROW_HEIGHT, UNIT_SLOT_WIDTH } from "./theme.js";
|
||||
import { comboValues, commitWidgetValue, findWidget, hideWidget, widgetLinked, widgetSlot, widgetTooltip } from "./widgets.js";
|
||||
|
||||
export const CARD_WIDGET = "fbui_card";
|
||||
const WRAPPER_TOP = 10;
|
||||
|
||||
function isFloatWidget(widget) {
|
||||
const precision = widget?.options?.precision;
|
||||
if (precision !== undefined) return Number(precision) > 0;
|
||||
const step = widget?.options?.step2 ?? widget?.options?.round;
|
||||
return step !== undefined ? !Number.isInteger(Number(step)) : !Number.isInteger(Number(widget?.value));
|
||||
}
|
||||
|
||||
export function mountCard(node, { rows, minWidth = 280, first = false } = {}) {
|
||||
ensureKitCss();
|
||||
const root = el("div", "fbui-card");
|
||||
const card = { node, root, entries: [], height: 0, widget: null, rowTop: new Map(), rowSpan: new Map(), disposed: false };
|
||||
const managed = new Set();
|
||||
|
||||
const values = () => Object.fromEntries((node.widgets ?? []).map((widget) => [widget.name, widget.value]));
|
||||
const groupKey = (name) => `fbui_open_${name}`;
|
||||
const groupOpen = (name) => Boolean(node.properties?.[groupKey(name)]);
|
||||
|
||||
const setWidget = (name, value, { settle = true } = {}) => {
|
||||
const widget = findWidget(node, name);
|
||||
if (!widget || widget.value === value) return;
|
||||
card.byHand = true;
|
||||
try {
|
||||
commitWidgetValue(node, widget, value);
|
||||
} finally {
|
||||
card.byHand = false;
|
||||
}
|
||||
node.graph?.setDirtyCanvas?.(true, true);
|
||||
if (settle) notifyChange();
|
||||
};
|
||||
card.setWidget = setWidget;
|
||||
|
||||
const builders = {
|
||||
scrub(name, row, into) {
|
||||
const widget = findWidget(node, name);
|
||||
const isFloat = isFloatWidget(widget);
|
||||
const steps = scrubSteps(widget?.options, isFloat, row.suffix === "px");
|
||||
const control = makeScrub({
|
||||
value: Number(widget?.value) || 0,
|
||||
min: Number(widget?.options?.min ?? -Infinity),
|
||||
max: Number(widget?.options?.max ?? Infinity),
|
||||
step: row.step ?? steps.step,
|
||||
fineStep: steps.fineStep,
|
||||
decimals: row.decimals ?? steps.decimals,
|
||||
unit: row.suffix ?? "",
|
||||
unitWidth: row.pair ? 0 : UNIT_SLOT_WIDTH,
|
||||
title: row.title ?? widgetTooltip(node, name),
|
||||
onChange: (next) => setWidget(name, isFloat ? next : Math.round(next), { settle: false }),
|
||||
onSettle: notifyChange,
|
||||
});
|
||||
into.append(control.root);
|
||||
return (vals) => control.set(Number(vals[name]) || 0);
|
||||
},
|
||||
segment(name, row, into) {
|
||||
const widget = findWidget(node, name);
|
||||
// The choices can change (one widget's list following another's value):
|
||||
// the pill is rebuilt whenever they do.
|
||||
let shown = null;
|
||||
let seg = null;
|
||||
return (vals) => {
|
||||
const options = comboValues(widget);
|
||||
const key = options.join("\n");
|
||||
if (key !== shown) {
|
||||
shown = key;
|
||||
const next = segmented(options.map((value) => ({ value, label: choiceLabel(row, value, options, node), title: row.titles?.[value] })), { onPick: (value) => setWidget(name, value) });
|
||||
if (seg) seg.root.replaceWith(next.root);
|
||||
else into.append(next.root);
|
||||
seg = next;
|
||||
}
|
||||
seg.set(vals[name]);
|
||||
};
|
||||
},
|
||||
switch(name, row, into) {
|
||||
const seg = segmented([{ value: false, label: row.offText ?? "off" }, { value: true, label: row.onText ?? "on" }], { bool: true, onPick: (value) => setWidget(name, value) });
|
||||
seg.root.title = row.title ?? widgetTooltip(node, name);
|
||||
into.append(seg.root);
|
||||
return (vals) => seg.set(Boolean(vals[name]));
|
||||
},
|
||||
select(name, row, into) {
|
||||
const widget = findWidget(node, name);
|
||||
const select = el("select", "fbui-select");
|
||||
select.title = row.title ?? widgetTooltip(node, name);
|
||||
let shown = null;
|
||||
const fill = (current) => {
|
||||
const options = comboValues(widget);
|
||||
const list = options.includes(current) || current === undefined || current === "" ? options : [...options, current];
|
||||
const key = list.join("\n");
|
||||
if (key !== shown) {
|
||||
shown = key;
|
||||
select.textContent = "";
|
||||
// row.groups(value) names a value's group: runs of one group sit
|
||||
// under an <optgroup> heading.
|
||||
let group = null;
|
||||
for (const value of list) {
|
||||
const option = el("option", "", choiceLabel(row, value, options, node));
|
||||
option.value = String(value);
|
||||
const name = row.groups?.(value, options, node) ?? null;
|
||||
if (name && name !== group?.label) {
|
||||
group = el("optgroup");
|
||||
group.label = name;
|
||||
select.append(group);
|
||||
} else if (!name) group = null;
|
||||
(group ?? select).append(option);
|
||||
}
|
||||
}
|
||||
select.value = String(current ?? "");
|
||||
select.title = String(current ?? "") || widgetTooltip(node, name);
|
||||
};
|
||||
select.addEventListener("change", () => setWidget(name, select.value));
|
||||
// The list may change between refreshes (an upload, a folder change).
|
||||
select.addEventListener("pointerdown", () => fill(findWidget(node, name)?.value));
|
||||
into.append(select);
|
||||
return (vals) => fill(vals[name]);
|
||||
},
|
||||
text(name, row, into) {
|
||||
const input = el("input", "fbui-text");
|
||||
input.type = "text";
|
||||
input.spellcheck = false;
|
||||
input.placeholder = row.placeholder ?? "";
|
||||
input.title = row.title ?? widgetTooltip(node, name);
|
||||
const commit = () => {
|
||||
if (input.value !== String(findWidget(node, name)?.value ?? "")) setWidget(name, input.value);
|
||||
};
|
||||
input.addEventListener("change", commit);
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key === "Enter") input.blur();
|
||||
if (event.key === "Escape") {
|
||||
input.value = String(findWidget(node, name)?.value ?? "");
|
||||
input.blur();
|
||||
}
|
||||
});
|
||||
into.append(input);
|
||||
return (vals) => {
|
||||
if (document.activeElement !== input) input.value = String(vals[name] ?? "");
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
let currentGroup = null;
|
||||
for (const row of rows) {
|
||||
if (row.section !== undefined) {
|
||||
const caption = el("div", "fbui-section", row.section);
|
||||
card.entries.push({ row: { ...row, inGroup: currentGroup }, element: caption, syncs: [] });
|
||||
root.append(caption);
|
||||
continue;
|
||||
}
|
||||
if (row.panel) {
|
||||
const line = el("div", "fbui-row panel");
|
||||
if (row.grow) {
|
||||
line.classList.add("grow");
|
||||
line.style.minHeight = `${rowHeight(row)}px`;
|
||||
} else {
|
||||
line.style.height = `${rowHeight(row)}px`;
|
||||
}
|
||||
const panel = row.panel(node, card);
|
||||
line.append(panel.element);
|
||||
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, syncs: panel.sync ? [panel.sync] : [] });
|
||||
root.append(line);
|
||||
continue;
|
||||
}
|
||||
if (row.control) {
|
||||
// `widgets` names the hidden widgets the control drives: their sockets
|
||||
// sit on this row and a link dims it, as for a widget row.
|
||||
const names = row.widgets ?? [];
|
||||
for (const name of names) {
|
||||
const widget = findWidget(node, name);
|
||||
if (widget) {
|
||||
hideWidget(widget);
|
||||
managed.add(name);
|
||||
}
|
||||
}
|
||||
const line = el("div", "fbui-row");
|
||||
const control = el("div", "fbui-control");
|
||||
const built = row.control(node, card);
|
||||
control.append(built.element);
|
||||
line.append(built.label ?? el("span", "fbui-label", row.label ?? ""), control);
|
||||
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, names, syncs: built.sync ? [built.sync] : [] });
|
||||
root.append(line);
|
||||
continue;
|
||||
}
|
||||
if (isGroupHeader(row)) {
|
||||
currentGroup = row.group;
|
||||
const header = el("div", "fbui-group");
|
||||
const toggle = el("button", "toggle");
|
||||
toggle.type = "button";
|
||||
toggle.append(el("span", "glyph", "▸"), el("span", "", row.label ?? row.group));
|
||||
const tools = row.tools?.(node, card);
|
||||
header.append(toggle, ...(tools ? [tools.element] : []));
|
||||
toggle.addEventListener("click", () => {
|
||||
node.properties ??= {};
|
||||
node.properties[groupKey(row.group)] = !groupOpen(row.group);
|
||||
card.byHand = true;
|
||||
try {
|
||||
refresh();
|
||||
} finally {
|
||||
card.byHand = false;
|
||||
}
|
||||
});
|
||||
card.entries.push({ row, element: header, header: true, syncs: tools?.sync ? [tools.sync] : [] });
|
||||
root.append(header);
|
||||
continue;
|
||||
}
|
||||
const names = row.pair ?? [row.widget];
|
||||
for (const name of names) {
|
||||
const widget = findWidget(node, name);
|
||||
if (widget) {
|
||||
hideWidget(widget);
|
||||
managed.add(name);
|
||||
}
|
||||
}
|
||||
const line = el("div", "fbui-row");
|
||||
const label = el("span", "fbui-label");
|
||||
label.title = row.title ?? widgetTooltip(node, names[0]);
|
||||
if (row.info) {
|
||||
label.classList.add("has-info");
|
||||
label.append(el("span", "", row.label ?? names[0]), infoIcon(row.info));
|
||||
} else {
|
||||
label.textContent = row.label ?? names[0];
|
||||
}
|
||||
const control = el("div", "fbui-control");
|
||||
const syncs = [];
|
||||
const fields = new Map();
|
||||
names.forEach((name, index) => {
|
||||
const widget = findWidget(node, name);
|
||||
if (!widget) return;
|
||||
if (index > 0) control.append(el("span", "fbui-sep", row.sep ?? "·"));
|
||||
if (row.prefixes?.[index]) control.append(el("span", "fbui-sep", row.prefixes[index]));
|
||||
const field = el("div", "fbui-field");
|
||||
const kind = rowKind(row, widget, comboValues(widget));
|
||||
syncs.push(builders[kind](name, row, field));
|
||||
control.append(field);
|
||||
fields.set(name, field);
|
||||
});
|
||||
for (const { text, onClick, ...rest } of [row.button ?? []].flat()) {
|
||||
control.append(makeButton(text, { ...rest, onClick: () => onClick?.(node, card) }));
|
||||
}
|
||||
line.append(label, control);
|
||||
card.entries.push({ row: { ...row, inGroup: row.group ?? null }, element: line, names, syncs, fields });
|
||||
root.append(line);
|
||||
}
|
||||
|
||||
// Clicks on controls stay out of the graph's drag; empty card space falls
|
||||
// through. A stage stops the events it consumes itself.
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
if (event.target.closest("button,input,select,textarea,.fbui-scrub")) event.stopPropagation();
|
||||
});
|
||||
|
||||
const widget = node.addDOMWidget(CARD_WIDGET, CARD_WIDGET, root, { serialize: false, hideOnZoom: false });
|
||||
keepDomWidgetWidthAuto(widget);
|
||||
// options.serialize only keeps it out of the prompt; saves skip a widget
|
||||
// whose own serialize is false.
|
||||
widget.serialize = false;
|
||||
card.widget = widget;
|
||||
const declared = () => card.height + WIDGET_FRAME;
|
||||
if (rows.some((row) => row.grow)) fillNodeHeight(widget, { minWidth, minHeight: declared });
|
||||
else pinHeight(widget, declared, minWidth);
|
||||
if (first && Array.isArray(node.widgets)) {
|
||||
const index = node.widgets.indexOf(widget);
|
||||
const firstDom = node.widgets.findIndex((item) => item !== widget && item.element);
|
||||
if (index >= 0 && firstDom >= 0 && firstDom < index) {
|
||||
node.widgets.splice(index, 1);
|
||||
node.widgets.splice(firstDom, 0, widget);
|
||||
}
|
||||
}
|
||||
|
||||
// Each hidden widget with an input slot reports the y of its row, so the
|
||||
// frontend draws and hit-tests its socket there. A folded row hands its
|
||||
// socket to its group header, or to the card's top edge.
|
||||
const socketY = (name) => {
|
||||
const cardY = Number(card.widget?.y);
|
||||
if (card.disposed || !Number.isFinite(cardY)) return null;
|
||||
const top = card.rowTop.get(name);
|
||||
if (top === undefined) return cardY + WRAPPER_TOP;
|
||||
return socketWidgetY(cardY, WRAPPER_TOP, top, card.rowSpan.get(name) ?? ROW_HEIGHT);
|
||||
};
|
||||
const socketed = [];
|
||||
for (const name of managed) {
|
||||
const target = findWidget(node, name);
|
||||
if (!target || !widgetSlot(node, name) || Object.getOwnPropertyDescriptor(target, "y")?.get) continue;
|
||||
let stored = target.y;
|
||||
try {
|
||||
Object.defineProperty(target, "y", { configurable: true, enumerable: true, get: () => socketY(name) ?? stored, set: (value) => { stored = value; } });
|
||||
socketed.push(() => { delete target.y; target.y = stored; });
|
||||
} catch {
|
||||
// A sealed widget keeps its socket where the frontend puts it.
|
||||
}
|
||||
}
|
||||
|
||||
// While a link is dragged, the row under the pointer stands in for its
|
||||
// widget, so a drop anywhere on the row lands on that widget's input.
|
||||
const originalGetWidgetOnPos = node.getWidgetOnPos;
|
||||
if (typeof originalGetWidgetOnPos === "function") {
|
||||
node.getWidgetOnPos = function (canvasX, canvasY, includeDisabled) {
|
||||
const found = originalGetWidgetOnPos.call(this, canvasX, canvasY, includeDisabled);
|
||||
if (card.disposed || found !== card.widget || !globalThis.app?.canvas?.linkConnector?.isConnecting) return found;
|
||||
const localY = canvasY - this.pos[1] - Number(card.widget.y) - WRAPPER_TOP;
|
||||
for (const entry of card.entries) {
|
||||
const name = entry.names?.[0];
|
||||
const top = card.rowTop.get(name);
|
||||
if (top !== undefined && localY >= top && localY <= top + (card.rowSpan.get(name) ?? ROW_HEIGHT)) return findWidget(this, name) ?? found;
|
||||
}
|
||||
return found;
|
||||
};
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
if (card.disposed) return;
|
||||
const vals = values();
|
||||
const open = {};
|
||||
for (const entry of card.entries) if (entry.header) open[entry.row.group] = groupOpen(entry.row.group);
|
||||
const shown = visibleRows(card.entries.map((entry) => entry.row), vals, open, node);
|
||||
const shownSet = new Set(shown);
|
||||
const tops = rowTops(shown);
|
||||
card.rowTop = new Map();
|
||||
card.rowSpan = new Map();
|
||||
shown.forEach((row, index) => {
|
||||
const entry = card.entries.find((item) => item.row === row);
|
||||
for (const name of entry.names ?? []) {
|
||||
card.rowTop.set(name, tops[index]);
|
||||
card.rowSpan.set(name, rowHeight(row));
|
||||
}
|
||||
if (entry.header) card.rowTop.set(`group:${row.group}`, tops[index]);
|
||||
});
|
||||
for (const entry of card.entries) {
|
||||
if (!entry.names || shownSet.has(entry.row) || !entry.row.inGroup) continue;
|
||||
const headerTop = card.rowTop.get(`group:${entry.row.inGroup}`);
|
||||
if (headerTop === undefined) continue;
|
||||
for (const name of entry.names) {
|
||||
card.rowTop.set(name, headerTop);
|
||||
card.rowSpan.set(name, GROUP_HEIGHT);
|
||||
}
|
||||
}
|
||||
for (const entry of card.entries) {
|
||||
const show = shownSet.has(entry.row);
|
||||
entry.element.classList.toggle("hidden", !show);
|
||||
if (entry.header) entry.element.classList.toggle("open", open[entry.row.group]);
|
||||
if (!show) continue;
|
||||
if (entry.row.panel && !entry.row.grow && typeof entry.row.height === "function") entry.element.style.height = `${rowHeight(entry.row)}px`;
|
||||
const linkedNames = (entry.names ?? []).filter((name) => widgetLinked(node, name));
|
||||
const linked = linkedNames.length > 0 && linkedNames.length === entry.names.length;
|
||||
entry.element.classList.toggle("linked", linked);
|
||||
for (const [name, field] of entry.fields ?? []) field.classList.toggle("linked", linkedNames.includes(name));
|
||||
for (const sync of entry.syncs) sync(vals, linked);
|
||||
}
|
||||
const height = cardHeight(shown);
|
||||
if (height !== card.height) {
|
||||
const change = card.height ? height - card.height : 0;
|
||||
card.height = height;
|
||||
// A row opened by hand moves the node's height with it, so a preview
|
||||
// under the card keeps its size; anything else keeps the node's height,
|
||||
// lifted to the floor.
|
||||
const current = Number(node.size?.[1]) || 0;
|
||||
const target = card.byHand && !card.restoring ? current + change : current;
|
||||
const floor = Number(node.computeSize?.()?.[1]) || 0;
|
||||
node.setSize?.([Math.max(minWidth, node.size?.[0] || minWidth), Math.max(floor, target)]);
|
||||
node.graph?.setDirtyCanvas?.(true, true);
|
||||
}
|
||||
node._widgetSlotsDirty = true;
|
||||
}
|
||||
card.refresh = refresh;
|
||||
// For a node that changes which rows show from its own controls (a tool
|
||||
// switch): the node's height follows the card, as for a group opened by hand.
|
||||
card.refreshByHand = () => {
|
||||
card.byHand = true;
|
||||
try {
|
||||
refresh();
|
||||
} finally {
|
||||
card.byHand = false;
|
||||
}
|
||||
};
|
||||
|
||||
for (const name of managed) {
|
||||
const target = findWidget(node, name);
|
||||
if (target) chainCallback(target, "callback", () => refresh());
|
||||
}
|
||||
chainCallback(node, "onConfigure", () => {
|
||||
card.restoring = true;
|
||||
queueMicrotask(() => {
|
||||
try {
|
||||
for (const name of managed) hideWidget(findWidget(node, name));
|
||||
refresh();
|
||||
} finally {
|
||||
card.restoring = false;
|
||||
}
|
||||
// A workflow saved before the card existed sized the node for the
|
||||
// stock widgets; give the card and its panels their floors.
|
||||
ensureNodeMinHeight(node);
|
||||
});
|
||||
});
|
||||
chainCallback(node, "onConnectionsChange", () => queueMicrotask(refresh));
|
||||
chainCallback(node, "onRemoved", () => {
|
||||
card.disposed = true;
|
||||
for (const restore of socketed) restore();
|
||||
if (typeof originalGetWidgetOnPos === "function") delete node.getWidgetOnPos;
|
||||
});
|
||||
|
||||
refresh();
|
||||
return card;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// Pure decisions behind card.js: which rows show, how tall the card is,
|
||||
// where each row sits and what control a widget gets. No DOM, for node:test.
|
||||
import { CARD_PADDING, GROUP_HEIGHT, ROW_GAP, ROW_HEIGHT, SECTION_HEIGHT } from "./theme.js";
|
||||
|
||||
// A widget input socket is drawn at the widget's y plus half a slot.
|
||||
export const SLOT_OFFSET = 10;
|
||||
const SEGMENT_MAX_OPTIONS = 4;
|
||||
const SEGMENT_MAX_CHARS = 26;
|
||||
|
||||
export const isGroupHeader = (row) => row.group !== undefined && row.widget === undefined && row.pair === undefined && !row.panel && !row.control && row.section === undefined;
|
||||
|
||||
// Rows the current values leave visible. `open` maps a group to its state.
|
||||
export function visibleRows(rows, values, open = {}, node = null) {
|
||||
return rows.filter((row) => {
|
||||
if (row.when && row.when(values, node) === false) return false;
|
||||
if (isGroupHeader(row)) return true;
|
||||
return !(row.inGroup && !open[row.inGroup]);
|
||||
});
|
||||
}
|
||||
|
||||
export function rowHeight(row) {
|
||||
if (row.section !== undefined) return SECTION_HEIGHT;
|
||||
if (row.panel) return Number(typeof row.height === "function" ? row.height() : row.height) || ROW_HEIGHT;
|
||||
if (isGroupHeader(row)) return GROUP_HEIGHT;
|
||||
return ROW_HEIGHT;
|
||||
}
|
||||
|
||||
export function cardHeight(rows) {
|
||||
if (!rows.length) return CARD_PADDING * 2;
|
||||
return CARD_PADDING * 2 + rows.reduce((sum, row) => sum + rowHeight(row), 0) + ROW_GAP * (rows.length - 1);
|
||||
}
|
||||
|
||||
export function rowTops(rows) {
|
||||
let y = CARD_PADDING;
|
||||
return rows.map((row) => {
|
||||
const top = y;
|
||||
y += rowHeight(row) + ROW_GAP;
|
||||
return top;
|
||||
});
|
||||
}
|
||||
|
||||
// The y a hidden widget reports so its socket sits level with its row.
|
||||
export function socketWidgetY(cardY, insetTop, rowTop, height) {
|
||||
return cardY + insetTop + rowTop + Math.min(height / 2, 13) - SLOT_OFFSET;
|
||||
}
|
||||
|
||||
export function segmentFits(labels) {
|
||||
if (labels.length < 2 || labels.length > SEGMENT_MAX_OPTIONS) return false;
|
||||
return labels.reduce((sum, label) => sum + String(label).length, 0) <= SEGMENT_MAX_CHARS;
|
||||
}
|
||||
|
||||
export function choiceLabel(row, value, values = [], node = null) {
|
||||
const own = typeof row?.labels === "function" ? row.labels(value, values, node) : row?.labels?.[value];
|
||||
return own ?? String(value);
|
||||
}
|
||||
|
||||
// Row kind from the widget it mirrors, unless the row names one.
|
||||
export function rowKind(row, widget, values = []) {
|
||||
if (row.kind) return row.kind;
|
||||
const type = String(widget?.type ?? "");
|
||||
if (type === "number" || type === "slider" || type === "INT" || type === "FLOAT") return "scrub";
|
||||
if (type === "combo" || type === "COMBO") return segmentFits(values.map((value) => choiceLabel(row, value, values))) ? "segment" : "select";
|
||||
if (type === "toggle" || type === "BOOLEAN") return "switch";
|
||||
return "text";
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Helpers that need the ComfyUI app.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
export function isVueNodes() {
|
||||
return globalThis.LiteGraph?.vueNodesMode === true;
|
||||
}
|
||||
|
||||
// One toast for every message; never alert(). Falls back to the console and
|
||||
// never throws, so a message cannot break the action that raised it.
|
||||
export function toast(detail, { severity = "info", summary = "", life = 5000 } = {}) {
|
||||
try {
|
||||
const store = app?.extensionManager?.toast;
|
||||
if (typeof store?.add === "function") {
|
||||
store.add({ severity, summary, detail, life });
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
// Fall through to the console.
|
||||
}
|
||||
(severity === "error" || severity === "warn" ? console.warn : console.log)(`${summary ? `${summary}: ` : ""}${detail}`);
|
||||
}
|
||||
|
||||
// The undo/dirty tracker snapshots on canvas mouse-up, but our DOM panels
|
||||
// commit values a phase later. Call once per user gesture, after the write,
|
||||
// and never from a workflow-load path.
|
||||
let changeTimer = null;
|
||||
export function notifyChange() {
|
||||
clearTimeout(changeTimer);
|
||||
changeTimer = setTimeout(() => {
|
||||
changeTimer = null;
|
||||
try {
|
||||
const workflow = app?.extensionManager?.workflow?.activeWorkflow;
|
||||
const tracker = workflow?.changeTracker;
|
||||
if (typeof tracker?.captureCanvasState === "function") tracker.captureCanvasState();
|
||||
else tracker?.checkState?.();
|
||||
} catch {
|
||||
// The write itself already succeeded.
|
||||
}
|
||||
}, 120);
|
||||
}
|
||||
Vendored
+337
@@ -0,0 +1,337 @@
|
||||
// Stand-alone controls for panels that are not card rows (a toolbar over a
|
||||
// preview, a modal footer). Card rows build on the same classes.
|
||||
import { chainCallback, chainHandler, el } from "./dom.js";
|
||||
|
||||
// button("Browse", { icon, title, primary, soft, danger, small, grow, onClick })
|
||||
// soft: the suite's blue action button (Save, New, More).
|
||||
export function button(label, { icon = "", title = "", primary = false, soft = false, danger = false, small = false, grow = false, onClick = null } = {}) {
|
||||
const node = el("button", "fbui-btn");
|
||||
node.type = "button";
|
||||
node.classList.toggle("primary", primary);
|
||||
node.classList.toggle("soft", soft);
|
||||
node.classList.toggle("danger", danger);
|
||||
node.classList.toggle("small", small);
|
||||
node.classList.toggle("grow", grow);
|
||||
// An icon alone is a square button the height of a row.
|
||||
node.classList.toggle("icon", Boolean(icon) && !label);
|
||||
if (icon) node.insertAdjacentHTML("beforeend", icon);
|
||||
if (label) node.append(el("span", "", label));
|
||||
if (title) node.title = title;
|
||||
if (onClick) node.addEventListener("click", (event) => onClick(event));
|
||||
return node;
|
||||
}
|
||||
|
||||
// The help popover: `lines` under (or over) `anchor`, a client-pixel box
|
||||
// { left, top, bottom }. It stays until a click outside it (or Esc), so the
|
||||
// text can be selected and copied; a click on a token copies that token.
|
||||
// `lines` are strings, or [code, text] pairs shown as a two-column list
|
||||
// (tokens and what they do). Returns close().
|
||||
export function openHelp(lines, anchor, { keep = null, onClose = null } = {}) {
|
||||
const pop = el("div", "fbui-pop");
|
||||
pop.tabIndex = -1;
|
||||
for (const line of lines) {
|
||||
if (Array.isArray(line)) {
|
||||
const row = el("div", "pair");
|
||||
const code = el("code", "", line[0]);
|
||||
code.title = "Click to copy";
|
||||
code.addEventListener("click", () => {
|
||||
navigator.clipboard?.writeText(line[0]).then(() => {
|
||||
code.classList.add("copied");
|
||||
setTimeout(() => code.classList.remove("copied"), 900);
|
||||
});
|
||||
});
|
||||
row.append(code, el("span", "", line[1]));
|
||||
pop.append(row);
|
||||
} else {
|
||||
pop.append(el("div", "", line));
|
||||
}
|
||||
}
|
||||
const close = () => {
|
||||
pop.remove();
|
||||
document.removeEventListener("pointerdown", outside, true);
|
||||
document.removeEventListener("keydown", onEscape, true);
|
||||
onClose?.();
|
||||
};
|
||||
// A press on `keep` (the control that opened it) is that control's to handle.
|
||||
const outside = (event) => {
|
||||
if (!pop.contains(event.target) && !keep?.contains(event.target)) close();
|
||||
};
|
||||
const onEscape = (event) => {
|
||||
if (event.key === "Escape") close();
|
||||
};
|
||||
// Keys typed here (Ctrl+C on a selection) are the popover's, not the canvas's.
|
||||
pop.addEventListener("keydown", (event) => event.stopPropagation());
|
||||
document.body.append(pop);
|
||||
pop.style.left = `${Math.max(8, Math.min(window.innerWidth - pop.offsetWidth - 8, anchor.left))}px`;
|
||||
const below = anchor.bottom + 6;
|
||||
pop.style.top = `${below + pop.offsetHeight > window.innerHeight - 8 ? Math.max(8, anchor.top - pop.offsetHeight - 6) : below}px`;
|
||||
pop.focus({ preventScroll: true });
|
||||
document.addEventListener("pointerdown", outside, true);
|
||||
document.addEventListener("keydown", onEscape, true);
|
||||
return close;
|
||||
}
|
||||
|
||||
// A small (i) beside a label; a click opens `lines` (see openHelp).
|
||||
export function info(lines) {
|
||||
const icon = el("span", "fbui-info");
|
||||
icon.innerHTML = ICONS.info;
|
||||
icon.title = "Help";
|
||||
let close = null;
|
||||
icon.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
if (close) return close();
|
||||
icon.classList.add("on");
|
||||
close = openHelp(lines, icon.getBoundingClientRect(), {
|
||||
keep: icon,
|
||||
onClose: () => {
|
||||
close = null;
|
||||
icon.classList.remove("on");
|
||||
},
|
||||
});
|
||||
});
|
||||
return icon;
|
||||
}
|
||||
|
||||
// The node's help as a "?" at the right of its title bar, where most packs
|
||||
// put it; a click opens `lines` (see openHelp). Nodes 2.0 draws no title
|
||||
// badges, so there it is "About this node" in the node's menu.
|
||||
const BADGE_INSET = 16;
|
||||
const BADGE_MIN_WIDTH = 140;
|
||||
|
||||
function badgeShown(node) {
|
||||
return !node.flags?.collapsed && (node.size?.[0] ?? 0) >= BADGE_MIN_WIDTH;
|
||||
}
|
||||
|
||||
export function helpBadge(node, lines) {
|
||||
const centerY = -(globalThis.LiteGraph?.NODE_TITLE_HEIGHT ?? 30) / 2;
|
||||
chainCallback(node, "onDrawForeground", function (ctx) {
|
||||
if (!badgeShown(this)) return;
|
||||
ctx.save();
|
||||
ctx.fillStyle = "rgba(255,255,255,0.9)";
|
||||
ctx.font = "bold 19px sans-serif";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText("?", this.size[0] - BADGE_INSET, centerY + 1);
|
||||
ctx.restore();
|
||||
});
|
||||
chainHandler(node, "onMouseDown", function (event, pos) {
|
||||
if (!badgeShown(this) || !pos) return false;
|
||||
if (Math.abs(pos[0] - (this.size[0] - BADGE_INSET)) > 10 || Math.abs(pos[1] - centerY) > 11) return false;
|
||||
openHelp(lines, { left: event.clientX - 150, top: event.clientY, bottom: event.clientY + 6 });
|
||||
// Consumed, so the click does not start a drag.
|
||||
return true;
|
||||
});
|
||||
chainCallback(node, "getExtraMenuOptions", function (_canvas, options) {
|
||||
if (!globalThis.LiteGraph?.vueNodesMode) return;
|
||||
options.unshift({ content: "About this node", callback: () => openHelp(lines, { left: window.innerWidth / 2 - 150, top: 80, bottom: 80 }) });
|
||||
});
|
||||
}
|
||||
|
||||
// A row of pill choices: segmented([{ value, label, title }], { onPick, bool })
|
||||
// -> { root, set(value) }.
|
||||
export function segmented(choices, { onPick, bool = false } = {}) {
|
||||
const root = el("div", bool ? "fbui-seg fbui-bool" : "fbui-seg");
|
||||
const buttons = new Map();
|
||||
for (const choice of choices) {
|
||||
const item = el("button", "", choice.label ?? String(choice.value));
|
||||
item.type = "button";
|
||||
item.title = choice.title ?? String(choice.label ?? choice.value);
|
||||
item.addEventListener("click", () => onPick?.(choice.value));
|
||||
root.append(item);
|
||||
buttons.set(choice.value, item);
|
||||
}
|
||||
return {
|
||||
root,
|
||||
set(value) {
|
||||
for (const [key, item] of buttons) item.classList.toggle("on", key === value);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// A slide handle (↔ or ↕) at the start of a row's fields: dragging it
|
||||
// reports the pointer's sideways travel for either axis, as every slider
|
||||
// here moves sideways (right is right, or down).
|
||||
export function slideHandle({ axis = "x", title = "", onStart, onSlide, onEnd } = {}) {
|
||||
const handle = el("span", "fbui-slide");
|
||||
handle.insertAdjacentHTML("beforeend", axis === "x" ? ICONS.slideX : ICONS.slideY);
|
||||
handle.title = title;
|
||||
handle.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
handle.setPointerCapture(event.pointerId);
|
||||
handle.classList.add("on");
|
||||
const zoom = handle.getBoundingClientRect().width / Math.max(1, handle.offsetWidth) || 1;
|
||||
const start = event.clientX;
|
||||
const move = (e) => onSlide?.((e.clientX - start) / zoom);
|
||||
const end = () => {
|
||||
handle.removeEventListener("pointermove", move);
|
||||
handle.removeEventListener("pointerup", end);
|
||||
handle.removeEventListener("pointercancel", end);
|
||||
handle.classList.remove("on");
|
||||
onEnd?.();
|
||||
};
|
||||
onStart?.();
|
||||
handle.addEventListener("pointermove", move);
|
||||
handle.addEventListener("pointerup", end);
|
||||
handle.addEventListener("pointercancel", end);
|
||||
});
|
||||
return handle;
|
||||
}
|
||||
|
||||
// A timeline rail with a playhead, for picking a frame: press or drag
|
||||
// anywhere on it. rail({ onSeek(fraction, settled) }) -> { root, set(fraction), setEnabled(on) }.
|
||||
// `fraction` is 0..1 along the rail; the caller maps it to its own frames.
|
||||
export function rail({ onSeek, title = "" } = {}) {
|
||||
const root = el("div", "fbui-rail");
|
||||
const fill = el("div", "fbui-rail-fill");
|
||||
const head = el("div", "fbui-rail-head");
|
||||
root.append(fill, head);
|
||||
if (title) root.title = title;
|
||||
let enabled = true;
|
||||
const at = (event) => {
|
||||
const box = root.getBoundingClientRect();
|
||||
return Math.max(0, Math.min(1, (event.clientX - box.left) / Math.max(1, box.width)));
|
||||
};
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
if (!enabled || event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
root.setPointerCapture(event.pointerId);
|
||||
onSeek?.(at(event), false);
|
||||
});
|
||||
root.addEventListener("pointermove", (event) => {
|
||||
if (root.hasPointerCapture(event.pointerId)) onSeek?.(at(event), false);
|
||||
});
|
||||
const end = (event) => {
|
||||
if (!root.hasPointerCapture(event.pointerId)) return;
|
||||
root.releasePointerCapture(event.pointerId);
|
||||
onSeek?.(at(event), true);
|
||||
};
|
||||
root.addEventListener("pointerup", end);
|
||||
root.addEventListener("pointercancel", end);
|
||||
return {
|
||||
root,
|
||||
set(fraction) {
|
||||
const pct = `${Math.max(0, Math.min(1, fraction)) * 100}%`;
|
||||
head.style.left = pct;
|
||||
fill.style.width = pct;
|
||||
},
|
||||
setEnabled(on) {
|
||||
enabled = on;
|
||||
root.classList.toggle("disabled", !on);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// A rail with in and out edges and a playhead, for trimming: press near an
|
||||
// edge to move it, anywhere else to move the playhead.
|
||||
// rangeRail({ onEdge(edge, fraction, settled), onSeek(fraction, settled) })
|
||||
// -> { root, set({ start, stop, head }) } with edge "in" | "out", all 0..1.
|
||||
export function rangeRail({ onEdge, onSeek, title = "" } = {}) {
|
||||
const root = el("div", "fbui-rail fbui-range");
|
||||
const fill = el("div", "fbui-range-fill");
|
||||
const edgeIn = el("div", "fbui-range-edge");
|
||||
const edgeOut = el("div", "fbui-range-edge");
|
||||
const head = el("div", "fbui-rail-head");
|
||||
root.append(fill, edgeIn, edgeOut, head);
|
||||
if (title) root.title = title;
|
||||
let shown = { start: 0, stop: 1, head: 0 };
|
||||
let drag = null;
|
||||
const at = (event) => {
|
||||
const box = root.getBoundingClientRect();
|
||||
return Math.max(0, Math.min(1, (event.clientX - box.left) / Math.max(1, box.width)));
|
||||
};
|
||||
const send = (event, settled) => {
|
||||
if (drag === "head") onSeek?.(at(event), settled);
|
||||
else onEdge?.(drag, at(event), settled);
|
||||
};
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
root.setPointerCapture(event.pointerId);
|
||||
// The nearer edge within 8px; on top of each other, the side pressed.
|
||||
const width = root.getBoundingClientRect().width;
|
||||
const x = at(event);
|
||||
const toIn = Math.abs(x - shown.start) * width;
|
||||
const toOut = Math.abs(x - shown.stop) * width;
|
||||
drag = Math.min(toIn, toOut) > 8 ? "head" : toIn < toOut || (toIn === toOut && x < shown.start) ? "in" : "out";
|
||||
send(event, false);
|
||||
});
|
||||
root.addEventListener("pointermove", (event) => {
|
||||
if (drag && root.hasPointerCapture(event.pointerId)) send(event, false);
|
||||
});
|
||||
const end = (event) => {
|
||||
if (!drag || !root.hasPointerCapture(event.pointerId)) return;
|
||||
root.releasePointerCapture(event.pointerId);
|
||||
send(event, true);
|
||||
drag = null;
|
||||
};
|
||||
root.addEventListener("pointerup", end);
|
||||
root.addEventListener("pointercancel", end);
|
||||
const pct = (fraction) => `${Math.max(0, Math.min(1, fraction)) * 100}%`;
|
||||
return {
|
||||
root,
|
||||
set(next) {
|
||||
shown = { ...shown, ...next };
|
||||
fill.style.left = pct(shown.start);
|
||||
fill.style.width = pct(shown.stop - shown.start);
|
||||
edgeIn.style.left = pct(shown.start);
|
||||
edgeOut.style.left = pct(shown.stop);
|
||||
head.style.left = pct(shown.head);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Small stroke icons, drawn in currentColor so they follow the button state.
|
||||
const svg = (body) => `<svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${body}</svg>`;
|
||||
export const ICONS = {
|
||||
folder: svg('<path d="M1.5 4.5v8a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-6a1 1 0 0 0-1-1H8L6.5 3.5h-4a1 1 0 0 0-1 1z"/>'),
|
||||
play: svg('<path d="M5 3.5v9l7-4.5z" fill="currentColor"/>'),
|
||||
pause: svg('<path d="M5 3.5v9M11 3.5v9"/>'),
|
||||
expand: svg('<path d="M10 2.5h3.5V6M6 13.5H2.5V10M13.5 2.5 9 7M2.5 13.5 7 9"/>'),
|
||||
brush: svg('<path d="M10.5 2.5l3 3-6 6-3-3zM4.5 8.5l-2 5 5-2"/>'),
|
||||
crop: svg('<path d="M4 1.5V12h10.5M1.5 4H12v10.5"/>'),
|
||||
feather: svg('<path d="M13.5 2.5C8 2.5 4.5 6 4.5 11.5h2c5.5 0 7-4 7-9z"/><path d="M2.5 13.5l7-7"/>'),
|
||||
ratio: svg('<rect x="1.5" y="3.5" width="13" height="9" rx="1"/><path d="M4.5 8.5v-2H7M11.5 7.5v2H9"/>'),
|
||||
slideX: svg('<path d="M1.5 8h13M4.5 5 1.5 8l3 3M11.5 5l3 3-3 3"/>'),
|
||||
slideY: svg('<path d="M8 1.5v13M5 4.5 8 1.5l3 3M5 11.5l3 3 3-3"/>'),
|
||||
centerX: svg('<path d="M2 3v10M14 3v10M8 5v6M5 8H4M12 8h-1"/>'),
|
||||
centerY: svg('<path d="M3 2h10M3 14h10M5 8h6M8 5V4M8 12v-1"/>'),
|
||||
pad: svg('<rect x="5.5" y="5.5" width="5" height="5" rx=".5"/><path d="M1.5 5V1.5H5M11 1.5h3.5V5M14.5 11v3.5H11M5 14.5H1.5V11"/>'),
|
||||
rotate: svg('<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3"/><rect x="6" y="6" width="4" height="4" rx=".5"/>'),
|
||||
rotateLeft: svg('<path d="M2.5 5.5h7a4 4 0 0 1 0 8h-2M5 3 2.5 5.5 5 8"/>'),
|
||||
rotateRight: svg('<path d="M13.5 5.5h-7a4 4 0 0 0 0 8h2M11 3l2.5 2.5L11 8"/>'),
|
||||
cropTurn: svg('<path d="M4 1.5V10h6M1.5 4H10v2"/><path d="M14.5 11a3.5 3.5 0 1 1-1-2.5M14.5 7v2h-2"/>'),
|
||||
scale: svg('<rect x="1.5" y="8.5" width="6" height="6" rx=".5"/><path d="M9.5 1.5h5v5M14.5 1.5 8.5 7.5"/>'),
|
||||
eraser: svg('<path d="M6 13.5h7.5M2.5 10l6-6.5 5 5-5 5h-3z"/>'),
|
||||
undo: svg('<path d="M4.5 6.5h6a3 3 0 0 1 0 6h-3M6.5 4l-2.5 2.5L6.5 9"/>'),
|
||||
redo: svg('<path d="M11.5 6.5h-6a3 3 0 0 0 0 6h3M9.5 4l2.5 2.5L9.5 9"/>'),
|
||||
trash: svg('<path d="M2.5 4.5h11M6 4.5V3h4v1.5M4 4.5l.7 9h6.6l.7-9"/>'),
|
||||
flipX: svg('<path d="M8 1.5v13M6 4 2 12h4zM10 4l4 8h-4z"/>'),
|
||||
flipY: svg('<path d="M1.5 8h13M4 6 12 2v4zM4 10l8 4v-4z"/>'),
|
||||
reset: svg('<path d="M2.5 8a5.5 5.5 0 1 0 1.6-3.9M2.5 2.5v3h3"/>'),
|
||||
close: svg('<path d="M3.5 3.5l9 9M12.5 3.5l-9 9"/>'),
|
||||
invert: svg('<circle cx="8" cy="8" r="5.5"/><path d="M8 2.5v11a5.5 5.5 0 0 0 0-11z" fill="currentColor"/>'),
|
||||
eye: svg('<path d="M1.5 8S4 3.5 8 3.5 14.5 8 14.5 8 12 12.5 8 12.5 1.5 8 1.5 8z"/><circle cx="8" cy="8" r="1.8"/>'),
|
||||
info: svg('<circle cx="8" cy="8" r="6.5"/><path d="M8 7.2V11.5M8 4.6v.1"/>'),
|
||||
open: svg('<path d="M9.5 2.5h4v4M13.5 2.5 8 8M11.5 9.5v3a1 1 0 0 1-1 1h-7a1 1 0 0 1-1-1v-7a1 1 0 0 1 1-1h3"/>'),
|
||||
up: svg('<path d="M8 13.5v-11M3.5 7 8 2.5 12.5 7"/>'),
|
||||
refresh: svg('<path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2.5v3h-3"/>'),
|
||||
chevronUp: svg('<path d="M3.5 10 8 5.5l4.5 4.5"/>'),
|
||||
chevronLeft: svg('<path d="M10 3.5 5.5 8l4.5 4.5"/>'),
|
||||
chevronRight: svg('<path d="M6 3.5 10.5 8 6 12.5"/>'),
|
||||
check: svg('<path d="M3 8.5 6.5 12 13 4.5"/>'),
|
||||
grip: svg('<g fill="currentColor" stroke="none"><circle cx="6" cy="4" r="1.1"/><circle cx="10" cy="4" r="1.1"/><circle cx="6" cy="8" r="1.1"/><circle cx="10" cy="8" r="1.1"/><circle cx="6" cy="12" r="1.1"/><circle cx="10" cy="12" r="1.1"/></g>'),
|
||||
scissors: svg('<circle cx="4" cy="4.5" r="2"/><circle cx="4" cy="11.5" r="2"/><path d="M5.7 5.6 13.5 12M5.7 10.4 13.5 4"/>'),
|
||||
timer: svg('<circle cx="8" cy="9" r="5.5"/><path d="M8 6v3l2 1.5M6.5 1.5h3"/>'),
|
||||
chevronDown: svg('<path d="M3.5 6 8 10.5 12.5 6"/>'),
|
||||
grid: svg('<rect x="2" y="2" width="5" height="5" rx="1"/><rect x="9" y="2" width="5" height="5" rx="1"/><rect x="2" y="9" width="5" height="5" rx="1"/><rect x="9" y="9" width="5" height="5" rx="1"/>'),
|
||||
tiles: svg('<path d="M2 2h3v3H2zM6.5 2h3v3h-3zM11 2h3v3h-3zM2 6.5h3v3H2zM6.5 6.5h3v3h-3zM11 6.5h3v3h-3zM2 11h3v3H2zM6.5 11h3v3h-3zM11 11h3v3h-3z"/>'),
|
||||
list: svg('<path d="M5.5 4h8M5.5 8h8M5.5 12h8M2.5 4h.5M2.5 8h.5M2.5 12h.5"/>'),
|
||||
search: svg('<circle cx="7" cy="7" r="4.5"/><path d="M10.5 10.5 14 14"/>'),
|
||||
film: svg('<rect x="2" y="3" width="12" height="10" rx="1.5"/><path d="M5 3v10M11 3v10M2 6h3M2 10h3M11 6h3M11 10h3"/>'),
|
||||
music: svg('<path d="M6 12V3.5l7.5-1.5V10.5"/><circle cx="4.5" cy="12" r="1.8"/><circle cx="12" cy="10.5" r="1.8"/>'),
|
||||
file: svg('<path d="M4 1.5h5.5L13 5v9.5H4zM9.5 1.5V5H13"/>'),
|
||||
};
|
||||
@@ -0,0 +1,52 @@
|
||||
// Plain DOM and LiteGraph-object helpers. No imports, so node:test can load
|
||||
// everything that builds on them.
|
||||
|
||||
export function el(tag, className = "", text) {
|
||||
const node = document.createElement(tag);
|
||||
if (className) node.className = className;
|
||||
if (text !== undefined) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
// Wrap a callback without clobbering whoever hooked it first. Other packs
|
||||
// patch the same objects, so never assign `obj[name] = fn` directly.
|
||||
export function chainCallback(obj, name, fn) {
|
||||
const prior = obj[name];
|
||||
obj[name] = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
fn.apply(this, args);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
// chainCallback for handlers whose truthy return means "consumed".
|
||||
export function chainHandler(obj, name, fn) {
|
||||
const prior = obj[name];
|
||||
obj[name] = function (...args) {
|
||||
const result = prior?.apply(this, args);
|
||||
const handled = fn.apply(this, args);
|
||||
return result || handled;
|
||||
};
|
||||
}
|
||||
|
||||
// The frontend sizes a DOM widget's wrapper as `widget.width ?? node.width`,
|
||||
// and LiteGraph plants widget.width during draws, after which the wrapper no
|
||||
// longer follows the node when it is resized narrower. Discard those writes.
|
||||
export function keepDomWidgetWidthAuto(widget) {
|
||||
if (!widget) return widget;
|
||||
try {
|
||||
Object.defineProperty(widget, "width", { get: () => undefined, set: () => {}, configurable: true });
|
||||
} catch {
|
||||
// A frozen widget keeps the frontend's behaviour.
|
||||
}
|
||||
return widget;
|
||||
}
|
||||
|
||||
// App shortcuts (Ctrl+Enter, Ctrl+S) go on to ComfyUI; every other key typed
|
||||
// in one of our fields stays in the field so the canvas never acts on it.
|
||||
const FIELD_EDIT_KEYS = new Set(["a", "c", "v", "x", "z", "y", "backspace", "delete", "arrowleft", "arrowright", "arrowup", "arrowdown", "home", "end"]);
|
||||
|
||||
export function keepKeyInField(event) {
|
||||
const appShortcut = (event.ctrlKey || event.metaKey) && !FIELD_EDIT_KEYS.has(String(event.key ?? "").toLowerCase());
|
||||
if (!appShortcut) event.stopPropagation();
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// How a DOM panel claims its share of a node's height, in both renderers.
|
||||
// No imports, so node:test can load it.
|
||||
//
|
||||
// The classic frontend arranges widgets in one pass:
|
||||
// if (w.computeSize) -> fixed height, kept out of the split
|
||||
// else if (w.computeLayoutSize) -> shares the node's free height
|
||||
// so a growing panel must not carry a computeSize, and a fixed one should.
|
||||
//
|
||||
// DomWidgets insets an element by options.margin per side (default 10), so
|
||||
// the element gets this much less height than the layout hands the widget.
|
||||
export const WIDGET_FRAME = 20;
|
||||
|
||||
const resolve = (value) => {
|
||||
const number = Number(typeof value === "function" ? value() : value);
|
||||
return Number.isFinite(number) ? Math.max(0, number) : 0;
|
||||
};
|
||||
|
||||
// The frontend pads a DOM widget's minWidth before it becomes the node's
|
||||
// floor (the room a number widget's value box takes). Measure that padding
|
||||
// once from the frontend itself instead of copying its constants.
|
||||
const PROBE_WIDTH = 100000;
|
||||
let probing = false;
|
||||
let widthPadding = null;
|
||||
|
||||
function measureWidthPadding(node, widget) {
|
||||
if (probing || typeof node?.computeSize !== "function") return null;
|
||||
const own = widget.computeLayoutSize;
|
||||
probing = true;
|
||||
widget.computeLayoutSize = () => ({ minWidth: PROBE_WIDTH, minHeight: 0 });
|
||||
let width = NaN;
|
||||
try {
|
||||
width = Number(node.computeSize()?.[0]);
|
||||
} catch {
|
||||
// Measured next time.
|
||||
} finally {
|
||||
widget.computeLayoutSize = own;
|
||||
probing = false;
|
||||
}
|
||||
return Number.isFinite(width) && width >= PROBE_WIDTH ? width - PROBE_WIDTH : null;
|
||||
}
|
||||
|
||||
// A node can carry several panels; its width floor is the widest of them.
|
||||
const FLOORS = Symbol.for("fbui.widthFloors");
|
||||
|
||||
function nodeWidthFloor(node) {
|
||||
let floor = 0;
|
||||
for (const value of node?.[FLOORS]?.values() ?? []) floor = Math.max(floor, resolve(value));
|
||||
return floor;
|
||||
}
|
||||
|
||||
// Nodes 2.0 lays a node out by its content and has no layout API for
|
||||
// minimums: lend it the floors as inline CSS on the node element and panel.
|
||||
function holdVueMinWidth(panel, width) {
|
||||
const host = panel?.closest?.("[data-node-id]");
|
||||
if (!host?.style || !(width > 0)) return;
|
||||
const css = `${Math.round(width)}px`;
|
||||
if (host.style.minWidth !== css) host.style.minWidth = css;
|
||||
}
|
||||
|
||||
function holdVueMinHeight(panel, height) {
|
||||
if (!panel?.style) return;
|
||||
const inside = Boolean(panel.closest?.("[data-node-id]"));
|
||||
const css = inside && height > 0 ? `${Math.round(height)}px` : "";
|
||||
if ((panel.style.minHeight || "") !== css) panel.style.minHeight = css;
|
||||
}
|
||||
|
||||
// One ResizeObserver per panel; the Vue node element only exists around a
|
||||
// panel once it has been laid out inside it.
|
||||
const WATCHED = Symbol.for("fbui.layoutWatch");
|
||||
function whenLaidOut(panel, name, task) {
|
||||
if (!panel || typeof ResizeObserver !== "function") return;
|
||||
if (!panel[WATCHED]) {
|
||||
const tasks = new Map();
|
||||
panel[WATCHED] = tasks;
|
||||
new ResizeObserver(() => { for (const run of tasks.values()) run(); }).observe(panel);
|
||||
}
|
||||
panel[WATCHED].set(name, task);
|
||||
}
|
||||
|
||||
// Make `minWidth` a real floor for the node in both renderers: the classic
|
||||
// corner drag stops at node.computeSize(), Nodes 2.0 at the host's min-width.
|
||||
export function holdNodeMinWidth(widget, minWidth) {
|
||||
const node = widget?.node;
|
||||
if (!node) return widget;
|
||||
if (!node[FLOORS]) {
|
||||
node[FLOORS] = new Map();
|
||||
const inherited = node.computeSize;
|
||||
node.computeSize = function (out) {
|
||||
const size = inherited.call(this, out);
|
||||
const floor = nodeWidthFloor(this);
|
||||
if (size && size[0] < floor) size[0] = floor;
|
||||
return size;
|
||||
};
|
||||
}
|
||||
node[FLOORS].set(widget, minWidth);
|
||||
whenLaidOut(widget.element, "width", () => holdVueMinWidth(widget.element, nodeWidthFloor(node)));
|
||||
return widget;
|
||||
}
|
||||
|
||||
// A panel that takes whatever height the node has left over (a preview).
|
||||
export function fillNodeHeight(widget, { minWidth = 0, minHeight = 0 } = {}) {
|
||||
if (!widget) return widget;
|
||||
const panel = widget.element;
|
||||
const holdHeight = (height) => holdVueMinHeight(panel, height - WIDGET_FRAME);
|
||||
delete widget.computeSize;
|
||||
widget.computeLayoutSize = (node) => {
|
||||
const height = resolve(minHeight);
|
||||
holdHeight(height);
|
||||
if (widthPadding === null) widthPadding = measureWidthPadding(node ?? widget.node, widget);
|
||||
return { minWidth: Math.max(0, resolve(minWidth) - (widthPadding ?? 0)), minHeight: height };
|
||||
};
|
||||
holdNodeMinWidth(widget, minWidth);
|
||||
whenLaidOut(panel, "height", () => holdHeight(resolve(minHeight)));
|
||||
return widget;
|
||||
}
|
||||
|
||||
// A panel that keeps its own height (a card whose height is its rows).
|
||||
// Nodes 2.0 gives any widget with a computeLayoutSize a share of the spare
|
||||
// height, and every DOM widget inherits one, so shadow it.
|
||||
export function pinHeight(widget, height, minWidth = 0) {
|
||||
if (!widget) return widget;
|
||||
widget.computeSize = (width) => [Math.max(minWidth, Number(width) || 0), resolve(height)];
|
||||
widget.computeLayoutSize = undefined;
|
||||
if (minWidth) holdNodeMinWidth(widget, minWidth);
|
||||
return widget;
|
||||
}
|
||||
|
||||
// Grow a node to the height its widgets ask for: a workflow saved before a
|
||||
// panel existed carries the node's old, smaller size.
|
||||
export function ensureNodeMinHeight(node) {
|
||||
const min = Number(node?.computeSize?.()?.[1]);
|
||||
const current = Number(node?.size?.[1]);
|
||||
if (!Number.isFinite(min) || !Number.isFinite(current) || current >= min) return false;
|
||||
node.setSize?.([node.size[0], min]);
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
// Modals and context menus in the kit's look. One backdrop, one z-index
|
||||
// scale, Escape and a click outside close, and keys typed inside stay out of
|
||||
// the canvas.
|
||||
import { el } from "./dom.js";
|
||||
import { button, ICONS } from "./controls.js";
|
||||
import { ensureKitCss, T, Z_MODAL } from "./theme.js";
|
||||
|
||||
// Open modals, newest last: Escape closes only the top one.
|
||||
const stack = [];
|
||||
|
||||
// Whether a kit modal, menu or viewer is open: node shortcuts stand aside.
|
||||
export const modalOpen = () => stack.length > 0;
|
||||
|
||||
// openModal({ title, body, footer, width, height, closable, onClose }) -> { overlay, modal, body, close, isTop }.
|
||||
// `body` and `footer` are elements (or arrays of elements). closable: false
|
||||
// takes away the close button, Escape and the backdrop click, for a dialog
|
||||
// that must end with one of its own buttons.
|
||||
export function openModal({ title = "", body = null, footer = null, width = null, height = null, closable = true, onClose = null } = {}) {
|
||||
ensureKitCss();
|
||||
const overlay = el("div", "fbui-overlay");
|
||||
const modal = el("div", "fbui-modal");
|
||||
const size = (value) => (typeof value === "number" ? `${value}px` : value);
|
||||
if (width) modal.style.width = size(width);
|
||||
if (height) modal.style.height = size(height);
|
||||
const head = el("div", "fbui-modal-head");
|
||||
head.append(el("span", "title", title));
|
||||
const close = () => {
|
||||
if (!overlay.isConnected) return;
|
||||
overlay.remove();
|
||||
stack.splice(stack.indexOf(close), 1);
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
onClose?.();
|
||||
};
|
||||
if (closable) head.append(button("", { icon: ICONS.close, small: true, title: "Close (Esc)", onClick: close }));
|
||||
modal.append(head);
|
||||
const content = el("div", "fbui-modal-body");
|
||||
for (const item of [body].flat()) if (item) content.append(item);
|
||||
modal.append(content);
|
||||
if (footer) {
|
||||
const foot = el("div", "fbui-modal-foot");
|
||||
for (const item of [footer].flat()) if (item) foot.append(item);
|
||||
modal.append(foot);
|
||||
}
|
||||
overlay.append(modal);
|
||||
const onKey = (event) => {
|
||||
if (!closable || event.key !== "Escape" || stack[stack.length - 1] !== close) return;
|
||||
event.stopPropagation();
|
||||
close();
|
||||
};
|
||||
overlay.addEventListener("pointerdown", (event) => {
|
||||
if (closable && event.target === overlay) close();
|
||||
});
|
||||
overlay.addEventListener("keydown", (event) => event.stopPropagation());
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
document.body.append(overlay);
|
||||
stack.push(close);
|
||||
return { overlay, modal, body: content, close, isTop: () => stack[stack.length - 1] === close };
|
||||
}
|
||||
|
||||
// prompt({ title, message, value, placeholder, confirmText }) -> Promise<string | null>:
|
||||
// the trimmed text on OK or Enter, null on Cancel or Escape.
|
||||
export function prompt({ title = "", message = "", value = "", placeholder = "", confirmText = "OK" } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let answer = null;
|
||||
const field = el("input", "fbui-text");
|
||||
field.type = "text";
|
||||
field.spellcheck = false;
|
||||
field.value = value;
|
||||
field.placeholder = placeholder;
|
||||
field.style.width = "min(520px, 70vw)";
|
||||
const text = el("div", "", message);
|
||||
text.style.cssText = "margin-bottom:8px;max-width:520px;line-height:1.45;color:" + T.label;
|
||||
const accept = () => {
|
||||
answer = field.value.trim() || null;
|
||||
dialog.close();
|
||||
};
|
||||
field.addEventListener("keydown", (event) => {
|
||||
if (event.key === "Enter") accept();
|
||||
});
|
||||
const dialog = openModal({
|
||||
title,
|
||||
body: [message ? text : null, field],
|
||||
footer: [button("Cancel", { onClick: () => dialog.close() }), button(confirmText, { primary: true, onClick: accept })],
|
||||
onClose: () => resolve(answer),
|
||||
});
|
||||
dialog.overlay.style.zIndex = String(Z_MODAL + stack.length);
|
||||
field.focus();
|
||||
field.select();
|
||||
});
|
||||
}
|
||||
|
||||
// confirm({ title, message, confirmText, danger }) -> Promise<boolean>.
|
||||
export function confirm({ title = "Are you sure?", message = "", confirmText = "OK", danger = false } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let answer = false;
|
||||
const text = el("div", "", message);
|
||||
text.style.cssText = "max-width:420px;line-height:1.45";
|
||||
const cancel = button("Cancel", { onClick: () => dialog.close() });
|
||||
const ok = button(confirmText, { primary: !danger, danger, onClick: () => { answer = true; dialog.close(); } });
|
||||
if (danger) ok.style.background = T.danger;
|
||||
const dialog = openModal({ title, body: text, footer: [cancel, ok], onClose: () => resolve(answer) });
|
||||
dialog.overlay.style.zIndex = String(Z_MODAL + stack.length);
|
||||
ok.focus();
|
||||
});
|
||||
}
|
||||
|
||||
// openMenu(clientX, clientY, [{ label, action, disabled, danger } | null]) at
|
||||
// the pointer (null: a separator), kept inside the viewport; closes on pick
|
||||
// or any outside press.
|
||||
export function openMenu(x, y, items) {
|
||||
ensureKitCss();
|
||||
document.querySelector(".fbui-menu")?.remove();
|
||||
const menu = el("div", "fbui-menu");
|
||||
const close = () => {
|
||||
menu.remove();
|
||||
document.removeEventListener("pointerdown", outside, true);
|
||||
};
|
||||
const outside = (event) => {
|
||||
if (menu.contains(event.target)) return;
|
||||
close();
|
||||
// The press that closes the menu must not also click what is under it.
|
||||
const swallow = (click) => {
|
||||
click.stopPropagation();
|
||||
click.preventDefault();
|
||||
};
|
||||
document.addEventListener("click", swallow, { capture: true, once: true });
|
||||
setTimeout(() => document.removeEventListener("click", swallow, true), 400);
|
||||
};
|
||||
for (const item of items) {
|
||||
// null: a separator between groups of items.
|
||||
if (!item) {
|
||||
menu.append(el("div", "sep"));
|
||||
continue;
|
||||
}
|
||||
const entry = el("button", item.danger ? "danger" : "", item.label);
|
||||
entry.type = "button";
|
||||
entry.disabled = Boolean(item.disabled);
|
||||
if (item.disabled) entry.style.opacity = ".45";
|
||||
entry.addEventListener("click", () => {
|
||||
close();
|
||||
item.action?.();
|
||||
});
|
||||
menu.append(entry);
|
||||
}
|
||||
menu.style.left = `${x}px`;
|
||||
menu.style.top = `${y}px`;
|
||||
document.body.append(menu);
|
||||
const rect = menu.getBoundingClientRect();
|
||||
if (rect.right > window.innerWidth) menu.style.left = `${Math.max(0, x - rect.width)}px`;
|
||||
if (rect.bottom > window.innerHeight) menu.style.top = `${Math.max(0, y - rect.height)}px`;
|
||||
setTimeout(() => document.addEventListener("pointerdown", outside, true), 0);
|
||||
return { menu, close };
|
||||
}
|
||||
|
||||
// openViewer([{ url, title, video?, fallback?, where? }], index, { step? }):
|
||||
// the picture (or video) as large as the screen allows over a darkened
|
||||
// ComfyUI. ←/→ and the ‹ › buttons step through several (while a video
|
||||
// plays the keys seek it instead), Esc or a click on the dark closes. `fallback` is an image URL shown when the browser cannot
|
||||
// play a video. With `step(direction)` the caller does the stepping instead
|
||||
// and returns the item to show (null to stay); `where` labels its position.
|
||||
export function openViewer(items, index = 0, { step = null } = {}) {
|
||||
ensureKitCss();
|
||||
if (!items.length) return;
|
||||
const root = el("div", "fbui-viewer");
|
||||
const stage = el("div", "stage");
|
||||
const name = el("div", "name");
|
||||
const where = el("div", "where");
|
||||
const close = () => {
|
||||
root.remove();
|
||||
stack.splice(stack.indexOf(close), 1);
|
||||
document.removeEventListener("keydown", onKey, true);
|
||||
};
|
||||
const prev = button("", { icon: ICONS.chevronLeft, title: "Previous (←)", onClick: () => move(-1) });
|
||||
const next = button("", { icon: ICONS.chevronRight, title: "Next (→)", onClick: () => move(1) });
|
||||
prev.classList.add("nav", "prev");
|
||||
next.classList.add("nav", "next");
|
||||
const shut = button("", { icon: ICONS.close, title: "Close (Esc)", onClick: close });
|
||||
shut.classList.add("shut");
|
||||
let at = 0;
|
||||
function show(next) {
|
||||
at = (next + items.length) % items.length;
|
||||
const item = items[at];
|
||||
let media;
|
||||
if (item.video) {
|
||||
media = el("video");
|
||||
Object.assign(media, { controls: true, autoplay: true, loop: true, playsInline: true, src: item.url });
|
||||
if (item.fallback) {
|
||||
media.addEventListener("error", () => {
|
||||
const still = el("img");
|
||||
still.src = item.fallback;
|
||||
media.replaceWith(still);
|
||||
});
|
||||
}
|
||||
} else {
|
||||
media = el("img");
|
||||
media.src = item.url;
|
||||
media.draggable = false;
|
||||
}
|
||||
stage.replaceChildren(media);
|
||||
// Focused, a video takes ← / → itself (seeking) and Space.
|
||||
if (item.video) media.focus({ preventScroll: true });
|
||||
name.textContent = item.title ?? "";
|
||||
name.title = item.title ?? "";
|
||||
where.textContent = item.where ?? `${at + 1} / ${items.length}`;
|
||||
where.hidden = !where.textContent || (!step && items.length < 2);
|
||||
}
|
||||
function move(direction) {
|
||||
if (!step) return show(at + direction);
|
||||
const item = step(direction);
|
||||
if (!item) return;
|
||||
items = [item];
|
||||
show(0);
|
||||
}
|
||||
const onKey = (event) => {
|
||||
if (stack[stack.length - 1] !== close) return;
|
||||
if (event.key === "Escape") close();
|
||||
else if (stage.firstChild?.tagName === "VIDEO" && (event.key === "ArrowLeft" || event.key === "ArrowRight")) return;
|
||||
else if ((step || items.length > 1) && (event.key === "ArrowLeft" || event.key === "ArrowRight")) move(event.key === "ArrowRight" ? 1 : -1);
|
||||
else return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
};
|
||||
root.addEventListener("pointerdown", (event) => {
|
||||
if (event.target === root || event.target === stage) close();
|
||||
});
|
||||
prev.hidden = next.hidden = !step && items.length < 2;
|
||||
root.append(stage, name, where, shut, prev, next);
|
||||
document.body.append(root);
|
||||
document.addEventListener("keydown", onKey, true);
|
||||
stack.push(close);
|
||||
show(index);
|
||||
return { close };
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
// Graph zoom and pan over our panels, and files dropped on them.
|
||||
//
|
||||
// A panel that takes the mouse also swallows the wheel, so the graph stopped
|
||||
// zooming the moment the pointer crossed a card or preview. One listener hands
|
||||
// those gestures back to the canvas, unless the element under the pointer can
|
||||
// still scroll that way. In the classic renderer a file dropped on a panel
|
||||
// missed its node; the drop listeners hand it to the node under the pointer.
|
||||
//
|
||||
// Every pack carrying the kit calls installPassthrough(); the first one wins,
|
||||
// and it serves the `fbui-` panels of all of them.
|
||||
import { app } from "../../../scripts/app.js";
|
||||
|
||||
const INSTALLED = Symbol.for("fbui.passthrough");
|
||||
const WRAPPERS = ".dom-widget, .lg-node-widgets";
|
||||
const isOurs = (element) => typeof element?.className === "string" && element.className.includes("fbui-");
|
||||
|
||||
function panelRoot(target) {
|
||||
const host = target?.closest?.(WRAPPERS);
|
||||
if (!host) return null;
|
||||
let root = null;
|
||||
for (let element = target; element && element !== host; element = element.parentElement) if (isOurs(element)) root = element;
|
||||
if (!root && target === host && host.matches(".dom-widget")) root = Array.from(host.children).find(isOurs) ?? null;
|
||||
return root;
|
||||
}
|
||||
|
||||
function canScroll(element, delta, horizontal) {
|
||||
if (!delta) return false;
|
||||
const size = horizontal ? element.scrollWidth : element.scrollHeight;
|
||||
const visible = horizontal ? element.clientWidth : element.clientHeight;
|
||||
const start = horizontal ? element.scrollLeft : element.scrollTop;
|
||||
if (size - visible <= 1) return false;
|
||||
return delta > 0 ? start + visible < size - 1 : start > 0;
|
||||
}
|
||||
|
||||
function panelKeepsWheel(target, event, root) {
|
||||
if (event.ctrlKey || event.metaKey) return false;
|
||||
for (let element = target; element && element !== root.parentElement; element = element.parentElement) {
|
||||
const style = getComputedStyle(element);
|
||||
if (/(auto|scroll)/.test(style.overflowY) && canScroll(element, event.deltaY, false)) return true;
|
||||
if (/(auto|scroll)/.test(style.overflowX) && canScroll(element, event.deltaX, true)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
let forwardedPointer = null;
|
||||
|
||||
function onWheel(event) {
|
||||
const root = panelRoot(event.target);
|
||||
if (!root || !app.canvas || event.defaultPrevented || panelKeepsWheel(event.target, event, root)) return;
|
||||
event.preventDefault();
|
||||
app.canvas.processMouseWheel(event);
|
||||
}
|
||||
|
||||
// Middle-button pan starts over a panel too.
|
||||
function onPointerDown(event) {
|
||||
if (!app.canvas || event.button !== 1 || !panelRoot(event.target)) return;
|
||||
forwardedPointer = event.pointerId;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
app.canvas.processMouseDown(event);
|
||||
}
|
||||
|
||||
function onPointerMove(event) {
|
||||
if (forwardedPointer === event.pointerId) app.canvas?.processMouseMove(event);
|
||||
}
|
||||
|
||||
function onPointerEnd(event) {
|
||||
if (forwardedPointer !== event.pointerId) return;
|
||||
forwardedPointer = null;
|
||||
app.canvas?.processMouseUp(event);
|
||||
}
|
||||
|
||||
function dropTaker(event) {
|
||||
const types = Array.from(event.dataTransfer?.types ?? []);
|
||||
if (!types.includes("Files") || !event.target?.closest?.(".dom-widget") || !panelRoot(event.target)) return null;
|
||||
const canvas = app.canvas;
|
||||
if (typeof canvas?.adjustMouseEvent !== "function") return null;
|
||||
canvas.adjustMouseEvent(event);
|
||||
const node = canvas.graph?.getNodeOnPos?.(event.canvasX, event.canvasY);
|
||||
return typeof node?.onDragDrop === "function" && node.onDragOver?.(event) ? node : null;
|
||||
}
|
||||
|
||||
function onDragOver(event) {
|
||||
if (!dropTaker(event)) return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
|
||||
async function onDrop(event) {
|
||||
const node = dropTaker(event);
|
||||
if (!node) return;
|
||||
// The node takes the file; ComfyUI's own handler would add a new node.
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
await node.onDragDrop(event);
|
||||
}
|
||||
|
||||
export function installPassthrough() {
|
||||
if (globalThis[INSTALLED]) return;
|
||||
globalThis[INSTALLED] = true;
|
||||
window.addEventListener("wheel", onWheel, { passive: false });
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
window.addEventListener("pointermove", onPointerMove, true);
|
||||
window.addEventListener("pointerup", onPointerEnd, true);
|
||||
window.addEventListener("pointercancel", onPointerEnd, true);
|
||||
window.addEventListener("dragover", onDragOver, true);
|
||||
window.addEventListener("drop", onDrop, true);
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
// The kit's number control: drag left/right to scrub, click to type a value
|
||||
// or a sum (1024*1.5), chevrons or ArrowUp/Down to step, Shift for the fine
|
||||
// step. Pure math first (node:test), DOM factory below.
|
||||
import { keepKeyInField } from "./dom.js";
|
||||
|
||||
export const SCRUB_DEAD_ZONE = 3;
|
||||
export const SCRUB_PIXELS_PER_STEP = 4;
|
||||
// Shift on a box with no finer step slows the drag by this much instead.
|
||||
export const SCRUB_SLOW_FACTOR = 4;
|
||||
|
||||
export function quantize(value, { min = -Infinity, max = Infinity, decimals = 2 } = {}) {
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number)) return quantize(min === -Infinity ? 0 : min, { min, max, decimals });
|
||||
const factor = 10 ** Math.max(0, decimals);
|
||||
return Math.round(Math.max(min, Math.min(max, number)) * factor) / factor;
|
||||
}
|
||||
|
||||
// A sum typed into a number box: + - * / %, brackets and signs. Returns the
|
||||
// answer, or null when the text is not a sum that comes to a finite number.
|
||||
const SUM_NUMBER = /(?:\d+\.?\d*|\.\d+)/y;
|
||||
export function sumValue(text) {
|
||||
const source = String(text ?? "");
|
||||
if (source.length > 200) return null;
|
||||
let at = 0;
|
||||
const skip = () => { while (source[at] === " ") at += 1; };
|
||||
const atom = () => {
|
||||
skip();
|
||||
const mark = source[at];
|
||||
if (mark === "+" || mark === "-") {
|
||||
at += 1;
|
||||
const value = atom();
|
||||
return value === null ? null : mark === "-" ? -value : value;
|
||||
}
|
||||
if (mark === "(") {
|
||||
at += 1;
|
||||
const value = sum();
|
||||
skip();
|
||||
if (value === null || source[at] !== ")") return null;
|
||||
at += 1;
|
||||
return value;
|
||||
}
|
||||
SUM_NUMBER.lastIndex = at;
|
||||
const match = SUM_NUMBER.exec(source);
|
||||
if (!match) return null;
|
||||
at += match[0].length;
|
||||
return Number(match[0]);
|
||||
};
|
||||
const product = () => {
|
||||
let value = atom();
|
||||
while (value !== null) {
|
||||
skip();
|
||||
const mark = source[at];
|
||||
if (mark !== "*" && mark !== "/" && mark !== "%") break;
|
||||
at += 1;
|
||||
const next = atom();
|
||||
if (next === null) return null;
|
||||
value = mark === "*" ? value * next : mark === "/" ? value / next : value % next;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
function sum() {
|
||||
let value = product();
|
||||
while (value !== null) {
|
||||
skip();
|
||||
const mark = source[at];
|
||||
if (mark !== "+" && mark !== "-") break;
|
||||
at += 1;
|
||||
const next = product();
|
||||
if (next === null) return null;
|
||||
value = mark === "+" ? value + next : value - next;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
const value = sum();
|
||||
skip();
|
||||
return value === null || at !== source.length || !Number.isFinite(value) ? null : value;
|
||||
}
|
||||
|
||||
// Steps from a widget's options: the fine step is the widget's own
|
||||
// increment; a 0..1 float moves by 0.05, a wide float by ten increments, a
|
||||
// whole number by its increment (a wide pixel size by 8).
|
||||
export function scrubSteps(options = {}, isFloat = true, pixels = false) {
|
||||
const fine = Number(options.step2 ?? (options.step ? options.step / 10 : null) ?? (isFloat ? 0.01 : 1)) || (isFloat ? 0.01 : 1);
|
||||
const range = Number(options.max ?? Infinity) - Number(options.min ?? -Infinity);
|
||||
let step;
|
||||
if (!isFloat) step = pixels && Number.isFinite(range) && range > 2048 ? 8 : Math.max(1, fine);
|
||||
else if (Number.isFinite(range) && range <= 2) step = Math.max(fine, 0.05);
|
||||
else step = fine * 10;
|
||||
const decimals = isFloat ? Number(options.precision ?? Math.max(0, -Math.floor(Math.log10(fine)))) : 0;
|
||||
return { step, fineStep: fine, decimals };
|
||||
}
|
||||
|
||||
export function scrubbedValue(start, deltaX, fine, { step = 1, fineStep = null, ...range } = {}) {
|
||||
if (Math.abs(deltaX) <= SCRUB_DEAD_ZONE) return quantize(start, range);
|
||||
const finer = fineStep != null && fineStep < step;
|
||||
const size = fine && finer ? fineStep : step;
|
||||
const pixels = fine && !finer ? SCRUB_PIXELS_PER_STEP * SCRUB_SLOW_FACTOR : SCRUB_PIXELS_PER_STEP;
|
||||
const steps = Math.round((deltaX - Math.sign(deltaX) * SCRUB_DEAD_ZONE) / pixels);
|
||||
return quantize(start + steps * size, range);
|
||||
}
|
||||
|
||||
function chevron(up) {
|
||||
const points = up ? "1.5,4 4.5,1 7.5,4" : "1.5,1 4.5,4 7.5,1";
|
||||
return `<svg width="9" height="5" viewBox="0 0 9 5" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="${points}"/></svg>`;
|
||||
}
|
||||
|
||||
// makeScrub({ value, min, max, step, fineStep, decimals, unit, unitWidth, title, onChange, onSettle })
|
||||
// -> { root, get, set, setRange }. onChange fires on every committed change,
|
||||
// onSettle once a gesture finishes (the undo point).
|
||||
export function makeScrub(options = {}) {
|
||||
const opts = { value: 0, min: -Infinity, max: Infinity, step: 1, fineStep: null, decimals: 2, unit: "", unitWidth: 0, title: "", ...options };
|
||||
let current = quantize(opts.value, opts);
|
||||
const format = (value) => Number(value).toFixed(Math.max(0, opts.decimals));
|
||||
const stepped = (direction, fine) => current + direction * (fine ? (opts.fineStep ?? opts.step) : opts.step);
|
||||
|
||||
const box = document.createElement("div");
|
||||
box.className = "fbui-scrub";
|
||||
const input = document.createElement("input");
|
||||
input.className = "fbui-scrub-input";
|
||||
input.type = "text";
|
||||
input.inputMode = "decimal";
|
||||
input.readOnly = true;
|
||||
input.value = format(current);
|
||||
input.title = `${opts.title ? `${opts.title} ` : ""}Hold and drag right/up to raise, left/down to lower; click to type; Shift = fine.`;
|
||||
|
||||
const commit = (value) => {
|
||||
const next = quantize(value, opts);
|
||||
const changed = next !== current;
|
||||
current = next;
|
||||
input.value = format(current);
|
||||
if (changed) opts.onChange?.(current);
|
||||
};
|
||||
const settle = () => opts.onSettle?.();
|
||||
|
||||
// Press and drag either way: right or up raises the value, left or down
|
||||
// lowers it. The axis is the one the drag starts along.
|
||||
let drag = null;
|
||||
const travel = (event) => (drag.axis === "y" ? drag.y - event.clientY : event.clientX - drag.x);
|
||||
input.addEventListener("pointerdown", (event) => {
|
||||
if (event.button !== 0 || !input.readOnly) return;
|
||||
drag = { x: event.clientX, y: event.clientY, start: current, scrubbed: false, fine: event.shiftKey, axis: "x" };
|
||||
input.setPointerCapture(event.pointerId);
|
||||
event.preventDefault();
|
||||
});
|
||||
input.addEventListener("pointermove", (event) => {
|
||||
if (!drag) return;
|
||||
const dx = event.clientX - drag.x;
|
||||
const dy = event.clientY - drag.y;
|
||||
if (!drag.scrubbed && Math.max(Math.abs(dx), Math.abs(dy)) > SCRUB_DEAD_ZONE) {
|
||||
drag.scrubbed = true;
|
||||
drag.axis = Math.abs(dy) > Math.abs(dx) ? "y" : "x";
|
||||
drag.fine = event.shiftKey;
|
||||
}
|
||||
if (!drag.scrubbed) return;
|
||||
if (event.shiftKey !== drag.fine) {
|
||||
// Pressing or releasing Shift carries on from here at the other speed.
|
||||
const moved = travel(event);
|
||||
const offset = Math.sign(moved || 1) * (SCRUB_DEAD_ZONE + 1);
|
||||
drag.start = current;
|
||||
if (drag.axis === "y") drag.y = event.clientY + offset;
|
||||
else drag.x = event.clientX - offset;
|
||||
drag.fine = event.shiftKey;
|
||||
}
|
||||
commit(scrubbedValue(drag.start, travel(event), event.shiftKey, opts));
|
||||
});
|
||||
const endDrag = (event) => {
|
||||
if (!drag) return;
|
||||
try { input.releasePointerCapture(event.pointerId); } catch { /* mouse fallback */ }
|
||||
const scrubbed = drag.scrubbed;
|
||||
drag = null;
|
||||
if (scrubbed) {
|
||||
settle();
|
||||
return;
|
||||
}
|
||||
input.readOnly = false;
|
||||
input.focus();
|
||||
input.select();
|
||||
// The canvas can grab focus during the click sequence; win that race once.
|
||||
requestAnimationFrame(() => {
|
||||
if (document.activeElement === input) return;
|
||||
input.readOnly = false;
|
||||
input.focus();
|
||||
input.select();
|
||||
});
|
||||
};
|
||||
input.addEventListener("pointerup", endDrag);
|
||||
input.addEventListener("pointercancel", endDrag);
|
||||
input.addEventListener("keydown", (event) => {
|
||||
keepKeyInField(event);
|
||||
if (event.key === "Enter") input.blur();
|
||||
else if (event.key === "Escape") { input.value = format(current); input.blur(); }
|
||||
else if (event.key === "ArrowUp" || event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
commit(stepped(event.key === "ArrowUp" ? 1 : -1, event.shiftKey));
|
||||
input.select();
|
||||
settle();
|
||||
}
|
||||
});
|
||||
input.addEventListener("blur", () => {
|
||||
if (!input.readOnly) {
|
||||
const number = Number(input.value);
|
||||
const typed = Number.isFinite(number) && input.value.trim() !== "" ? number : sumValue(input.value);
|
||||
if (typed !== null) { commit(typed); settle(); }
|
||||
input.readOnly = true;
|
||||
}
|
||||
input.value = format(current);
|
||||
});
|
||||
|
||||
const steppers = document.createElement("div");
|
||||
steppers.className = "fbui-scrub-step";
|
||||
for (const direction of [1, -1]) {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.tabIndex = -1;
|
||||
button.innerHTML = chevron(direction > 0);
|
||||
button.addEventListener("click", (event) => { commit(stepped(direction, event.shiftKey)); settle(); });
|
||||
steppers.append(button);
|
||||
}
|
||||
|
||||
box.append(input);
|
||||
if (opts.unit || opts.unitWidth) {
|
||||
// A fixed unit slot keeps every number in a column on one centre line.
|
||||
const unit = document.createElement("span");
|
||||
unit.className = "fbui-scrub-unit";
|
||||
unit.textContent = opts.unit;
|
||||
if (opts.unitWidth) unit.style.width = `${opts.unitWidth}px`;
|
||||
else unit.style.padding = "0 3px 0 1px";
|
||||
box.append(unit);
|
||||
}
|
||||
box.append(steppers);
|
||||
|
||||
return {
|
||||
root: box,
|
||||
get: () => current,
|
||||
set: (value) => {
|
||||
current = quantize(value, opts);
|
||||
if (input.readOnly) input.value = format(current);
|
||||
},
|
||||
setRange: (range = {}) => {
|
||||
for (const key of ["min", "max", "step", "fineStep", "decimals"]) if (range[key] !== undefined) opts[key] = range[key];
|
||||
current = quantize(current, opts);
|
||||
if (input.readOnly) input.value = format(current);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// FB UI kit: the shared look of FBnodes, Prompt Manager and H3RefModPicker.
|
||||
// Every pack ships an identical copy of js/fbui/ (tools/sync_fbui.py), so each
|
||||
// pack works alone and all of them look the same when installed together.
|
||||
// Layout and controls adapted from ComfyUI-AusBoss (MIT, (c) 2026 ausboss).
|
||||
//
|
||||
// No imports: the node:test suites load this file without the ComfyUI app.
|
||||
|
||||
// Bump once per release that changes the CSS below (against the last pushed
|
||||
// value, not per local edit). Two packs shipping the same version inject one
|
||||
// stylesheet; different versions both inject and the later wins.
|
||||
export const KIT_VERSION = 13;
|
||||
|
||||
export const T = Object.freeze({
|
||||
brand: "#4299e1", // the one accent: picked segment, switch on, focus ring
|
||||
onBrand: "#08182a", // text on a brand fill
|
||||
brandSoft: "rgba(66,153,225,.16)",
|
||||
brandSoftHover: "rgba(66,153,225,.28)",
|
||||
brandInk: "#8cc4f2", // chip text on brandSoft
|
||||
|
||||
card: "#101317", // card ground
|
||||
fill: "#2b3036", // every control: solid, no border
|
||||
fillHover: "#363c43",
|
||||
rule: "#2a2f35", // hairline after a section label
|
||||
switchOff: "#5f666e", // the "off" half of a boolean pill when picked
|
||||
|
||||
ink: "#f5f7f9", // values
|
||||
inkSoft: "#dfe3e7", // default card text
|
||||
inkHover: "#ffffff",
|
||||
label: "#b2b9c0", // row labels, unselected segments
|
||||
faint: "#959ca4", // units, captions, placeholders
|
||||
|
||||
danger: "#e0605a",
|
||||
dangerInk: "#ffd9d6",
|
||||
dangerSoft: "#3a1c1b",
|
||||
warn: "#e0a040",
|
||||
warnInk: "#ffdca8",
|
||||
warnSoft: "#3a2a10",
|
||||
latent: "#c840c0", // a lossless .latent file beside a clip
|
||||
|
||||
overlay: "rgba(0,0,0,.72)", // modal backdrop
|
||||
panel: "#171b20", // modal surface
|
||||
shade: "rgba(8,10,12,.62)", // outside a crop
|
||||
maskInk: "#ff3b3b", // painted mask, drawn at half strength
|
||||
plate: "#1d232b", // media frame and footnote bar: neutral slate
|
||||
plateEdge: "#323a45", // their 1px trim
|
||||
});
|
||||
|
||||
export const FONT = `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`;
|
||||
export const MONO = `ui-monospace,"Cascadia Mono",Menlo,Consolas,monospace`;
|
||||
|
||||
export const ROW_HEIGHT = 26;
|
||||
// The footnote bar under a picture or video (card panel row height).
|
||||
export const CAPTION_HEIGHT = 24;
|
||||
export const ROW_GAP = 8;
|
||||
export const SECTION_HEIGHT = 17;
|
||||
export const GROUP_HEIGHT = 22;
|
||||
export const CARD_PADDING = 10;
|
||||
export const UNIT_SLOT_WIDTH = 22;
|
||||
export const RADIUS_XS = 4;
|
||||
export const RADIUS = 6;
|
||||
export const RADIUS_CARD = 10;
|
||||
|
||||
// Modals stack above ComfyUI's own dialogs; menus above modals.
|
||||
export const Z_MODAL = 10000;
|
||||
export const Z_MENU = 10010;
|
||||
|
||||
const CHEVRON = `url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' fill='none' stroke='%23b2b9c0' stroke-width='1.5'/%3E%3C/svg%3E")`;
|
||||
|
||||
export function kitCss() {
|
||||
return `
|
||||
.fbui-card{position:relative;box-sizing:border-box;width:100%;height:100%;display:flex;flex-direction:column;gap:${ROW_GAP}px;padding:${CARD_PADDING}px 12px;overflow:hidden;border-radius:${RADIUS_CARD}px;background:${T.card};font:12px/1.3 ${FONT};color:${T.inkSoft};pointer-events:none}
|
||||
.fbui-row{display:grid;grid-template-columns:minmax(52px,24%) 1fr;align-items:center;gap:10px;height:${ROW_HEIGHT}px;flex:none;pointer-events:auto}
|
||||
.fbui-row.wide{grid-template-columns:1fr}
|
||||
.fbui-card .hidden{display:none!important}
|
||||
.fbui-row.linked{opacity:.5}
|
||||
.fbui-row.linked .fbui-control{pointer-events:none}
|
||||
.fbui-row.panel{display:block}
|
||||
.fbui-row.panel.grow{flex:1 1 auto;height:auto}
|
||||
.fbui-label{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;color:${T.label};font-size:11px;user-select:none}
|
||||
.fbui-label.has-info{display:flex;align-items:center;gap:4px}
|
||||
.fbui-label.has-info>span{overflow:hidden;text-overflow:ellipsis}
|
||||
.fbui-info{flex:none;display:inline-flex;color:${T.faint};cursor:pointer}
|
||||
.fbui-info:hover,.fbui-info.on{color:${T.brandInk}}
|
||||
.fbui-info svg{width:13px;height:13px}
|
||||
.fbui-pop{position:fixed;z-index:${Z_MENU};max-width:460px;padding:14px 16px;border:1px solid ${T.plateEdge};border-radius:${RADIUS_CARD}px;background:${T.panel};box-shadow:0 10px 32px rgba(0,0,0,.6);color:${T.inkSoft};font:13px/1.55 ${FONT};user-select:text;cursor:auto;outline:none}
|
||||
.fbui-pop>div+div{margin-top:6px}
|
||||
.fbui-pop .pair{display:grid;grid-template-columns:minmax(150px,auto) 1fr;gap:14px;align-items:baseline}
|
||||
.fbui-pop code{justify-self:start;padding:1px 6px;border-radius:4px;background:${T.card};color:${T.brandInk};font:600 13px ${MONO};cursor:copy}
|
||||
.fbui-pop code:hover{background:${T.fill}}
|
||||
.fbui-pop code.copied{background:${T.brand};color:${T.onBrand}}
|
||||
.fbui-control{display:flex;align-items:center;gap:6px;min-width:0;height:100%}
|
||||
.fbui-field{display:flex;align-items:center;gap:6px;flex:1 1 0;min-width:0;height:100%}
|
||||
.fbui-field.linked{opacity:.5;pointer-events:none}
|
||||
.fbui-sep{flex:none;color:${T.faint};font-size:11px}
|
||||
.fbui-section{height:${SECTION_HEIGHT}px;flex:none;display:flex;align-items:flex-end;gap:8px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;user-select:none}
|
||||
.fbui-section::after{content:"";flex:1;height:1px;margin-bottom:4px;background:${T.rule}}
|
||||
.fbui-group{height:${GROUP_HEIGHT}px;flex:none;display:flex;align-items:center;gap:6px;padding:0 0 0 4px;color:${T.faint};font:600 10px/1 ${FONT};letter-spacing:.1em;text-transform:uppercase;pointer-events:auto}
|
||||
.fbui-group .toggle{flex:1;min-width:0;height:100%;display:flex;align-items:center;gap:6px;padding:0;border:none;border-radius:${RADIUS}px;background:transparent;color:inherit;font:inherit;letter-spacing:inherit;text-transform:inherit;cursor:pointer;text-align:left}
|
||||
.fbui-group .toggle:hover{color:${T.inkHover}}
|
||||
.fbui-group .glyph{display:inline-block;width:10px;transition:transform .12s}
|
||||
.fbui-group.open .glyph{transform:rotate(90deg)}
|
||||
.fbui-seg{display:grid;grid-auto-flow:column;grid-auto-columns:1fr;width:100%;height:${ROW_HEIGHT}px;padding:2px;box-sizing:border-box;border-radius:${RADIUS}px;background:${T.fill}}
|
||||
.fbui-seg button{min-width:0;border:none;border-radius:${RADIUS_XS}px;padding:0 2px;background:transparent;color:${T.label};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.fbui-seg button:hover{color:${T.inkHover}}
|
||||
.fbui-seg button.on{background:${T.brand};color:${T.onBrand}}
|
||||
.fbui-bool button.on:first-child{background:${T.switchOff};color:${T.ink}}
|
||||
.fbui-select{width:100%;height:${ROW_HEIGHT}px;padding:0 24px 0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill} ${CHEVRON} no-repeat right 9px center;color:${T.ink};font:500 12px ${FONT};appearance:none;-webkit-appearance:none;cursor:pointer;overflow:hidden;text-overflow:ellipsis;min-width:0}
|
||||
.fbui-select:hover{background-color:${T.fillHover}}
|
||||
.fbui-select:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.fbui-select option{background:${T.panel};color:${T.ink}}
|
||||
.fbui-text{width:100%;height:${ROW_HEIGHT}px;padding:0 8px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};color:${T.ink};font:12px ${FONT};min-width:0}
|
||||
.fbui-text:focus{outline:none;border-color:${T.brand}}
|
||||
textarea.fbui-text{background:${T.card};border-color:${T.plateEdge};font-size:13px;line-height:1.45}
|
||||
.fbui-text.entry{flex:none;height:30px;background:${T.card};border-color:${T.plateEdge};font-size:13px}
|
||||
.comfy-multiline-input.fbui-native-text,.lg-node-widgets textarea[data-fbui-text]{background:${T.card};border:1px solid ${T.plateEdge};color:${T.ink}}
|
||||
.fbui-text::placeholder{color:${T.faint}}
|
||||
.fbui-btn{flex:none;display:inline-flex;align-items:center;justify-content:center;gap:5px;height:${ROW_HEIGHT}px;padding:0 10px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};color:${T.inkSoft};font:600 11px/1 ${FONT};cursor:pointer;white-space:nowrap;pointer-events:auto}
|
||||
.fbui-btn:hover{background:${T.fillHover};color:${T.inkHover}}
|
||||
.fbui-btn:focus-visible{outline:2px solid ${T.brand};outline-offset:1px}
|
||||
.fbui-btn:disabled{opacity:.45;cursor:default}
|
||||
.fbui-card [hidden],.fbui-overlay [hidden],.fbui-btn[hidden]{display:none!important}
|
||||
.fbui-btn.grow{flex:1 1 0;min-width:0}
|
||||
/* soft: the suite's blue action button; on: a tool that is enabled but not the one in use. Same look. */
|
||||
.fbui-btn.on,.fbui-btn.soft{background:${T.brandSoft};color:${T.brandInk}}
|
||||
.fbui-btn.soft:hover{background:${T.brandSoftHover};color:${T.ink}}
|
||||
.fbui-btn.primary{background:${T.brand};color:${T.onBrand}}
|
||||
.fbui-btn.primary:hover{filter:brightness(1.1)}
|
||||
.fbui-btn.danger:hover{background:${T.dangerSoft};color:${T.dangerInk}}
|
||||
.fbui-btn.small{height:20px;padding:0 7px;font-size:10px}
|
||||
.fbui-btn.icon{width:${ROW_HEIGHT}px;padding:0}
|
||||
.fbui-btn.icon.small{width:20px}
|
||||
/* A slide handle sits in a field's icon column: its padding hangs outside so the icon lines up. */
|
||||
.fbui-slide{flex:none;display:flex;align-items:center;align-self:stretch;margin:2px -4px;padding:0 4px;border-radius:${RADIUS}px;cursor:ew-resize;touch-action:none}
|
||||
.fbui-slide svg{flex:none;color:${T.label}}
|
||||
.fbui-slide:hover,.fbui-slide.on{background:${T.fill};color:${T.ink}}
|
||||
.fbui-slide:hover svg,.fbui-slide.on svg{color:${T.brand}}
|
||||
.fbui-rail{position:relative;height:24px;margin:0 7px;touch-action:none;cursor:pointer;user-select:none;pointer-events:auto}
|
||||
.fbui-rail::before{content:"";position:absolute;left:0;right:0;top:10px;height:5px;border-radius:3px;background:${T.fill}}
|
||||
.fbui-rail.disabled{opacity:.45;cursor:default}
|
||||
.fbui-rail-fill{position:absolute;left:0;top:10px;height:5px;border-radius:3px;background:${T.brandSoftHover};pointer-events:none}
|
||||
.fbui-rail-head{position:absolute;top:0;bottom:0;width:2px;margin-left:-1px;background:${T.ink};box-shadow:0 0 0 1px rgba(0,0,0,.55);pointer-events:none}
|
||||
.fbui-rail-head::before{content:"";position:absolute;top:-1px;left:50%;transform:translateX(-50%);border:5px solid transparent;border-top:6px solid ${T.ink};filter:drop-shadow(0 0 1px rgba(0,0,0,.7))}
|
||||
.fbui-range-fill{position:absolute;top:10px;height:5px;background:${T.brand};opacity:.6;pointer-events:none}
|
||||
.fbui-range-edge{position:absolute;top:4px;width:7px;height:17px;margin-left:-3.5px;border-radius:3px;background:${T.brand};box-shadow:0 0 0 1px rgba(0,0,0,.5);pointer-events:none}
|
||||
.fbui-readout{flex:1 1 0;min-width:0;color:${T.faint};font:11px ${FONT};font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.fbui-readout b{color:${T.ink};font-weight:600}
|
||||
.fbui-tag{flex:none;color:${T.brand};font:650 10px ${FONT};letter-spacing:.08em;text-transform:uppercase;user-select:none}
|
||||
.fbui-btn svg{flex:none}
|
||||
.fbui-chip{height:20px;flex:none;display:inline-flex;align-items:center;padding:0 9px;border:none;border-radius:999px;background:${T.brandSoft};color:${T.brandInk};font:600 10px/1 ${FONT};letter-spacing:.02em;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.fbui-chip.warn{background:${T.warnSoft};color:${T.warnInk}}
|
||||
.fbui-chip.danger{background:${T.dangerSoft};color:${T.dangerInk}}
|
||||
.fbui-scrub{display:flex;width:100%;height:${ROW_HEIGHT}px;box-sizing:border-box;border:1px solid transparent;border-radius:${RADIUS}px;background:${T.fill};overflow:hidden;flex:1 1 0;min-width:0;color:${T.ink};font:500 12px ${FONT};font-variant-numeric:tabular-nums}
|
||||
.fbui-scrub:focus-within{border-color:${T.brand}}
|
||||
.fbui-scrub>.fbui-scrub-input{flex:1 1 auto;min-width:0;width:100%;height:100%;border:none;padding:0;margin:0;background:transparent;color:inherit;text-align:center;cursor:ew-resize;user-select:none;font:inherit;outline:none;border-radius:0}
|
||||
.fbui-scrub>.fbui-scrub-input:focus{cursor:text;user-select:text}
|
||||
.fbui-scrub>.fbui-scrub-unit{flex:none;align-self:center;color:${T.faint};font:600 10px ${FONT};letter-spacing:.04em;text-transform:uppercase;text-align:center;user-select:none;pointer-events:none}
|
||||
.fbui-scrub>.fbui-scrub-step{flex:none;width:14px;display:flex;flex-direction:column;background:${T.fillHover}}
|
||||
.fbui-scrub>.fbui-scrub-step>button{flex:1 1 0;min-height:0;border:none;background:transparent;color:${T.label};cursor:pointer;padding:0;margin:0;display:grid;place-items:center;border-radius:0}
|
||||
.fbui-scrub>.fbui-scrub-step>button:hover{color:${T.brand};background:rgba(255,255,255,.05)}
|
||||
.fbui-stage{position:relative;width:100%;height:100%;min-height:0;box-sizing:border-box;border:1px solid ${T.plateEdge};border-radius:${RADIUS_CARD}px;background:${T.plate};overflow:hidden;pointer-events:auto}
|
||||
.fbui-stage>img,.fbui-stage>video,.fbui-stage>canvas.fbui-fit{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;display:block}
|
||||
.fbui-stage-empty{position:absolute;inset:0;display:grid;place-items:center;padding:12px;color:${T.faint};font:11px ${FONT};text-align:center;pointer-events:none}
|
||||
.fbui-stage-tools{position:absolute;top:6px;right:6px;display:flex;gap:4px;z-index:2}
|
||||
.fbui-stage-tools .fbui-btn{height:20px;padding:0 7px;font-size:10px;letter-spacing:.04em;background:rgba(16,19,23,.82)}
|
||||
.fbui-stage-tools .fbui-btn:hover{background:${T.fillHover}}
|
||||
.fbui-stage-tools .fbui-btn.on{background:${T.brand};color:${T.onBrand}}
|
||||
.fbui-caption{box-sizing:border-box;width:100%;height:${CAPTION_HEIGHT}px;display:flex;align-items:center;justify-content:center;gap:6px;padding:0 10px;border:1px solid ${T.plateEdge};border-radius:${RADIUS + 2}px;background:${T.plate};color:${T.label};font:600 11px ${FONT};font-variant-numeric:tabular-nums;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;pointer-events:auto}
|
||||
.fbui-overlay{position:fixed;inset:0;z-index:${Z_MODAL};display:flex;align-items:center;justify-content:center;background:${T.overlay};font:12px/1.4 ${FONT};color:${T.inkSoft}}
|
||||
.fbui-modal{display:flex;flex-direction:column;max-width:92vw;max-height:90vh;min-width:320px;border-radius:${RADIUS_CARD}px;background:${T.panel};box-shadow:0 18px 60px rgba(0,0,0,.6);overflow:hidden}
|
||||
.fbui-modal-head{flex:none;display:flex;align-items:center;gap:8px;padding:10px 12px;color:${T.ink};font:600 13px ${FONT}}
|
||||
.fbui-modal-head .title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.fbui-modal-body{flex:1 1 auto;min-height:0;overflow:auto;padding:0 12px 12px}
|
||||
.fbui-modal-foot{flex:none;display:flex;justify-content:flex-end;gap:6px;padding:10px 12px;background:${T.card}}
|
||||
.fbui-viewer{position:fixed;inset:0;z-index:${Z_MODAL};background:rgba(5,6,8,.94);font:12px ${FONT};color:${T.inkSoft}}
|
||||
.fbui-viewer .stage{position:absolute;inset:48px 64px 24px;display:flex;align-items:center;justify-content:center}
|
||||
.fbui-viewer .stage img,.fbui-viewer .stage video{max-width:100%;max-height:100%;object-fit:contain;border-radius:${RADIUS}px;box-shadow:0 12px 48px rgba(0,0,0,.6);display:block}
|
||||
.fbui-viewer .name{position:absolute;left:20px;top:14px;max-width:60vw;padding:4px 10px;border-radius:999px;background:${T.panel};color:${T.ink};font:600 12px ${FONT};white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||||
.fbui-viewer .where{position:absolute;left:50%;top:14px;transform:translateX(-50%);padding:4px 10px;border-radius:999px;background:${T.panel};color:${T.label};font:600 12px ${FONT};font-variant-numeric:tabular-nums}
|
||||
.fbui-viewer .shut{position:absolute;right:16px;top:10px}
|
||||
.fbui-viewer .nav{position:absolute;top:50%;transform:translateY(-50%);width:44px;height:44px;border-radius:50%;background:rgba(16,19,23,.8)}
|
||||
.fbui-viewer .nav svg{width:20px;height:20px}
|
||||
.fbui-viewer .nav.prev{left:12px}
|
||||
.fbui-viewer .nav.next{right:12px}
|
||||
.fbui-menu{position:fixed;z-index:${Z_MENU};min-width:160px;padding:4px;border-radius:${RADIUS}px;background:${T.panel};box-shadow:0 8px 28px rgba(0,0,0,.55);font:12px ${FONT};color:${T.inkSoft}}
|
||||
.fbui-menu button{display:block;width:100%;padding:6px 10px;border:none;border-radius:${RADIUS_XS}px;background:transparent;color:inherit;font:inherit;text-align:left;cursor:pointer}
|
||||
.fbui-menu button:hover{background:${T.fillHover};color:${T.inkHover}}
|
||||
.fbui-menu button.danger:hover{background:${T.dangerSoft};color:${T.dangerInk}}
|
||||
.fbui-menu .sep{height:1px;margin:4px 6px;background:${T.rule}}
|
||||
`;
|
||||
}
|
||||
|
||||
export function ensureKitCss() {
|
||||
const id = `fbui-css-v${KIT_VERSION}`;
|
||||
if (document.getElementById(id)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = id;
|
||||
style.textContent = kitCss();
|
||||
document.head.append(style);
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// Show and hide stock widgets in place. A hidden widget stays in
|
||||
// node.widgets, so widgets_values keeps its order and saved workflows load
|
||||
// unchanged; only its rendering collapses.
|
||||
//
|
||||
// The classic canvas lays widgets out by computeSize / computeLayoutSize and
|
||||
// paints them with draw, so those are zeroed. Nodes 2.0 filters its widget
|
||||
// list on `widget.options.hidden`, so that flag is set too.
|
||||
|
||||
const STASH = Symbol.for("fbui.hiddenWidget");
|
||||
const PAINT_KEYS = ["computeSize", "computeLayoutSize", "draw"];
|
||||
|
||||
export function hideWidget(widget) {
|
||||
if (!widget) return false;
|
||||
if (widget[STASH]) {
|
||||
if (widget.options) widget.options.hidden = true;
|
||||
return false;
|
||||
}
|
||||
let options = widget.options ?? {};
|
||||
widget[STASH] = {
|
||||
own: Object.fromEntries(PAINT_KEYS.map((key) => [key, Object.hasOwn(widget, key)])),
|
||||
paint: Object.fromEntries(PAINT_KEYS.map((key) => [key, widget[key]])),
|
||||
hidden: widget.hidden,
|
||||
optionsHidden: options.hidden,
|
||||
};
|
||||
widget.hidden = true;
|
||||
options.hidden = true;
|
||||
// The frontend swaps a widget's options object after creation (a workflow
|
||||
// restore does), which would drop the flag; keep re-applying it.
|
||||
try {
|
||||
Object.defineProperty(widget, "options", {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: () => options,
|
||||
set: (next) => {
|
||||
options = next ?? {};
|
||||
options.hidden = true;
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
widget.options = options;
|
||||
}
|
||||
widget.computeSize = () => [0, -4];
|
||||
widget.computeLayoutSize = () => ({ minWidth: 0, minHeight: 0 });
|
||||
widget.draw = () => {};
|
||||
if (widget.element) widget.element.style.display = "none";
|
||||
return true;
|
||||
}
|
||||
|
||||
export function showWidget(widget) {
|
||||
const stash = widget?.[STASH];
|
||||
if (!stash) return false;
|
||||
for (const key of PAINT_KEYS) {
|
||||
if (stash.own[key]) widget[key] = stash.paint[key];
|
||||
else delete widget[key];
|
||||
}
|
||||
widget.hidden = stash.hidden;
|
||||
const options = widget.options;
|
||||
delete widget.options;
|
||||
widget.options = options;
|
||||
if (stash.optionsHidden === undefined) delete options.hidden;
|
||||
else options.hidden = stash.optionsHidden;
|
||||
if (widget.element) widget.element.style.display = "";
|
||||
widget[STASH] = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isWidgetHidden(widget) {
|
||||
return Boolean(widget?.[STASH]);
|
||||
}
|
||||
|
||||
// Mark inputs hidden in the node definition, before any widget exists. The
|
||||
// frontend rebuilds widget options from this spec on restore and on the
|
||||
// Nodes 2.0 mount, so a flag on the live widget alone is not enough.
|
||||
export function hideInputsInDef(nodeData, names) {
|
||||
for (const name of names) {
|
||||
for (const group of ["required", "optional"]) {
|
||||
const spec = nodeData?.input?.[group]?.[name];
|
||||
if (!Array.isArray(spec)) continue;
|
||||
spec[1] = { ...(spec[1] ?? {}), hidden: true };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function findWidget(node, name) {
|
||||
return node?.widgets?.find((widget) => widget.name === name) ?? null;
|
||||
}
|
||||
|
||||
export function comboValues(widget) {
|
||||
let values = widget?.options?.values;
|
||||
if (typeof values === "function") values = values(widget);
|
||||
return Array.isArray(values) ? values : [];
|
||||
}
|
||||
|
||||
// Write a value the way LiteGraph's own widgets do: set it, run the widget's
|
||||
// callback, then tell the node.
|
||||
export function commitWidgetValue(node, widget, value) {
|
||||
const previous = widget.value;
|
||||
widget.value = value;
|
||||
widget.callback?.(value, globalThis.app?.canvas, node);
|
||||
node.onWidgetChanged?.(widget.name, value, previous, widget);
|
||||
}
|
||||
|
||||
export function widgetSlot(node, name) {
|
||||
return node?.inputs?.find((input) => input?.widget?.name === name) ?? null;
|
||||
}
|
||||
|
||||
export function widgetLinked(node, name) {
|
||||
const slot = widgetSlot(node, name);
|
||||
return slot?.link !== null && slot?.link !== undefined;
|
||||
}
|
||||
|
||||
// A widget's hover text: its own tooltip, else the node definition's.
|
||||
export function widgetTooltip(node, name) {
|
||||
const widget = findWidget(node, name);
|
||||
const own = widget?.options?.tooltip ?? widget?.tooltip;
|
||||
if (typeof own === "string" && own) return own;
|
||||
const inputs = node?.constructor?.nodeData?.input;
|
||||
const spec = inputs?.required?.[name] ?? inputs?.optional?.[name];
|
||||
return typeof spec?.[1]?.tooltip === "string" ? spec[1].tooltip : "";
|
||||
}
|
||||
|
||||
// For a node that draws its own preview: keep the frontend's run-output
|
||||
// picture off it in both renderers. Nodes 2.0 reads hideOutputImages; the
|
||||
// classic canvas draws node.imgs through a "$$canvas-image-preview" widget,
|
||||
// and an animated (video) output through a "video-preview" DOM widget, which
|
||||
// it adds without looking at hideOutputImages.
|
||||
const CORE_PREVIEW = "$$canvas-image-preview";
|
||||
const CORE_VIDEO_PREVIEW = "video-preview";
|
||||
export function suppressCorePreview(node) {
|
||||
node.hideOutputImages = true;
|
||||
const index = node.widgets?.findIndex((widget) => widget.name === CORE_PREVIEW) ?? -1;
|
||||
if (index >= 0) {
|
||||
node.widgets[index].onRemove?.();
|
||||
node.widgets.splice(index, 1);
|
||||
}
|
||||
if (Object.getOwnPropertyDescriptor(node, "imgs")?.get) return;
|
||||
const addDom = node.addDOMWidget;
|
||||
if (typeof addDom === "function") {
|
||||
node.addDOMWidget = function (name, type, element, options) {
|
||||
const widget = addDom.call(this, name, type, element, options);
|
||||
if (name === CORE_VIDEO_PREVIEW) {
|
||||
hideWidget(widget);
|
||||
element.style.display = "none";
|
||||
// Nothing plays or stays loaded behind the node's own player.
|
||||
element.removeAttribute?.("src");
|
||||
element.load?.();
|
||||
}
|
||||
return widget;
|
||||
};
|
||||
}
|
||||
const add = node.addCustomWidget;
|
||||
if (typeof add === "function") {
|
||||
node.addCustomWidget = function (widget) {
|
||||
if (widget?.name === CORE_PREVIEW) hideWidget(widget);
|
||||
return add.call(this, widget);
|
||||
};
|
||||
}
|
||||
Object.defineProperty(node, "imgs", { configurable: true, enumerable: true, get: () => undefined, set: () => {} });
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Shared look for Prompt Manager: node colours, the kit stylesheet, and graph
|
||||
// zoom/drop over our panels. See docs/UI_RULES.md.
|
||||
import { installAppearance } from "./fbui/appearance.js";
|
||||
import { installPassthrough } from "./fbui/passthrough.js";
|
||||
import { ensureKitCss } from "./fbui/theme.js";
|
||||
|
||||
installAppearance({ settingsPrefix: "PromptManager", category: "Prompt Manager" });
|
||||
ensureKitCss();
|
||||
installPassthrough();
|
||||
+967
-2240
File diff suppressed because it is too large
Load Diff
+20
-9
@@ -1,10 +1,8 @@
|
||||
/**
|
||||
* Shared media path browser helpers for FBnodes Load+ nodes.
|
||||
*
|
||||
* Provides the backend-list/file URL helpers, root resolution, and the
|
||||
* input/output/absolute selection classifier used by the thumbnail browser
|
||||
* (file_browser.js) so the loader nodes can browse anywhere while keeping
|
||||
* old workflows working.
|
||||
* Prompt Manager's side of the shared file browser (file_browser.js, the
|
||||
* same file as in FBnodes): its routes and Custom-folder setting, root
|
||||
* resolution, and the input/output/absolute selection classifier, so the
|
||||
* Prompt Extractor can browse anywhere while keeping old workflows working.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
@@ -12,14 +10,27 @@ import { api } from "../../scripts/api.js";
|
||||
|
||||
export const SETTING_CUSTOM_PATH = "PromptManager.PromptExtractorCustomPath";
|
||||
|
||||
// This pack's routes for the shared file browser.
|
||||
export const BROWSER_ROUTES = {
|
||||
list: "/prompt-extractor/path-browser/list",
|
||||
file: "/prompt-extractor/path-browser/file",
|
||||
remove: "/prompt-extractor/path-browser/delete",
|
||||
videoFrame: "/prompt-extractor/video-frame",
|
||||
};
|
||||
|
||||
export function getCustomPresetPath() {
|
||||
const pref = app.ui?.settings?.getSettingValue(SETTING_CUSTOM_PATH) || "";
|
||||
return typeof pref === "string" ? pref.trim() : "";
|
||||
}
|
||||
|
||||
/** Store the Custom folder (the same setting as in Preferences). */
|
||||
export function setCustomPresetPath(path) {
|
||||
return app.ui.settings.setSettingValueAsync(SETTING_CUSTOM_PATH, String(path || "").trim());
|
||||
}
|
||||
|
||||
/** URL that streams a media file from any path (for previews of out-of-tree files). */
|
||||
export function mediaFileUrl(absPath) {
|
||||
return api.apiURL(`/prompt-extractor/path-browser/file?path=${encodeURIComponent(absPath)}`);
|
||||
return api.apiURL(`${BROWSER_ROUTES.file}?path=${encodeURIComponent(absPath)}`);
|
||||
}
|
||||
|
||||
function normalizeSlashes(p) {
|
||||
@@ -66,7 +77,7 @@ async function fetchBrowser(path, kind) {
|
||||
if (path) params.push(`path=${encodeURIComponent(path)}`);
|
||||
if (kind) params.push(`kind=${encodeURIComponent(kind)}`);
|
||||
const query = params.length ? `?${params.join("&")}` : "";
|
||||
const resp = await api.fetchApi(`/prompt-extractor/path-browser/list${query}`);
|
||||
const resp = await api.fetchApi(`${BROWSER_ROUTES.list}${query}`);
|
||||
if (!resp.ok) {
|
||||
let msg = `Request failed (${resp.status})`;
|
||||
try {
|
||||
@@ -99,7 +110,7 @@ app.registerExtension({
|
||||
id: SETTING_CUSTOM_PATH,
|
||||
category: ["Prompt Manager", "Prompt Extractor", "Custom Browser Path"],
|
||||
name: "Prompt Extractor Custom Browser Path",
|
||||
tooltip: "Optional folder shown as the 'Custom' preset in the Load+ file browsers.",
|
||||
tooltip: "The folder the Custom button opens in the Prompt Extractor's file browser.",
|
||||
type: "text",
|
||||
defaultValue: "",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
// Prompt Manager's small form dialogs on the FB UI kit modal: text fields and
|
||||
// selects in a column, Enter to confirm, Esc or a click outside to cancel.
|
||||
//
|
||||
// formDialog({ title, fields, confirmText }) -> Promise<{ [key]: value } | null>
|
||||
// fields: [{ key, label, type: "text" | "select" | "check", value, options }]
|
||||
// options: values or { value, label }, or (values) => options for a select
|
||||
// that follows the fields above it (a category list per prompt group).
|
||||
import { button } from "./fbui/controls.js";
|
||||
import { el } from "./fbui/dom.js";
|
||||
import { openModal } from "./fbui/modal.js";
|
||||
import { T } from "./fbui/theme.js";
|
||||
|
||||
function fillSelect(select, options, value) {
|
||||
select.replaceChildren(...options.map((option) => {
|
||||
const entry = typeof option === "object" && option ? option : { value: option, label: option };
|
||||
const item = el("option", "", String(entry.label ?? entry.value ?? ""));
|
||||
item.value = String(entry.value ?? "");
|
||||
return item;
|
||||
}));
|
||||
if (options.length) select.value = String(value ?? "");
|
||||
if (!select.value && select.options.length) select.selectedIndex = 0;
|
||||
}
|
||||
|
||||
export function formDialog({ title, fields, confirmText = "OK" }) {
|
||||
return new Promise((resolve) => {
|
||||
let answer = null;
|
||||
const controls = new Map();
|
||||
const values = () => Object.fromEntries([...controls].map(([key, control]) => [key, control.type === "checkbox" ? control.checked : control.value]));
|
||||
const refreshDependent = () => {
|
||||
for (const field of fields) {
|
||||
if (field.type === "select" && typeof field.options === "function") {
|
||||
const select = controls.get(field.key);
|
||||
const keep = select.value || field.value;
|
||||
fillSelect(select, field.options(values()), keep);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const body = fields.map((field, index) => {
|
||||
if (field.type === "check") {
|
||||
const box = el("input");
|
||||
box.type = "checkbox";
|
||||
box.checked = Boolean(field.value);
|
||||
box.style.cssText = `margin:0;accent-color:${T.brand}`;
|
||||
controls.set(field.key, box);
|
||||
const row = el("label");
|
||||
row.style.cssText = `display:flex;align-items:center;gap:8px;margin-top:${index ? 10 : 0}px;color:${T.inkSoft};font-size:12px;cursor:pointer`;
|
||||
row.append(box, el("span", "", field.label));
|
||||
return row;
|
||||
}
|
||||
const label = el("div", "", field.label);
|
||||
label.style.cssText = `margin:${index ? 10 : 0}px 0 5px;color:${T.label};font-size:12px`;
|
||||
let control;
|
||||
if (field.type === "select") {
|
||||
control = el("select", "fbui-select");
|
||||
if (typeof field.options !== "function") fillSelect(control, field.options ?? [], field.value);
|
||||
control.addEventListener("change", refreshDependent);
|
||||
} else {
|
||||
control = el("input", "fbui-text");
|
||||
control.type = "text";
|
||||
control.spellcheck = false;
|
||||
control.value = String(field.value ?? "");
|
||||
}
|
||||
control.style.width = "100%";
|
||||
// Enter moves to the next field, and confirms on the last one.
|
||||
control.addEventListener("keydown", (event) => {
|
||||
if (event.key !== "Enter") return;
|
||||
event.preventDefault();
|
||||
const next = [...controls.values()].slice([...controls.keys()].indexOf(field.key) + 1).find((other) => other.type !== "checkbox");
|
||||
if (next) next.focus();
|
||||
else accept();
|
||||
});
|
||||
controls.set(field.key, control);
|
||||
const row = el("div");
|
||||
row.append(label, control);
|
||||
return row;
|
||||
});
|
||||
|
||||
const accept = () => {
|
||||
answer = values();
|
||||
dialog.close();
|
||||
};
|
||||
const dialog = openModal({
|
||||
title,
|
||||
body,
|
||||
width: 440,
|
||||
footer: [button("Cancel", { onClick: () => dialog.close() }), button(confirmText, { primary: true, onClick: accept })],
|
||||
onClose: () => resolve(answer),
|
||||
});
|
||||
refreshDependent();
|
||||
const first = controls.values().next().value;
|
||||
first?.focus();
|
||||
if (first?.type === "text") first.select();
|
||||
});
|
||||
}
|
||||
+576
-2570
File diff suppressed because it is too large
Load Diff
+39
-135
@@ -2,6 +2,9 @@ import { saveComposerCategorySettings, saveComposerTypeSettings } from "./prompt
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { getCategoryPromptEntries, getCategoryPromptEntriesForEndpoint, getCategoryPromptEntryForEndpoint } from "./prompt_store_adapters.js";
|
||||
import { mediaFileUrl } from "./path_browser.js";
|
||||
import { PM_UI_PALETTE } from "./ui_palette.js";
|
||||
import { button as kitButton } from "./fbui/controls.js";
|
||||
import { RADIUS, T } from "./fbui/theme.js";
|
||||
|
||||
// Placeholder thumbnail. Defined locally (NOT imported from prompt_manager_advanced.js)
|
||||
// to break the module cycle:
|
||||
@@ -241,20 +244,7 @@ function getComposerCategoryMetadata(composerLibrary, category, promptType = "")
|
||||
};
|
||||
}
|
||||
|
||||
const STYLE = {
|
||||
panel: "hsl(216 11% 15%)",
|
||||
panelBorder: "hsl(216 20% 65% / 0.24)",
|
||||
sectionBorder: "hsl(216 20% 65% / 0.20)",
|
||||
inputBg: "hsl(220 15% 10%)",
|
||||
inputBorder: "hsl(218 10% 41%)",
|
||||
buttonBg: "hsl(219 16% 18%)",
|
||||
cardBg: "hsl(219 16% 18%)",
|
||||
textPrimary: "hsl(0 0% 87%)",
|
||||
textMuted: "hsl(0 0% 67%)",
|
||||
accent: "hsl(208 73% 57% / 0.9)",
|
||||
accentBorder: "hsl(208 73% 57% / 0.65)",
|
||||
accentSoft: "hsl(208 73% 57% / 0.16)",
|
||||
};
|
||||
const STYLE = PM_UI_PALETTE;
|
||||
|
||||
let _composerLoraPickerCache = null;
|
||||
let _composerLoraPickerPromise = null;
|
||||
@@ -554,11 +544,7 @@ function showVisualAssetImportPicker({ title, rootPath, loadFolder, emptyMessage
|
||||
});
|
||||
selectionTools.appendChild(selectToggleBtn);
|
||||
const cancelBtn = createButton("Cancel", () => close(null));
|
||||
const createBtn = createButton(createButtonLabel, () => close([...selectedAssets.values()]), {
|
||||
background: "#2b6d3a",
|
||||
borderColor: "#4a9158",
|
||||
color: "#fff",
|
||||
});
|
||||
const createBtn = createButton(createButtonLabel, () => close([...selectedAssets.values()]), { primary: true });
|
||||
buttonRow.append(selectionTools, cancelBtn, createBtn);
|
||||
|
||||
dialog.append(titleEl, controlsRow, selectionInfo, content, buttonRow);
|
||||
@@ -784,84 +770,35 @@ function el(tag, styles = {}, text = "") {
|
||||
return element;
|
||||
}
|
||||
|
||||
// The panel's controls are the kit's (js/fbui): text fields, selects and
|
||||
// buttons; `styles` adds layout on top.
|
||||
function createInput(value, placeholder, styles = {}) {
|
||||
const input = document.createElement("input");
|
||||
const input = el("input", styles);
|
||||
input.className = "fbui-text";
|
||||
input.type = "text";
|
||||
input.spellcheck = false;
|
||||
input.value = value || "";
|
||||
input.placeholder = placeholder || "";
|
||||
input.style.cssText = `
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
`;
|
||||
Object.assign(input.style, styles);
|
||||
input.addEventListener("focus", () => { input.style.borderColor = STYLE.accent; });
|
||||
input.addEventListener("blur", () => { input.style.borderColor = STYLE.inputBorder; });
|
||||
return input;
|
||||
}
|
||||
|
||||
function createTextarea(value, placeholder, styles = {}) {
|
||||
const textarea = document.createElement("textarea");
|
||||
const textarea = el("textarea", { height: "auto", minHeight: "120px", padding: "8px", resize: "none", lineHeight: "1.45", userSelect: "text", ...styles });
|
||||
textarea.className = "fbui-text";
|
||||
textarea.value = value || "";
|
||||
textarea.placeholder = placeholder || "";
|
||||
textarea.style.cssText = `
|
||||
width: 100%;
|
||||
min-height: 120px;
|
||||
resize: none;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 14px;
|
||||
padding: 8px;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
font-family: inherit;
|
||||
`;
|
||||
Object.assign(textarea.style, styles);
|
||||
textarea.addEventListener("focus", () => { textarea.style.borderColor = STYLE.accent; });
|
||||
textarea.addEventListener("blur", () => { textarea.style.borderColor = STYLE.inputBorder; });
|
||||
return textarea;
|
||||
}
|
||||
|
||||
function createButton(text, onClick, styles = {}) {
|
||||
const button = document.createElement("button");
|
||||
button.textContent = text;
|
||||
button.style.cssText = `
|
||||
background: ${STYLE.buttonBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
color: ${STYLE.textPrimary};
|
||||
padding: 6px 12px;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
`;
|
||||
Object.assign(button.style, styles);
|
||||
button.addEventListener("click", onClick);
|
||||
return button;
|
||||
function createButton(text, onClick, { primary = false, ...styles } = {}) {
|
||||
const control = kitButton(text, { primary, onClick });
|
||||
Object.assign(control.style, styles);
|
||||
return control;
|
||||
}
|
||||
|
||||
function createSelect(value, options, styles = {}) {
|
||||
const select = document.createElement("select");
|
||||
select.style.cssText = `
|
||||
width: 100%;
|
||||
padding: 7px 10px;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
`;
|
||||
Object.assign(select.style, styles);
|
||||
const select = el("select", { width: "100%", ...styles });
|
||||
select.className = "fbui-select";
|
||||
for (const opt of options) {
|
||||
const option = document.createElement("option");
|
||||
option.value = opt.value;
|
||||
@@ -869,8 +806,6 @@ function createSelect(value, options, styles = {}) {
|
||||
if (opt.value === value) option.selected = true;
|
||||
select.appendChild(option);
|
||||
}
|
||||
select.addEventListener("focus", () => { select.style.borderColor = STYLE.accent; });
|
||||
select.addEventListener("blur", () => { select.style.borderColor = STYLE.inputBorder; });
|
||||
return select;
|
||||
}
|
||||
|
||||
@@ -898,26 +833,13 @@ function replaceSelectOptions(select, options, value) {
|
||||
}
|
||||
|
||||
function createNumberInput(value, options = {}, styles = {}) {
|
||||
const input = document.createElement("input");
|
||||
const input = el("input", { width: "84px", ...styles });
|
||||
input.className = "fbui-text";
|
||||
input.type = "number";
|
||||
input.value = String(value ?? "1");
|
||||
if (options.min !== undefined && options.min !== null) input.min = String(options.min);
|
||||
if (options.max !== undefined && options.max !== null) input.max = String(options.max);
|
||||
if (options.step !== undefined && options.step !== null) input.step = String(options.step);
|
||||
input.style.cssText = `
|
||||
width: 84px;
|
||||
padding: 7px 8px;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
`;
|
||||
Object.assign(input.style, styles);
|
||||
input.addEventListener("focus", () => { input.style.borderColor = STYLE.accent; });
|
||||
input.addEventListener("blur", () => { input.style.borderColor = STYLE.inputBorder; });
|
||||
return input;
|
||||
}
|
||||
|
||||
@@ -946,23 +868,8 @@ function createPickerTrigger(placeholder = "(None)", styles = {}) {
|
||||
button.type = "button";
|
||||
button.value = "";
|
||||
button.title = placeholder;
|
||||
button.style.cssText = `
|
||||
width: 100%;
|
||||
min-height: 34px;
|
||||
padding: 7px 10px;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
font-size: 13px;
|
||||
box-sizing: border-box;
|
||||
outline: none;
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
`;
|
||||
button.className = "fbui-text";
|
||||
button.style.cssText = "cursor: pointer; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;";
|
||||
Object.assign(button.style, styles);
|
||||
button.dataset.placeholder = placeholder;
|
||||
button.setSelectedItem = (item) => {
|
||||
@@ -971,12 +878,10 @@ function createPickerTrigger(placeholder = "(None)", styles = {}) {
|
||||
button.value = value;
|
||||
button.textContent = value ? label : placeholder;
|
||||
button.title = value ? `${label}${item?.pickerMeta ? `\n${item.pickerMeta}` : ""}` : placeholder;
|
||||
button.style.color = value ? "#fff" : STYLE.textMuted;
|
||||
button.style.color = value ? T.ink : T.faint;
|
||||
};
|
||||
button.getSelectedValue = () => String(button.value || "").trim();
|
||||
button.setSelectedItem(null);
|
||||
button.addEventListener("focus", () => { button.style.borderColor = STYLE.accent; });
|
||||
button.addEventListener("blur", () => { button.style.borderColor = STYLE.inputBorder; });
|
||||
return button;
|
||||
}
|
||||
|
||||
@@ -1082,7 +987,7 @@ async function fetchAvailableComposerLoras(refresh = false) {
|
||||
}
|
||||
|
||||
if (!rawPaths.length) {
|
||||
const resp = await fetch("/prompt-manager-advanced/available-loras", { cache: "no-store" });
|
||||
const resp = await api.fetchApi("/prompt-manager-advanced/available-loras", { cache: "no-store" });
|
||||
const data = await resp.json();
|
||||
if (resp.ok && data?.success && Array.isArray(data?.loras)) {
|
||||
rawPaths = [...new Set(data.loras.map((x) => String(x || "").trim()).filter(Boolean))];
|
||||
@@ -1199,17 +1104,17 @@ function showTextAssetPicker({ title, items, initialValue = "", emptyLabel = "(N
|
||||
list.style.cssText = `
|
||||
width: 100%;
|
||||
min-height: 280px;
|
||||
background: ${STYLE.inputBg};
|
||||
border: 1px solid ${STYLE.inputBorder};
|
||||
border-radius: 4px;
|
||||
color: #fff;
|
||||
background: ${T.card};
|
||||
border: 1px solid ${T.plateEdge};
|
||||
border-radius: ${RADIUS}px;
|
||||
color: ${T.inkSoft};
|
||||
padding: 6px;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
list.multiple = false;
|
||||
const buttonRow = el("div", { display: "flex", justifyContent: "flex-end", gap: "8px" });
|
||||
const cancelBtn = createButton("Cancel", () => close(null));
|
||||
const selectBtn = createButton("Select", () => close(list.value), { background: "#2b6d3a", borderColor: "#4a9158", color: "#fff" });
|
||||
const selectBtn = createButton("Select", () => close(list.value), { primary: true });
|
||||
buttonRow.append(cancelBtn, selectBtn);
|
||||
dialog.append(titleEl, filterInput, list, buttonRow);
|
||||
overlay.appendChild(dialog);
|
||||
@@ -1697,7 +1602,7 @@ export function createPromptBrowserEditPanel(options) {
|
||||
"Save Prompt Group Settings",
|
||||
`Save prompt group settings for "${groupMeta.typeName || promptType}"?`,
|
||||
"Save",
|
||||
"#2b6d3a"
|
||||
{ danger: false }
|
||||
);
|
||||
if (!confirmed) return;
|
||||
|
||||
@@ -1730,7 +1635,7 @@ export function createPromptBrowserEditPanel(options) {
|
||||
} else {
|
||||
await _showInfo("Save Failed", result?.error || "Failed to save prompt group settings.");
|
||||
}
|
||||
}, { background: "#2b6d3a", borderColor: "#4a9158", color: "#fff" });
|
||||
}, { primary: true });
|
||||
groupBody.appendChild(saveGroupSettingsBtn);
|
||||
|
||||
const categoryBasePromptInfoText = "Thumbnail prompt for this category.\nIf empty, the prompt group thumbnail prompt is used.";
|
||||
@@ -1802,7 +1707,6 @@ export function createPromptBrowserEditPanel(options) {
|
||||
"Update Category Settings",
|
||||
`Category settings for "${categoryLabel}" already exist. Update them?`,
|
||||
"Update",
|
||||
"#c44"
|
||||
);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
@@ -1835,11 +1739,12 @@ export function createPromptBrowserEditPanel(options) {
|
||||
} else {
|
||||
await _showInfo("Save Failed", result?.error || "Failed to save category settings.");
|
||||
}
|
||||
}, { background: "#2b6d3a", borderColor: "#4a9158", color: "#fff" });
|
||||
}, { primary: true });
|
||||
settingsBody.appendChild(saveSettingsBtn);
|
||||
|
||||
// Prompt editor section
|
||||
const promptNameInput = createInput("", "Prompt name");
|
||||
promptNameInput.classList.add("entry");
|
||||
promptBody.appendChild(promptNameInput);
|
||||
promptNameInput.addEventListener("input", () => {
|
||||
const nextName = String(promptNameInput.value || "").trim();
|
||||
@@ -2099,11 +2004,11 @@ export function createPromptBrowserEditPanel(options) {
|
||||
|
||||
const saveNewBtn = createButton("Save New", async () => {
|
||||
await doSavePrompt(false);
|
||||
}, { background: "#313843", borderColor: "#5f6773", color: STYLE.textPrimary });
|
||||
}, {});
|
||||
|
||||
const saveBtn = createButton("Save", async () => {
|
||||
await doPrimaryPromptAction(false);
|
||||
}, { background: "#2b6d3a", borderColor: "#4a9158", color: "#fff" });
|
||||
}, { primary: true });
|
||||
saveNewBtn.style.display = "none";
|
||||
editorButtonRow.appendChild(saveNewBtn);
|
||||
editorButtonRow.appendChild(saveBtn);
|
||||
@@ -2256,7 +2161,7 @@ export function createPromptBrowserEditPanel(options) {
|
||||
? `Update prompt "${originalName}" in category "${categoryLabel}"?`
|
||||
: `Update prompt "${originalName}" and rename it to "${nextName}" in category "${categoryLabel}"?`,
|
||||
"Update",
|
||||
"#2b6d3a"
|
||||
{ danger: false }
|
||||
);
|
||||
if (!confirmed) return { success: false };
|
||||
|
||||
@@ -2389,7 +2294,8 @@ export function createPromptBrowserEditPanel(options) {
|
||||
generateBtn.textContent = "Generate Thumbnail";
|
||||
}
|
||||
});
|
||||
generateBtn.style.flex = "1";
|
||||
// Shrinks with a narrow browser, its label cut short, so the row never scrolls sideways.
|
||||
Object.assign(generateBtn.style, { flex: "1", minWidth: "0", overflow: "hidden", textOverflow: "ellipsis" });
|
||||
generateBtn.style.height = thumbnailControlHeight;
|
||||
generateBtn.style.minHeight = thumbnailControlHeight;
|
||||
const refreshThumbnailModelButton = () => {
|
||||
@@ -2454,7 +2360,6 @@ export function createPromptBrowserEditPanel(options) {
|
||||
"Overwrite Prompt",
|
||||
`Prompt "${name}" already exists in category "${categoryLabel}". Replace it?`,
|
||||
"Replace",
|
||||
"#c44"
|
||||
);
|
||||
}
|
||||
if (!overwrite) return { success: false };
|
||||
@@ -2539,7 +2444,6 @@ export function createPromptBrowserEditPanel(options) {
|
||||
"Unsaved Changes",
|
||||
"You have unsaved changes. Discard them?",
|
||||
"Discard",
|
||||
"#c44"
|
||||
);
|
||||
return confirmed;
|
||||
}
|
||||
@@ -2917,7 +2821,7 @@ export function createPromptBrowserEditPanel(options) {
|
||||
"Prompts Created",
|
||||
`${created} prompt(s) created in "${category}".${failed ? ` ${failed} failed.` : ""}${invalid ? ` ${invalid} line(s) were skipped because they were not in the format \"Title - Prompt text\".` : ""}`
|
||||
);
|
||||
}, { background: "#2b6d3a", borderColor: "#4a9158", color: "#fff" });
|
||||
}, { primary: true });
|
||||
|
||||
buttonRow.appendChild(cancelBtn);
|
||||
buttonRow.appendChild(createBtn);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -346,12 +346,6 @@ function getComposerExportData(node) {
|
||||
: { __meta__: { schema_version: 2, storage: "type_files" }, _types_: {} };
|
||||
}
|
||||
|
||||
function normalizeComposerFilename(name, fallback = "prompt_composer_data.json") {
|
||||
const trimmed = String(name || "").trim();
|
||||
if (!trimmed) return fallback;
|
||||
return trimmed.toLowerCase().endsWith(".json") ? trimmed : `${trimmed}.json`;
|
||||
}
|
||||
|
||||
function buildComposerExportTimestamp(date = new Date()) {
|
||||
const pad = (value) => String(value).padStart(2, "0");
|
||||
const year = pad(Number(date?.getFullYear?.() || 0) % 100);
|
||||
@@ -363,535 +357,6 @@ function buildComposerExportTimestamp(date = new Date()) {
|
||||
return `${year}.${month}.${day}_${hours}.${minutes}.${seconds}`;
|
||||
}
|
||||
|
||||
function joinComposerBrowserPath(base, leaf) {
|
||||
if (!base || !leaf) return leaf || base || "";
|
||||
const cleanBase = String(base).replace(/[\\/]+$/, "");
|
||||
const cleanLeaf = String(leaf).replace(/^[\\/]+/, "");
|
||||
return `${cleanBase}/${cleanLeaf}`;
|
||||
}
|
||||
|
||||
function composerBrowserBasename(path) {
|
||||
const normalized = String(path || "").replace(/\\/g, "/");
|
||||
const idx = normalized.lastIndexOf("/");
|
||||
return idx >= 0 ? normalized.slice(idx + 1) : normalized;
|
||||
}
|
||||
|
||||
async function fetchComposerBrowserListing(path = "") {
|
||||
const params = new URLSearchParams();
|
||||
if (path) params.set("path", path);
|
||||
params.set("kind", "json");
|
||||
const query = params.toString();
|
||||
const response = await fetch(`/prompt-extractor/path-browser/list${query ? `?${query}` : ""}`);
|
||||
if (!response.ok) {
|
||||
let message = `Request failed (${response.status})`;
|
||||
try {
|
||||
const err = await response.json();
|
||||
if (err?.error) message = err.error;
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return await response.json();
|
||||
}
|
||||
|
||||
async function requestComposerFilename(defaultValue = "prompt_composer_data.json") {
|
||||
return await new Promise((resolve) => {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.7);
|
||||
z-index: 9999;
|
||||
`;
|
||||
|
||||
const dialog = document.createElement("div");
|
||||
dialog.style.cssText = `
|
||||
position: fixed;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
transform: translate(-50%, -50%);
|
||||
width: min(520px, calc(100vw - 48px));
|
||||
background: ${UI.panel || "hsl(216 11% 15%)"};
|
||||
border: 1px solid ${UI.panelBorder || "hsl(216 20% 65% / 0.24)"};
|
||||
border-radius: 10px;
|
||||
padding: 18px 20px;
|
||||
box-shadow: 0 10px 32px rgba(0,0,0,0.45);
|
||||
color: ${UI.textPrimary || "hsl(0 0% 87%)"};
|
||||
z-index: 10000;
|
||||
box-sizing: border-box;
|
||||
`;
|
||||
|
||||
dialog.innerHTML = `
|
||||
<div style="font-size: 16px; font-weight: 700; margin-bottom: 10px;">Save Prompt Composer JSON</div>
|
||||
<div style="color: ${UI.textMuted || "hsl(0 0% 67%)"}; line-height: 1.45; margin-bottom: 12px;">
|
||||
Choose a filename for the exported Prompt Composer library.
|
||||
</div>
|
||||
<input class="filename-input" type="text" value="${String(defaultValue || "prompt_composer_data.json").replace(/"/g, """)}" style="width: 100%; height: 34px; padding: 0 10px; border-radius: 8px; border: 1px solid ${UI.inputBorder || "hsl(218 10% 41%)"}; background: ${UI.inputBg || "hsl(220 15% 10%)"}; color: ${UI.textPrimary || "hsl(0 0% 87%)"}; box-sizing: border-box; margin-bottom: 16px;" />
|
||||
<div style="display: flex; justify-content: flex-end; gap: 10px; flex-wrap: wrap;">
|
||||
<button class="cancel-btn" style="padding: 7px 12px; background: ${UI.buttonBg || "hsl(219 16% 18%)"}; color: ${UI.textPrimary || "hsl(0 0% 87%)"}; border: 1px solid ${UI.inputBorder || "hsl(218 10% 41%)"}; border-radius: 7px; cursor: pointer;">Cancel</button>
|
||||
<button class="save-btn" style="padding: 7px 12px; background: ${UI.accentSoft || "hsl(208 73% 57% / 0.16)"}; color: #dbeafe; border: 1px solid ${UI.accentBorder || "hsl(208 73% 57% / 0.65)"}; border-radius: 7px; cursor: pointer;">Save</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
const input = dialog.querySelector(".filename-input");
|
||||
|
||||
const cleanup = () => {
|
||||
overlay.parentNode?.removeChild(overlay);
|
||||
dialog.parentNode?.removeChild(dialog);
|
||||
document.removeEventListener("keydown", onKeyDown, true);
|
||||
};
|
||||
|
||||
const finish = (value) => {
|
||||
cleanup();
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
const onKeyDown = (event) => {
|
||||
if (event.key === "Escape") {
|
||||
finish(null);
|
||||
} else if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
finish(normalizeComposerFilename(input?.value, defaultValue));
|
||||
}
|
||||
};
|
||||
|
||||
dialog.querySelector(".cancel-btn").onclick = () => finish(null);
|
||||
dialog.querySelector(".save-btn").onclick = () => finish(normalizeComposerFilename(input?.value, defaultValue));
|
||||
overlay.onclick = () => finish(null);
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
document.body.appendChild(dialog);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
input?.focus();
|
||||
input?.select();
|
||||
});
|
||||
}
|
||||
|
||||
async function selectComposerSaveTarget(defaultValue = "prompt_composer_data.json") {
|
||||
if (window.showSaveFilePicker) {
|
||||
try {
|
||||
const handle = await window.showSaveFilePicker({
|
||||
suggestedName: normalizeComposerFilename(defaultValue, "prompt_composer_data.json"),
|
||||
types: [{
|
||||
description: "JSON Files",
|
||||
accept: { "application/json": [".json"] },
|
||||
}],
|
||||
});
|
||||
if (!handle) return null;
|
||||
return { mode: "handle", handle };
|
||||
} catch (err) {
|
||||
if (err?.name === "AbortError") return null;
|
||||
console.warn("[PromptComposer] Save picker failed, trying directory picker:", err);
|
||||
}
|
||||
}
|
||||
|
||||
if (window.showDirectoryPicker) {
|
||||
try {
|
||||
const directoryHandle = await window.showDirectoryPicker();
|
||||
if (!directoryHandle) return null;
|
||||
const filename = await requestComposerFilename(defaultValue);
|
||||
if (!filename) return null;
|
||||
const handle = await directoryHandle.getFileHandle(filename, { create: true });
|
||||
return { mode: "handle", handle };
|
||||
} catch (err) {
|
||||
if (err?.name === "AbortError") return null;
|
||||
console.warn("[PromptComposer] Directory picker failed, falling back to download:", err);
|
||||
}
|
||||
}
|
||||
|
||||
const filename = await requestComposerFilename(defaultValue);
|
||||
if (!filename) return null;
|
||||
return { mode: "download", filename };
|
||||
}
|
||||
|
||||
async function loadComposerLibraryFile(filePath) {
|
||||
const response = await api.fetchApi(`${COMPOSER_ENDPOINT_PREFIX}/load-prompts-file`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: filePath }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!response.ok || !result?.success) {
|
||||
throw new Error(result?.error || "Failed to load JSON file.");
|
||||
}
|
||||
return result.data;
|
||||
}
|
||||
|
||||
async function showComposerJsonBrowser({
|
||||
mode = "save",
|
||||
title = "Save Prompt Composer JSON",
|
||||
confirmLabel = "Save Here",
|
||||
defaultFilename = "prompt_composer_data.json",
|
||||
} = {}) {
|
||||
return await new Promise((resolve) => {
|
||||
const preferredStartDir = COMPOSER_BACKUP_BROWSER_DIR;
|
||||
const isSaveMode = mode === "save";
|
||||
let currentDir = "";
|
||||
let currentParent = null;
|
||||
let roots = [];
|
||||
let currentFiles = [];
|
||||
let currentDirs = [];
|
||||
let selectedFilePath = "";
|
||||
|
||||
const overlay = document.createElement("div");
|
||||
overlay.style.cssText = `
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
background: rgba(0,0,0,0.74);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
z-index: 10000;
|
||||
`;
|
||||
|
||||
const dialog = document.createElement("div");
|
||||
dialog.style.cssText = `
|
||||
background: #17191d;
|
||||
border: 1px solid rgba(255,255,255,0.08);
|
||||
border-radius: 4px;
|
||||
width: min(920px, calc(100vw - 48px));
|
||||
height: min(700px, calc(100vh - 48px));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
box-shadow: 0 18px 42px rgba(0,0,0,0.48);
|
||||
`;
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.style.cssText = `
|
||||
padding: 10px 14px 8px 14px;
|
||||
border-bottom: 1px solid rgba(255,255,255,0.1);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
`;
|
||||
|
||||
const topRow = document.createElement("div");
|
||||
topRow.style.cssText = "display:flex; justify-content:space-between; align-items:center; gap:12px;";
|
||||
topRow.innerHTML = `
|
||||
<h3 style="margin:0; color:#e5e7eb; font-size:16px; font-weight:600; letter-spacing:0.01em;">${title}</h3>
|
||||
<button class="close-btn" style="background:none; border:none; color:#8b9098; font-size:22px; cursor:pointer; padding:0; width:28px; height:28px;">×</button>
|
||||
`;
|
||||
header.appendChild(topRow);
|
||||
|
||||
const navRow = document.createElement("div");
|
||||
navRow.style.cssText = "display:flex; gap:6px; align-items:center; flex-wrap:nowrap;";
|
||||
const makeNavButton = (label) => {
|
||||
const button = document.createElement("button");
|
||||
button.type = "button";
|
||||
button.textContent = label;
|
||||
button.style.cssText = "background:#23262b; border:1px solid rgba(255,255,255,0.08); border-radius:3px; color:#cfd5de; min-width:28px; height:28px; padding:0 8px; cursor:pointer; font-size:13px;";
|
||||
button.onmouseover = () => { button.style.background = "#2a2e34"; };
|
||||
button.onmouseout = () => { button.style.background = "#23262b"; };
|
||||
return button;
|
||||
};
|
||||
const upBtn = makeNavButton("◀");
|
||||
const refreshBtn = makeNavButton("↻");
|
||||
const inputBtn = makeNavButton("In");
|
||||
const outputBtn = makeNavButton("Out");
|
||||
const homeBtn = makeNavButton("Home");
|
||||
const pathInput = document.createElement("input");
|
||||
pathInput.type = "text";
|
||||
pathInput.placeholder = "Paste folder path and press Enter";
|
||||
pathInput.style.cssText = "flex:1; min-width:240px; height:30px; font-size:14px; color:#e5e7eb; background:#111317; border:1px solid rgba(255,255,255,0.08); border-radius:3px; padding:0 10px; box-sizing:border-box;";
|
||||
navRow.appendChild(upBtn);
|
||||
navRow.appendChild(refreshBtn);
|
||||
navRow.appendChild(inputBtn);
|
||||
navRow.appendChild(outputBtn);
|
||||
navRow.appendChild(homeBtn);
|
||||
navRow.appendChild(pathInput);
|
||||
header.appendChild(navRow);
|
||||
|
||||
const body = document.createElement("div");
|
||||
body.style.cssText = "flex:1; min-height:0; overflow:hidden; padding:10px 14px 0 14px; display:flex; flex-direction:column; gap:0;";
|
||||
const listHeader = document.createElement("div");
|
||||
listHeader.textContent = "Name";
|
||||
listHeader.style.cssText = "height:30px; display:flex; align-items:center; padding:0 12px; background:#212121; color:#d7dbe1; font-size:14px; border:1px solid rgba(255,255,255,0.08); border-bottom:none; box-sizing:border-box;";
|
||||
const listing = document.createElement("div");
|
||||
listing.style.cssText = "flex:1; min-height:0; overflow:auto; display:flex; flex-direction:column; gap:0; background:#17191d; border:1px solid rgba(255,255,255,0.08);";
|
||||
body.appendChild(listHeader);
|
||||
body.appendChild(listing);
|
||||
|
||||
const footer = document.createElement("div");
|
||||
footer.style.cssText = `
|
||||
padding: 10px 14px 14px 14px;
|
||||
border-top: 1px solid rgba(255,255,255,0.1);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
`;
|
||||
const filenameRow = document.createElement("div");
|
||||
filenameRow.style.cssText = "display:flex; align-items:center; gap:10px;";
|
||||
const filenameLabel = document.createElement("span");
|
||||
filenameLabel.textContent = "Name:";
|
||||
filenameLabel.style.cssText = "font-size:14px; color:#d7dbe1; min-width:48px;";
|
||||
const filenameInput = document.createElement("input");
|
||||
filenameInput.type = "text";
|
||||
filenameInput.value = isSaveMode ? normalizeComposerFilename(defaultFilename, "prompt_composer_data.json") : "";
|
||||
filenameInput.readOnly = !isSaveMode;
|
||||
filenameInput.style.cssText = "flex:1; height:32px; padding:0 10px; border-radius:3px; border:1px solid rgba(255,255,255,0.08); background:#111317; color:#e5e7eb; box-sizing:border-box;";
|
||||
filenameRow.appendChild(filenameLabel);
|
||||
filenameRow.appendChild(filenameInput);
|
||||
footer.appendChild(filenameRow);
|
||||
|
||||
const footerButtons = document.createElement("div");
|
||||
footerButtons.style.cssText = "display:flex; justify-content:flex-end; gap:10px; flex-wrap:wrap;";
|
||||
const cancelBtn = document.createElement("button");
|
||||
cancelBtn.type = "button";
|
||||
cancelBtn.textContent = "Cancel";
|
||||
cancelBtn.style.cssText = "padding:7px 12px; background:#2a2f36; color:#e5e7eb; border:1px solid rgba(255,255,255,0.14); border-radius:7px; cursor:pointer;";
|
||||
const saveBtn = document.createElement("button");
|
||||
saveBtn.type = "button";
|
||||
saveBtn.textContent = confirmLabel;
|
||||
saveBtn.style.cssText = "padding:7px 12px; background:#23262b; color:#e5e7eb; border:1px solid rgba(255,255,255,0.14); border-radius:3px; cursor:pointer;";
|
||||
footerButtons.appendChild(cancelBtn);
|
||||
footerButtons.appendChild(saveBtn);
|
||||
footer.appendChild(footerButtons);
|
||||
|
||||
dialog.appendChild(header);
|
||||
dialog.appendChild(body);
|
||||
dialog.appendChild(footer);
|
||||
overlay.appendChild(dialog);
|
||||
|
||||
const cleanup = () => {
|
||||
overlay.parentNode?.removeChild(overlay);
|
||||
document.removeEventListener("keydown", onKeyDown, true);
|
||||
};
|
||||
|
||||
const finish = (value) => {
|
||||
cleanup();
|
||||
resolve(value);
|
||||
};
|
||||
|
||||
const renderListing = () => {
|
||||
listing.innerHTML = "";
|
||||
pathInput.value = currentDir || "";
|
||||
upBtn.disabled = !currentParent;
|
||||
upBtn.style.opacity = currentParent ? "1" : "0.45";
|
||||
|
||||
if (!currentDir && !roots.length) {
|
||||
const empty = document.createElement("div");
|
||||
empty.textContent = "No locations available.";
|
||||
empty.style.cssText = "text-align:center; padding:40px; color:#888;";
|
||||
listing.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentDir && roots.length) {
|
||||
roots.forEach((rootPath) => {
|
||||
const item = document.createElement("button");
|
||||
item.type = "button";
|
||||
item.textContent = rootPath;
|
||||
item.style.cssText = "text-align:left; min-height:38px; padding:0 12px; background:#17191d; color:#dce6f2; border:none; border-bottom:1px solid rgba(255,255,255,0.06); cursor:pointer;";
|
||||
item.onmouseover = () => { item.style.background = "#1f2937"; };
|
||||
item.onmouseout = () => { item.style.background = "#17191d"; };
|
||||
item.onclick = async () => {
|
||||
currentDir = rootPath;
|
||||
await loadListing(rootPath);
|
||||
};
|
||||
listing.appendChild(item);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!currentDirs.length && !currentFiles.length) {
|
||||
const empty = document.createElement("div");
|
||||
empty.textContent = "This folder is empty";
|
||||
empty.style.cssText = "padding:12px; color:#6b7280; font-size:14px; border-bottom:1px solid rgba(255,255,255,0.04);";
|
||||
listing.appendChild(empty);
|
||||
return;
|
||||
}
|
||||
|
||||
currentDirs.forEach((dir) => {
|
||||
const item = document.createElement("button");
|
||||
item.type = "button";
|
||||
item.textContent = dir.name;
|
||||
item.style.cssText = "text-align:left; min-height:40px; padding:0 12px; background:#17191d; color:#dce6f2; border:none; border-bottom:1px solid rgba(255,255,255,0.06); cursor:pointer;";
|
||||
item.onmouseover = () => { item.style.background = "#1d344d"; };
|
||||
item.onmouseout = () => { item.style.background = "#17191d"; };
|
||||
item.onclick = async () => {
|
||||
currentDir = dir.path;
|
||||
selectedFilePath = "";
|
||||
if (!isSaveMode) {
|
||||
filenameInput.value = "";
|
||||
}
|
||||
await loadListing(dir.path);
|
||||
};
|
||||
listing.appendChild(item);
|
||||
});
|
||||
|
||||
currentFiles.forEach((file) => {
|
||||
const item = document.createElement("button");
|
||||
item.type = "button";
|
||||
item.textContent = file.name;
|
||||
item.style.cssText = "text-align:left; min-height:40px; padding:0 12px; background:#17191d; color:#dbeafe; border:none; border-bottom:1px solid rgba(255,255,255,0.06); cursor:pointer;";
|
||||
item.onmouseover = () => { item.style.background = "#125d90"; };
|
||||
item.onmouseout = () => { item.style.background = "#17191d"; };
|
||||
item.onclick = () => {
|
||||
selectedFilePath = file.path || joinComposerBrowserPath(currentDir, file.name);
|
||||
filenameInput.value = file.name;
|
||||
item.style.background = "#125d90";
|
||||
};
|
||||
item.ondblclick = async () => {
|
||||
selectedFilePath = file.path || joinComposerBrowserPath(currentDir, file.name);
|
||||
filenameInput.value = file.name;
|
||||
await confirmSelection();
|
||||
};
|
||||
listing.appendChild(item);
|
||||
});
|
||||
};
|
||||
|
||||
const loadListing = async (targetPath = currentDir) => {
|
||||
listing.innerHTML = '<div style="text-align:center; padding:40px; color:#888;">Loading...</div>';
|
||||
try {
|
||||
let data = await fetchComposerBrowserListing(targetPath || "");
|
||||
if (data.mode === "roots") {
|
||||
roots = Array.isArray(data.roots) ? data.roots : [];
|
||||
if (!targetPath) {
|
||||
currentDir = roots[0] || "";
|
||||
if (currentDir) {
|
||||
data = await fetchComposerBrowserListing(currentDir);
|
||||
} else {
|
||||
currentParent = null;
|
||||
currentDirs = [];
|
||||
currentFiles = [];
|
||||
renderListing();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
currentDir = data.current_path || currentDir || targetPath || "";
|
||||
currentParent = data.parent_path || null;
|
||||
roots = Array.isArray(data.roots) ? data.roots : roots;
|
||||
currentDirs = Array.isArray(data.dirs) ? data.dirs : [];
|
||||
currentFiles = Array.isArray(data.files) ? data.files : [];
|
||||
renderListing();
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("[PromptComposer] Error loading save browser listing:", error);
|
||||
listing.innerHTML = `<div style="text-align:center; padding:40px; color:rgba(220,53,69,0.9);">${String(error?.message || "Error loading folders")}</div>`;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const confirmSelection = async () => {
|
||||
if (!isSaveMode) {
|
||||
if (!selectedFilePath) {
|
||||
await showInfo("Open Failed", "Choose a JSON file first.");
|
||||
return;
|
||||
}
|
||||
finish(selectedFilePath);
|
||||
return;
|
||||
}
|
||||
|
||||
const filename = normalizeComposerFilename(filenameInput.value, defaultFilename);
|
||||
if (!currentDir) {
|
||||
await showInfo("Save Failed", "Choose a target folder first.");
|
||||
return;
|
||||
}
|
||||
if (!filename) {
|
||||
await showInfo("Save Failed", "Enter a filename first.");
|
||||
return;
|
||||
}
|
||||
const existing = currentFiles.some((file) => String(file?.name || "").trim().toLowerCase() === filename.toLowerCase());
|
||||
if (existing) {
|
||||
const overwrite = await showConfirm(
|
||||
"Overwrite JSON",
|
||||
`A file named "${filename}" already exists in this folder. Overwrite it?`,
|
||||
"Overwrite",
|
||||
"rgba(56, 130, 246, 0.96)"
|
||||
);
|
||||
if (!overwrite) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
finish(joinComposerBrowserPath(currentDir, filename));
|
||||
};
|
||||
|
||||
const onKeyDown = async (event) => {
|
||||
if (event.key === "Escape") {
|
||||
finish(null);
|
||||
} else if (event.key === "Enter" && document.activeElement === pathInput) {
|
||||
event.preventDefault();
|
||||
const next = pathInput.value.trim();
|
||||
if (next) {
|
||||
currentDir = next;
|
||||
await loadListing(next);
|
||||
}
|
||||
} else if (event.key === "Enter" && (document.activeElement === filenameInput || !isSaveMode)) {
|
||||
event.preventDefault();
|
||||
await confirmSelection();
|
||||
}
|
||||
};
|
||||
|
||||
topRow.querySelector(".close-btn").onclick = () => finish(null);
|
||||
cancelBtn.onclick = () => finish(null);
|
||||
saveBtn.onclick = async () => {
|
||||
await confirmSelection();
|
||||
};
|
||||
overlay.onclick = (event) => {
|
||||
if (event.target === overlay) finish(null);
|
||||
};
|
||||
upBtn.onclick = async () => {
|
||||
if (!currentParent) return;
|
||||
currentDir = currentParent;
|
||||
selectedFilePath = "";
|
||||
if (!isSaveMode) {
|
||||
filenameInput.value = "";
|
||||
}
|
||||
await loadListing(currentDir);
|
||||
};
|
||||
refreshBtn.onclick = async () => {
|
||||
await loadListing(currentDir);
|
||||
};
|
||||
inputBtn.onclick = async () => {
|
||||
const inputRoot = Array.isArray(roots) ? roots[0] : "";
|
||||
if (!inputRoot) return;
|
||||
currentDir = inputRoot;
|
||||
selectedFilePath = "";
|
||||
if (!isSaveMode) {
|
||||
filenameInput.value = "";
|
||||
}
|
||||
await loadListing(currentDir);
|
||||
};
|
||||
outputBtn.onclick = async () => {
|
||||
const outputRoot = Array.isArray(roots) ? roots[1] : "";
|
||||
if (!outputRoot) return;
|
||||
currentDir = outputRoot;
|
||||
selectedFilePath = "";
|
||||
if (!isSaveMode) {
|
||||
filenameInput.value = "";
|
||||
}
|
||||
await loadListing(currentDir);
|
||||
};
|
||||
homeBtn.onclick = async () => {
|
||||
currentDir = COMPOSER_BACKUP_BROWSER_DIR;
|
||||
selectedFilePath = "";
|
||||
if (!isSaveMode) {
|
||||
filenameInput.value = "";
|
||||
}
|
||||
await loadListing(currentDir);
|
||||
};
|
||||
|
||||
document.body.appendChild(overlay);
|
||||
document.addEventListener("keydown", onKeyDown, true);
|
||||
void (async () => {
|
||||
const loadedPreferred = await loadListing(preferredStartDir);
|
||||
if (!loadedPreferred) {
|
||||
await loadListing("");
|
||||
}
|
||||
})();
|
||||
if (isSaveMode) {
|
||||
filenameInput.focus();
|
||||
filenameInput.select();
|
||||
} else {
|
||||
pathInput.focus();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function findExistingComposerCategoryName(promptsData, category) {
|
||||
const normalized = String(category || "").trim().toLowerCase();
|
||||
if (!normalized || !promptsData || typeof promptsData !== "object") return null;
|
||||
|
||||
+192
-11
@@ -1210,6 +1210,52 @@ function isPreviewableFile(filename) {
|
||||
return imageExtensions.includes(ext) || videoExtensions.includes(ext);
|
||||
}
|
||||
|
||||
// --- Arrow-key media navigation (Left/Right steps files while hovering a node) ---
|
||||
let _peHoveredNode = null;
|
||||
let _peKeyListenerInstalled = false;
|
||||
|
||||
function isPromptExtractorNodeInGraph(node) {
|
||||
if (!node || !app.graph?._nodes) return false;
|
||||
return app.graph._nodes.includes(node);
|
||||
}
|
||||
|
||||
function getActivePromptExtractorNode() {
|
||||
// Hover-only: only react when the cursor is actually over a live node.
|
||||
if (_peHoveredNode && !_peHoveredNode.flags?.collapsed && isPromptExtractorNodeInGraph(_peHoveredNode)) {
|
||||
return _peHoveredNode;
|
||||
}
|
||||
if (_peHoveredNode && !isPromptExtractorNodeInGraph(_peHoveredNode)) {
|
||||
_peHoveredNode = null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isTypingTarget(target) {
|
||||
if (!target) return false;
|
||||
const tag = String(target.tagName || "").toUpperCase();
|
||||
return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || !!target.isContentEditable;
|
||||
}
|
||||
|
||||
function installArrowKeyNavigation() {
|
||||
if (_peKeyListenerInstalled) return;
|
||||
_peKeyListenerInstalled = true;
|
||||
|
||||
window.addEventListener("keydown", (event) => {
|
||||
if (event.defaultPrevented) return;
|
||||
if (event.key !== "ArrowLeft" && event.key !== "ArrowRight") return;
|
||||
if (event.ctrlKey || event.altKey || event.metaKey || event.shiftKey) return;
|
||||
if (isTypingTarget(event.target)) return;
|
||||
|
||||
const node = getActivePromptExtractorNode();
|
||||
if (!node || typeof node._stepImageByDelta !== "function") return;
|
||||
|
||||
const dir = event.key === "ArrowRight" ? 1 : -1;
|
||||
if (!node._stepImageByDelta(dir)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
}, true);
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptExtractor",
|
||||
|
||||
@@ -1495,6 +1541,64 @@ app.registerExtension({
|
||||
}
|
||||
node.setDirtyCanvas(true);
|
||||
};
|
||||
|
||||
// Build the flat list of selectable file values (same order as
|
||||
// the picker combo) for arrow-key stepping.
|
||||
const listImageValues = () => {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
|
||||
const add = (v) => {
|
||||
if (typeof v !== "string") return;
|
||||
const value = stripAnnotation(v);
|
||||
if (!value || value === "(none)" || seen.has(value)) return;
|
||||
seen.add(value);
|
||||
out.push(value);
|
||||
};
|
||||
|
||||
const map = node._imagePickerMap;
|
||||
if (map && typeof map === "object") {
|
||||
for (const value of Object.values(map)) {
|
||||
add(value);
|
||||
}
|
||||
if (out.length > 0) return out;
|
||||
}
|
||||
|
||||
const values = imageWidget.options.values;
|
||||
if (Array.isArray(values)) {
|
||||
for (const value of values) add(value);
|
||||
} else if (values && typeof values === "object") {
|
||||
for (const value of Object.values(values)) add(value);
|
||||
}
|
||||
|
||||
return out;
|
||||
};
|
||||
|
||||
node._stepImageByDelta = (delta) => {
|
||||
if (!imageWidget) return false;
|
||||
|
||||
// When the video input is connected the picker UI is hidden,
|
||||
// so stepping files is not meaningful.
|
||||
const videoInput = (node.inputs || []).find(i => i?.name === "video");
|
||||
if (videoInput && videoInput.link != null) return false;
|
||||
|
||||
const values = listImageValues();
|
||||
if (values.length <= 1) return false;
|
||||
|
||||
const dir = delta >= 0 ? 1 : -1;
|
||||
const current = stripAnnotation(imageWidget.value);
|
||||
const currentIndex = values.indexOf(current);
|
||||
|
||||
let nextIndex;
|
||||
if (currentIndex < 0) {
|
||||
nextIndex = dir > 0 ? 0 : values.length - 1;
|
||||
} else {
|
||||
nextIndex = (currentIndex + dir + values.length) % values.length;
|
||||
}
|
||||
|
||||
setImageFilename(values[nextIndex]);
|
||||
return true;
|
||||
};
|
||||
|
||||
// Watch for value changes to update metadata indicator
|
||||
const originalOnDrawForeground = node.onDrawForeground;
|
||||
@@ -1591,17 +1695,11 @@ app.registerExtension({
|
||||
// Mark node as needing update
|
||||
node.setDirtyCanvas(true);
|
||||
}, sf, {
|
||||
enableNavigation: true,
|
||||
navKind: "all",
|
||||
allowedTypes: ["image", "video", "json"],
|
||||
initialPath,
|
||||
selectedAbsPath,
|
||||
viewMode: node.properties?._fileBrowserViewMode || "medium",
|
||||
onViewModeChange: (mode) => {
|
||||
if (!node.properties) node.properties = {};
|
||||
node.properties._fileBrowserViewMode = mode;
|
||||
},
|
||||
});
|
||||
navKind: "all",
|
||||
allowedTypes: ["image", "video", "json"],
|
||||
initialPath,
|
||||
selectedAbsPath,
|
||||
});
|
||||
},
|
||||
serialize: false // Don't save button state
|
||||
};
|
||||
@@ -1609,6 +1707,7 @@ app.registerExtension({
|
||||
// Insert button right after the image widget
|
||||
this.widgets.splice(imageWidgetIndex + 2, 0, browseButton);
|
||||
Object.defineProperty(browseButton, "node", { value: node });
|
||||
node._browseFilesButton = browseButton;
|
||||
|
||||
// Track if current file is a video for UI behavior
|
||||
node._isVideoFile = false;
|
||||
@@ -1997,11 +2096,47 @@ app.registerExtension({
|
||||
}
|
||||
canvas.canvas.style.cursor = '';
|
||||
}
|
||||
} else if (isPosOverPreview(localPos)) {
|
||||
canvas.canvas.style.cursor = 'pointer';
|
||||
canvas.canvas.title = 'Click to browse files';
|
||||
} else {
|
||||
canvas.canvas.style.cursor = '';
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// ── Click on the preview thumbnail to open the file browser ──
|
||||
// The preview is drawn by LiteGraph in the node body below all
|
||||
// visible widgets, so hit-test that area on the canvas.
|
||||
const isVideoInputConnected = () =>
|
||||
(node.inputs || []).some(i => i?.name === "video" && i.link != null);
|
||||
|
||||
const getPreviewBodyTop = () => {
|
||||
const titleHeight = LiteGraph.NODE_TITLE_HEIGHT || 30;
|
||||
const widgetHeight = LiteGraph.NODE_WIDGET_HEIGHT || 20;
|
||||
let bodyTop = titleHeight;
|
||||
for (const w of node.widgets || []) {
|
||||
if (w.hidden || !Number.isFinite(w.last_y)) continue;
|
||||
const size = typeof w.computeSize === "function" ? w.computeSize(node.size?.[0] || 320) : null;
|
||||
const height = Number(size?.[1]) || widgetHeight;
|
||||
bodyTop = Math.max(bodyTop, w.last_y + Math.max(1, height));
|
||||
}
|
||||
return bodyTop + 6;
|
||||
};
|
||||
|
||||
const isPosOverPreview = (localPos) => {
|
||||
if (!node.imgs || node.imgs.length === 0) return false;
|
||||
if (node.flags && node.flags.collapsed) return false;
|
||||
if (!node._browseFilesButton) return false;
|
||||
if (isVideoInputConnected()) return false;
|
||||
const bodyTop = getPreviewBodyTop();
|
||||
const bodyH = (node.size?.[1] || 0) - bodyTop;
|
||||
if (bodyH <= 10) return false;
|
||||
return localPos[0] >= 0 && localPos[0] <= (node.size?.[0] || 0) &&
|
||||
localPos[1] >= bodyTop && localPos[1] <= bodyTop + bodyH;
|
||||
};
|
||||
|
||||
// Handle click on preview icon
|
||||
const onMouseDown = node.onMouseDown;
|
||||
node.onMouseDown = function(e, localPos, canvas) {
|
||||
@@ -2036,9 +2171,39 @@ app.registerExtension({
|
||||
}
|
||||
}
|
||||
|
||||
// Left click on the preview thumbnail opens the file browser
|
||||
// (on mouse up, so node drags don't trigger it).
|
||||
if (e.button === 0 && isPosOverPreview(localPos)) {
|
||||
node._previewClickCandidate = { x: localPos[0], y: localPos[1] };
|
||||
} else {
|
||||
node._previewClickCandidate = null;
|
||||
}
|
||||
|
||||
return onMouseDown ? onMouseDown.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
const origOnMouseUp = node.onMouseUp;
|
||||
node.onMouseUp = function(e, localPos, canvas) {
|
||||
const candidate = node._previewClickCandidate;
|
||||
node._previewClickCandidate = null;
|
||||
if (candidate && e.button === 0 && isPosOverPreview(localPos)) {
|
||||
const dx = localPos[0] - candidate.x;
|
||||
const dy = localPos[1] - candidate.y;
|
||||
// Only treat it as a click if the pointer barely moved
|
||||
// (a drag to move the node should not open the browser).
|
||||
if (dx * dx + dy * dy <= 25) {
|
||||
const browseButton = node._browseFilesButton;
|
||||
if (browseButton && typeof browseButton.callback === "function") {
|
||||
Promise.resolve(browseButton.callback()).catch((err) =>
|
||||
console.error('[PromptExtractor] Error opening browser from preview:', err)
|
||||
);
|
||||
}
|
||||
return true; // Consume the event
|
||||
}
|
||||
}
|
||||
return origOnMouseUp ? origOnMouseUp.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
// ── Ghost the file-picker UI when a VIDEO input is connected ──
|
||||
// When the optional "video" input is linked, extraction reads the
|
||||
// connected video directly, so the image/source/browse widgets are
|
||||
@@ -2099,6 +2264,22 @@ app.registerExtension({
|
||||
// Initial state.
|
||||
setTimeout(updateVideoConnectedUI, 100);
|
||||
|
||||
// Install arrow-key file navigation (Left/Right steps media while
|
||||
// hovering this node).
|
||||
installArrowKeyNavigation();
|
||||
|
||||
const origOnMouseEnter = node.onMouseEnter;
|
||||
node.onMouseEnter = function () {
|
||||
_peHoveredNode = this;
|
||||
return origOnMouseEnter ? origOnMouseEnter.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
const origOnMouseLeave = node.onMouseLeave;
|
||||
node.onMouseLeave = function () {
|
||||
if (_peHoveredNode === this) _peHoveredNode = null;
|
||||
return origOnMouseLeave ? origOnMouseLeave.apply(this, arguments) : undefined;
|
||||
};
|
||||
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
+18
-71
@@ -22,27 +22,18 @@ import {
|
||||
|
||||
const HUB_TITLE = "Prompt Library Hub";
|
||||
const STYLE_ID = "pm-library-hub-style";
|
||||
const KIND_STORAGE_KEY = "pm-library-hub-kind";
|
||||
|
||||
// Saved prompt kinds share prompt_manager_data.json and are told apart by the browser's Type filter.
|
||||
const PROMPT_KINDS = [
|
||||
{ id: "prompt", label: "Prompt Manager", badge: "P", color: "56, 130, 246", hint: "Saved from Prompt Manager or Library Manager." },
|
||||
{ id: "compose", label: "Prompt Composer", badge: "C", color: "47, 146, 72", hint: "Prompt Composer setups saved with Library Manager." },
|
||||
{ id: "layout", label: "Prompt Layout", badge: "L", color: "124, 92, 220", hint: "Prompt Layout Builder layouts saved with Library Manager." },
|
||||
{ id: "recipe", label: "Prompt Recipe", badge: "R", color: "235, 140, 35", hint: "Recipes saved with Library Manager." },
|
||||
];
|
||||
|
||||
// Saved prompts of every type (prompts, recipes, Composer setups, layouts) share
|
||||
// prompt_manager_data.json; the Prompt Browser's Type filter tells them apart.
|
||||
const SECTIONS = [
|
||||
{ id: "prompts", title: "Saved Prompts", store: "manager", kinds: PROMPT_KINDS, unit: "entr" },
|
||||
{ id: "prompts", title: "Saved Prompts", store: "manager", hint: "Prompts, recipes, Composer setups and layouts saved from Prompt Manager or Library Manager. Filter them by Type in the browser.", unit: "entr" },
|
||||
{ id: "snippets", title: "Saved Snippets", browseTitle: "Saved Composer Snippets", store: "composer", hint: "Prompt snippets used by Prompt Composer.", unit: "snippet" },
|
||||
{ id: "system", title: "Saved System Prompts", store: "generator", hint: "System prompts used by Prompt Generator.", unit: "prompt" },
|
||||
];
|
||||
|
||||
const plural = (count, unit) => `${count} ${unit === "entr" ? (count === 1 ? "entry" : "entries") : `${unit}${count === 1 ? "" : "s"}`}`;
|
||||
|
||||
function libraryFor(section, kind) {
|
||||
if (!kind) return { id: section.id, title: section.browseTitle || section.title, store: section.store, unit: section.unit };
|
||||
return { id: `${section.id}_${kind.id}`, title: `${section.title} - ${kind.label}`, store: section.store, filter: kind.id, unit: section.unit };
|
||||
function libraryFor(section) {
|
||||
return { id: section.id, title: section.browseTitle || section.title, store: section.store, unit: section.unit };
|
||||
}
|
||||
|
||||
const STORE_ENDPOINTS = {
|
||||
@@ -77,7 +68,7 @@ function categoryNames(data) {
|
||||
function entryNames(library, category) {
|
||||
const data = hosts[library.store].prompts;
|
||||
if (library.store === "manager") {
|
||||
return getPromptNamesForCategory(hosts.manager, category, { contentFilter: library.filter, endpointPrefix: PROMPT_ADVANCED_ENDPOINT_PREFIX });
|
||||
return getPromptNamesForCategory(hosts.manager, category, { endpointPrefix: PROMPT_ADVANCED_ENDPOINT_PREFIX });
|
||||
}
|
||||
return Object.keys(getCategoryPromptEntries(data?.[category], library.store));
|
||||
}
|
||||
@@ -401,8 +392,7 @@ async function browseLibrary(library) {
|
||||
await showThumbnailBrowser(hosts.manager, "", "", {
|
||||
title,
|
||||
loadPromptsFn: loadManagerPrompts,
|
||||
contentFilter: library.filter,
|
||||
hideContentFilterControl: true,
|
||||
contentFilter: "all",
|
||||
filterEmptyCategories: true,
|
||||
allowMultiSelect: false,
|
||||
editMode: true,
|
||||
@@ -425,14 +415,6 @@ function ensureStyle() {
|
||||
.pm-hub-section-head { display: flex; align-items: baseline; gap: 8px; }
|
||||
.pm-hub-name { font-size: 15px; font-weight: 700; color: ${UI.textHeading}; }
|
||||
.pm-hub-count { margin-left: auto; color: ${UI.textHint}; font-size: 13px; white-space: nowrap; }
|
||||
.pm-hub-kinds { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 6px; }
|
||||
.pm-hub-kind { display: flex; align-items: center; gap: 8px; padding: 6px 8px; border-radius: 6px; cursor: pointer;
|
||||
border: 1px solid ${UI.inputBorder}; background: ${UI.inputBg}; color: ${UI.textPrimary}; font: inherit; font-size: 13px; text-align: left; }
|
||||
.pm-hub-kind:hover { border-color: rgba(var(--pm-hub-rgb), 0.8); }
|
||||
.pm-hub-kind.active { border-color: rgba(var(--pm-hub-rgb), 0.95); background: rgba(var(--pm-hub-rgb), 0.18); }
|
||||
.pm-hub-kind-count { margin-left: auto; color: ${UI.textHint}; }
|
||||
.pm-hub-badge { flex: 0 0 20px; height: 20px; border-radius: 5px; display: flex; align-items: center; justify-content: center;
|
||||
font-weight: 700; font-size: 12px; color: #fff; background: rgba(var(--pm-hub-rgb), 0.9); }
|
||||
.pm-hub-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; }
|
||||
.pm-hub-btn { padding: 6px 10px; border-radius: 6px; border: 1px solid ${UI.inputBorder}; background: ${UI.buttonBg};
|
||||
color: ${UI.textPrimary}; font: inherit; font-size: 13px; cursor: pointer; white-space: nowrap; }
|
||||
@@ -477,7 +459,6 @@ function renderHub(container) {
|
||||
status.className = "pm-hub-muted";
|
||||
root.append(header);
|
||||
|
||||
let selectedKind = PROMPT_KINDS.find((kind) => kind.id === localStorage.getItem(KIND_STORAGE_KEY)) || PROMPT_KINDS[0];
|
||||
let busy = false;
|
||||
const updaters = [];
|
||||
const update = () => updaters.forEach((fn) => fn());
|
||||
@@ -522,64 +503,30 @@ function renderHub(container) {
|
||||
head.append(name, count);
|
||||
const hint = document.createElement("div");
|
||||
hint.className = "pm-hub-muted";
|
||||
card.append(head);
|
||||
|
||||
const current = () => libraryFor(section, section.kinds ? selectedKind : null);
|
||||
|
||||
if (section.kinds) {
|
||||
const kinds = document.createElement("div");
|
||||
kinds.className = "pm-hub-kinds";
|
||||
for (const kind of section.kinds) {
|
||||
const chip = document.createElement("button");
|
||||
chip.type = "button";
|
||||
chip.className = "pm-hub-kind";
|
||||
chip.style.setProperty("--pm-hub-rgb", kind.color);
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "pm-hub-badge";
|
||||
badge.textContent = kind.badge;
|
||||
const label = document.createElement("span");
|
||||
label.textContent = kind.label;
|
||||
const kindCount = document.createElement("span");
|
||||
kindCount.className = "pm-hub-kind-count";
|
||||
chip.append(badge, label, kindCount);
|
||||
chip.onclick = () => {
|
||||
selectedKind = kind;
|
||||
localStorage.setItem(KIND_STORAGE_KEY, kind.id);
|
||||
update();
|
||||
};
|
||||
updaters.push(() => {
|
||||
chip.classList.toggle("active", kind === selectedKind);
|
||||
kindCount.textContent = String(summarize(libraryFor(section, kind)).entries);
|
||||
});
|
||||
kinds.appendChild(chip);
|
||||
}
|
||||
card.appendChild(kinds);
|
||||
}
|
||||
card.appendChild(hint);
|
||||
hint.textContent = section.hint;
|
||||
card.append(head, hint);
|
||||
const library = libraryFor(section);
|
||||
|
||||
const actions = document.createElement("div");
|
||||
actions.className = "pm-hub-actions";
|
||||
const browse = makeButton("Browse & Edit", { primary: true });
|
||||
browse.onclick = () => run(() => browseLibrary(current()));
|
||||
browse.onclick = () => run(() => browseLibrary(library));
|
||||
const importButton = makeButton("Import");
|
||||
importButton.onclick = () => run(() => importLibrary(current()));
|
||||
importButton.onclick = () => run(() => importLibrary(library));
|
||||
const exportButton = makeButton("Export");
|
||||
exportButton.onclick = () => run(() => exportLibrary(current()));
|
||||
exportButton.onclick = () => run(() => exportLibrary(library));
|
||||
actions.append(browse, importButton, exportButton);
|
||||
card.appendChild(actions);
|
||||
|
||||
browse.title = `Open ${library.title} in the Prompt Browser with editing on`;
|
||||
importButton.title = section.store === "manager"
|
||||
? "Merge a JSON file into Saved Prompts (entries keep their own type)"
|
||||
: `Merge or replace ${library.title} from a file`;
|
||||
exportButton.title = section.store === "composer" ? "Export selected prompt groups as a ZIP" : "Export selected categories as JSON";
|
||||
updaters.push(() => {
|
||||
const library = current();
|
||||
const { entries, categories, groups } = summarize(library);
|
||||
const parts = [plural(entries, library.unit), `${categories} categor${categories === 1 ? "y" : "ies"}`];
|
||||
if (groups) parts.push(`${groups} group${groups === 1 ? "" : "s"}`);
|
||||
count.textContent = parts.join(" · ");
|
||||
hint.textContent = section.kinds ? selectedKind.hint : section.hint;
|
||||
browse.title = `Open ${library.title} in the Prompt Browser with editing on`;
|
||||
importButton.title = section.store === "manager"
|
||||
? "Merge a JSON file into Saved Prompts (entries keep their own type)"
|
||||
: `Merge or replace ${library.title} from a file`;
|
||||
exportButton.title = section.store === "composer" ? "Export selected prompt groups as a ZIP" : "Export selected categories as JSON";
|
||||
});
|
||||
|
||||
root.appendChild(card);
|
||||
|
||||
@@ -738,7 +738,7 @@ function addButtonBar(node) {
|
||||
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");
|
||||
const warnEnabled = app.ui.settings.getSettingValue("PromptManager.WarnUnsavedChanges");
|
||||
|
||||
if (hasUnsaved && warnEnabled) {
|
||||
const confirmed = await showConfirm(
|
||||
@@ -891,10 +891,10 @@ function setupCategoryChangeHandler(node) {
|
||||
}
|
||||
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];
|
||||
// Only update text widget if not using external
|
||||
const useExternal = useExternalWidget ? useExternalWidget.value : false;
|
||||
if (!useExternal) {
|
||||
const promptData = node.prompts[category][promptNames[0]];
|
||||
textWidget.value = promptData?.prompt || "";
|
||||
|
||||
@@ -9566,6 +9566,8 @@ configurePromptBrowserDeps({
|
||||
export {
|
||||
PMA_THEME,
|
||||
DEFAULT_THUMBNAIL,
|
||||
exportPromptsJSON,
|
||||
getLoraManagerPreviewTooltip,
|
||||
loadPrompts,
|
||||
forwardWheelToCanvas,
|
||||
showInfo,
|
||||
|
||||
@@ -0,0 +1,753 @@
|
||||
/**
|
||||
* Prompt Manager (PromptManagerV2): a saved prompt with its LoRA stacks and
|
||||
* trigger words, on one fbui card with the legacy node's look: the prompt
|
||||
* bar, Save / New / More, a stack card per slot in use and the trigger words.
|
||||
*
|
||||
* The stock widgets stay hidden and hold the saved values: category, name,
|
||||
* use_prompt_input, lora_mode, text, and state, the node's edits
|
||||
* {loras: {slot: {name: {active, strength, removed}}}, order: {slot: [name]},
|
||||
* trigger_words: {text: {active, removed}}} (names in lower case). Before a
|
||||
* run the cards show the saved prompt's LoRAs; after one, the rows the node
|
||||
* ran with (its UI output, see nodes/prompt_manager_v2.py), connected LoRAs
|
||||
* included; those rows are kept in the node's properties, so a loaded
|
||||
* workflow shows them too.
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
import { api } from "../../scripts/api.js";
|
||||
import { mountCard } from "./fbui/card.js";
|
||||
import { notifyChange, toast } from "./fbui/comfy.js";
|
||||
import { button, helpBadge } from "./fbui/controls.js";
|
||||
import { chainCallback, el } from "./fbui/dom.js";
|
||||
import { confirm, openMenu } from "./fbui/modal.js";
|
||||
import { FONT } from "./fbui/theme.js";
|
||||
import { findWidget, hideInputsInDef, hideWidget } from "./fbui/widgets.js";
|
||||
import { DEFAULT_THUMBNAIL, exportPromptsJSON, getLoraManagerPreviewTooltip, PMA_THEME } from "./prompt_manager_advanced.js";
|
||||
import { getHideNSFW, hasComposeLikePayload, hasLayoutPayload, hasRecipeLikePayload, openPromptBrowserForSave, showThumbnailBrowser } from "./prompt_browser.js";
|
||||
import { buildSavePromptRequestBodyForEndpoint, isHiddenPromptEntryKey, PROMPT_ADVANCED_ENDPOINT_PREFIX as ENDPOINT } from "./prompt_store_adapters.js";
|
||||
|
||||
const NODE_NAME = "PromptManagerV2";
|
||||
const SLOTS = ["a", "b", "c", "d"];
|
||||
const MODE_LABELS = { "Prompt LoRAs Only": "Prompt only", "Combine LoRAs": "Combine", "Input LoRAs Only": "Input only" };
|
||||
const MODE_TITLES = {
|
||||
"Prompt LoRAs Only": "The saved prompt's LoRAs only.",
|
||||
"Combine LoRAs": "The saved prompt's LoRAs, then the connected ones.",
|
||||
"Input LoRAs Only": "The connected LoRAs only.",
|
||||
};
|
||||
const PROMPT_ONLY = "Prompt LoRAs Only";
|
||||
const INPUT_ONLY = "Input LoRAs Only";
|
||||
const MIN_WIDTH = 460;
|
||||
const TEXT_MIN_HEIGHT = 90;
|
||||
const BAR_HEIGHT = 26;
|
||||
const BUTTONS_HEIGHT = 28;
|
||||
// A stack card's padding and title bar, then one 24px line of tags per 28px.
|
||||
const STACK_HEAD = 50;
|
||||
const CSS_ID = "pm-v2-css-v2";
|
||||
// The last run's panel rows, saved with the workflow.
|
||||
const RUN_PROPERTY = "pm_last_run";
|
||||
|
||||
const GUIDE = [
|
||||
"Pick a prompt with ◀ ▶ or click its name to browse the library.",
|
||||
"LoRA stacks in:",
|
||||
["lora_stacks", "one LoRA stack: connect it here, it is stack A."],
|
||||
["Multi LoRA Stack", "stacks A-D from one node: connect its output here."],
|
||||
["Multi LoRA Relay", "several separate stacks: wire them into its lora_stack_a…d, and its lora_stacks out here."],
|
||||
"LoRA stacks out: a plain LoRA stack when one stack has LoRAs, a multi LoRA stack when several do. A node that takes one plain stack (a LoRA loader) fails on a prompt with several; put Multi LoRA Relay in between and use its lora_stack_a…d.",
|
||||
"Click a LoRA or trigger word to switch it off or on, its number to set the strength; right-click to move or delete it. Save Prompt keeps these edits with the prompt.",
|
||||
];
|
||||
|
||||
function ensureCss() {
|
||||
if (document.getElementById(CSS_ID)) return;
|
||||
const style = document.createElement("style");
|
||||
style.id = CSS_ID;
|
||||
style.textContent = `
|
||||
.pm-v2-bar{display:flex;align-items:center;width:100%;height:100%;background:#1a1a1a;border-radius:6px;pointer-events:auto}
|
||||
.pm-v2-arrow{height:100%;padding:0 10px;border:none;background:#2a2a2a;color:#888;font-size:12px;cursor:pointer;transition:all .15s ease}
|
||||
.pm-v2-arrow:first-child{border-radius:6px 0 0 6px}
|
||||
.pm-v2-arrow:last-child{border-radius:0 6px 6px 0}
|
||||
.pm-v2-arrow:hover{background:#3a3a3a;color:#fff}
|
||||
.pm-v2-name{flex:1;min-width:0;height:100%;display:flex;align-items:center;justify-content:center;padding:0 10px;box-sizing:border-box;border:1px solid rgba(56,130,246,.85);border-radius:4px;background:rgba(56,130,246,.22);color:#dbeafe;font-size:15px;cursor:pointer;transition:background .15s ease}
|
||||
.pm-v2-name:hover{background:rgba(56,130,246,.32)}
|
||||
.pm-v2-name .label{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.pm-v2-badge{flex-shrink:0;margin-left:6px;color:#fff;font-weight:bold}
|
||||
.pm-v2-badge.nsfw{padding:0 4px;border-radius:2px;background:rgba(204,50,50,.85);font-size:8px;line-height:12px}
|
||||
.pm-v2-badge.kind{width:14px;height:14px;display:inline-flex;align-items:center;justify-content:center;border-radius:50%;font-size:9px;line-height:1}
|
||||
.pm-v2-thumb{position:fixed;display:none;z-index:10001;pointer-events:none}
|
||||
.pm-v2-thumb img{display:block;max-width:300px;max-height:300px;object-fit:contain;border-radius:8px;box-shadow:0 4px 12px rgba(0,0,0,.5)}
|
||||
.pm-v2-buttons{display:flex;align-items:center;gap:2px;width:100%;height:100%;pointer-events:auto}
|
||||
.pm-v2-btn{min-width:80px;height:28px;font:500 13px/1 ${FONT}}
|
||||
.pm-v2-text.fbui-text{width:100%;height:100%;min-height:${TEXT_MIN_HEIGHT}px;padding:6px 8px;box-sizing:border-box;resize:none;pointer-events:auto}
|
||||
.pm-v2-text[readonly]{opacity:.5}
|
||||
.pm-v2-stack{display:flex;flex-direction:column;gap:4px;padding:8px;box-sizing:border-box;width:100%;border-radius:6px;background:${PMA_THEME.cardBg};pointer-events:auto}
|
||||
.pm-v2-stack .head{display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;padding-bottom:4px;border-bottom:1px solid ${PMA_THEME.sectionBorder}}
|
||||
.pm-v2-stack .title{color:${PMA_THEME.textMuted};font-size:14px;font-weight:bold}
|
||||
.pm-v2-stack .tools{display:flex;gap:4px}
|
||||
.pm-v2-mini{padding:2px 8px;border:1px solid ${PMA_THEME.inputBorder};border-radius:6px;background:${PMA_THEME.buttonBg};color:${PMA_THEME.textPrimary};font-size:12px;cursor:pointer}
|
||||
.pm-v2-tags{display:flex;flex-wrap:wrap;gap:4px}
|
||||
.pm-v2-tag{display:inline-flex;align-items:center;gap:6px;height:24px;padding:4px 10px;box-sizing:border-box;border:1px solid rgba(226,232,240,.2);border-radius:6px;background:rgba(45,55,72,.7);color:rgba(226,232,240,.6);font-size:14px;cursor:pointer;user-select:none;transition:background-color .15s ease,color .15s ease,border-color .15s ease}
|
||||
.pm-v2-tag:hover{transform:translateY(-1px);box-shadow:0 2px 4px rgba(0,0,0,.2)}
|
||||
.pm-v2-tag .name{flex-grow:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.pm-v2-tag.lora{flex-shrink:0;width:min(200px,calc(50% - 2px))}
|
||||
.pm-v2-tag.lora.on{background:rgba(66,153,225,.9);border-color:rgba(122,188,243,.9);color:#fff}
|
||||
.pm-v2-tag.lora.input.on{background:rgba(50,112,163,.9);border-color:rgba(66,153,225,.9)}
|
||||
.pm-v2-tag.lora.missing{background:rgba(220,53,69,.4);border-color:rgba(220,53,69,.9);color:rgba(255,200,200,.8)}
|
||||
.pm-v2-tag.lora.missing.on{background:rgba(220,53,69,.9);color:#fff}
|
||||
.pm-v2-tag.lora.missing .name{text-decoration:line-through;opacity:.8}
|
||||
.pm-v2-tag .warn{margin-right:-2px;font-size:13px}
|
||||
.pm-v2-strength{width:38px;padding:1px 4px;border:1px solid transparent;border-radius:999px;outline:none;background:rgba(255,255,255,.15);color:rgba(255,255,255,.9);font-size:12px;font-weight:600;text-align:center;cursor:text}
|
||||
.pm-v2-strength:focus{border-color:rgba(66,153,225,.6);background:rgba(255,255,255,.25)}
|
||||
.pm-v2-tag.word{justify-content:center;max-width:100%;white-space:nowrap;overflow:hidden}
|
||||
.pm-v2-tag.word.on{background:rgba(72,187,120,.9);border-color:rgba(72,187,120,.9);color:#fff}
|
||||
`;
|
||||
document.head.append(style);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- library
|
||||
|
||||
async function loadPrompts(node) {
|
||||
const response = await api.fetchApi(`${ENDPOINT}/get-prompts`, { cache: "no-store" });
|
||||
// The prompt browser reads the library from node.prompts too.
|
||||
node.prompts = response.ok ? await response.json() : {};
|
||||
return node.prompts;
|
||||
}
|
||||
|
||||
const selection = (node) => ({ category: findWidget(node, "category")?.value || "", name: findWidget(node, "name")?.value || "" });
|
||||
// A run's rows stand for the prompt and LoRA mode they were made with.
|
||||
const runKey = (category, name, mode) => `${category}\u0000${name}\u0000${mode}`;
|
||||
function currentKey(node) {
|
||||
const { category, name } = selection(node);
|
||||
return runKey(category, name, findWidget(node, "lora_mode")?.value);
|
||||
}
|
||||
|
||||
function entryOf(node) {
|
||||
const { category, name } = selection(node);
|
||||
const entry = name ? node.prompts?.[category]?.[name] : null;
|
||||
return entry && typeof entry === "object" ? entry : null;
|
||||
}
|
||||
|
||||
function isNsfw(node, category, name) {
|
||||
const entries = node.prompts?.[category];
|
||||
return entries?.__meta__?.nsfw === true || entries?.[name]?.nsfw === true;
|
||||
}
|
||||
|
||||
// Every prompt in library order, NSFW ones left out while they are hidden.
|
||||
function allPrompts(node) {
|
||||
const hide = getHideNSFW(app) === true;
|
||||
const out = [];
|
||||
for (const [category, entries] of Object.entries(node.prompts ?? {})) {
|
||||
if (!entries || typeof entries !== "object" || isHiddenPromptEntryKey(category)) continue;
|
||||
for (const name of Object.keys(entries)) {
|
||||
if (isHiddenPromptEntryKey(name)) continue;
|
||||
if (hide && isNsfw(node, category, name)) continue;
|
||||
out.push({ category, name });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- state
|
||||
|
||||
function readState(node) {
|
||||
try {
|
||||
const state = JSON.parse(findWidget(node, "state")?.value || "{}");
|
||||
return state && typeof state === "object" ? state : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function writeState(node, state) {
|
||||
findWidget(node, "state").value = JSON.stringify(state);
|
||||
node._pm.card.refresh();
|
||||
notifyChange();
|
||||
}
|
||||
|
||||
const hasEdits = (state) => ["loras", "order"].some((key) => Object.values(state[key] ?? {}).some((slot) => Object.keys(slot ?? {}).length)) || Object.keys(state.trigger_words ?? {}).length > 0;
|
||||
|
||||
// Rewrite one entry of an edits map; an empty entry is dropped.
|
||||
function setEdit(map, key, change) {
|
||||
const next = change({ ...(map[key] ?? {}) });
|
||||
if (Object.keys(next).length) map[key] = next;
|
||||
else delete map[key];
|
||||
}
|
||||
|
||||
function editLoras(node, slot, changes) {
|
||||
const state = readState(node);
|
||||
state.loras ??= {};
|
||||
state.loras[slot] ??= {};
|
||||
for (const [name, change] of changes) setEdit(state.loras[slot], name.toLowerCase(), change);
|
||||
writeState(node, state);
|
||||
}
|
||||
|
||||
function editWords(node, changes) {
|
||||
const state = readState(node);
|
||||
state.trigger_words ??= {};
|
||||
for (const [text, change] of changes) setEdit(state.trigger_words, text.toLowerCase(), change);
|
||||
writeState(node, state);
|
||||
}
|
||||
|
||||
// An on/off edit, dropped when it matches the row's own state.
|
||||
const activeEdit = (row, active) => (edit) => {
|
||||
if (active === (row.base_active ?? true)) delete edit.active;
|
||||
else edit.active = active;
|
||||
return edit;
|
||||
};
|
||||
|
||||
// ---------------------------------------------------------------- rows
|
||||
|
||||
// The rows the node runs with: the last run's when it ran this prompt in
|
||||
// this mode, else as nodes/prompt_manager_v2.py builds them, from the saved
|
||||
// prompt's LoRAs and the last run's connected ones (those do not depend on
|
||||
// the prompt), a connected LoRA of a saved one's name left out.
|
||||
function baseLoras(node, slot) {
|
||||
const pm = node._pm;
|
||||
if (pm.run?.key === currentKey(node)) return pm.run.loras?.[slot] ?? [];
|
||||
const mode = findWidget(node, "lora_mode")?.value;
|
||||
const saved = mode === INPUT_ONLY ? [] : savedLoras(node, slot);
|
||||
const connected = mode === PROMPT_ONLY ? [] : (pm.run?.loras?.[slot] ?? []).filter((row) => row.from_input);
|
||||
const names = new Set(saved.map((row) => row.name.toLowerCase()));
|
||||
return [...saved, ...connected.filter((row) => !names.has(row.name.toLowerCase()))];
|
||||
}
|
||||
|
||||
function savedLoras(node, slot) {
|
||||
return (entryOf(node)?.[`loras_${slot}`] ?? [])
|
||||
.filter((lora) => lora && typeof lora === "object" && String(lora.name ?? "").trim())
|
||||
.map((lora) => {
|
||||
const strength = Number(lora.strength ?? lora.model_strength ?? 1);
|
||||
return {
|
||||
name: String(lora.name).trim(),
|
||||
path: lora.path ?? lora.name,
|
||||
strength,
|
||||
clip_strength: Number(lora.clip_strength ?? strength),
|
||||
base_strength: strength,
|
||||
base_active: lora.active !== false,
|
||||
available: node._pm.available.get(String(lora.name).trim().toLowerCase()) ?? true,
|
||||
from_input: false,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// Rows as shown: the base with the node's edits, removed ones left out, in the node's order.
|
||||
function loraRows(node, slot) {
|
||||
const state = readState(node);
|
||||
const edits = state.loras?.[slot] ?? {};
|
||||
const order = state.order?.[slot] ?? [];
|
||||
const at = (row) => (order.includes(row.name.toLowerCase()) ? order.indexOf(row.name.toLowerCase()) : order.length);
|
||||
return baseLoras(node, slot)
|
||||
.filter((row) => edits[row.name.toLowerCase()]?.removed !== true)
|
||||
.map((row) => {
|
||||
const edit = edits[row.name.toLowerCase()] ?? {};
|
||||
const strength = typeof edit.strength === "number" ? edit.strength : row.base_strength ?? row.strength;
|
||||
return { ...row, strength, active: edit.active ?? row.base_active ?? row.active };
|
||||
})
|
||||
.sort((a, b) => at(a) - at(b));
|
||||
}
|
||||
|
||||
// Trigger words the same way: saved ones, then the last run's connected ones.
|
||||
function baseWords(node) {
|
||||
const pm = node._pm;
|
||||
if (pm.run?.key === currentKey(node)) return pm.run.trigger_words ?? [];
|
||||
const saved = (entryOf(node)?.trigger_words ?? []).map((word) => (typeof word === "string" ? { text: word, base_active: true } : { text: word?.text ?? "", base_active: word?.active !== false }));
|
||||
const texts = new Set(saved.map((word) => String(word.text).toLowerCase()));
|
||||
return [...saved, ...(pm.run?.trigger_words ?? []).filter((word) => word.from_input && !texts.has(word.text.toLowerCase()))];
|
||||
}
|
||||
|
||||
function wordRows(node) {
|
||||
const base = baseWords(node);
|
||||
const edits = readState(node).trigger_words ?? {};
|
||||
return base
|
||||
.filter((word) => String(word.text ?? "").trim() && edits[word.text.toLowerCase()]?.removed !== true)
|
||||
.map((word) => ({ ...word, active: edits[word.text.toLowerCase()]?.active ?? word.base_active ?? word.active }));
|
||||
}
|
||||
|
||||
// Which saved LoRAs are found locally, asked once per prompt shown.
|
||||
async function checkAvailability(node) {
|
||||
const entry = entryOf(node);
|
||||
const names = SLOTS.flatMap((slot) => (entry?.[`loras_${slot}`] ?? []).map((lora) => String(lora?.name ?? "").trim())).filter(Boolean);
|
||||
if (!names.length) return;
|
||||
const response = await api.fetchApi(`${ENDPOINT}/check-loras`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ lora_names: names }),
|
||||
});
|
||||
const result = response.ok ? await response.json() : null;
|
||||
for (const [name, found] of Object.entries(result?.results ?? {})) node._pm.available.set(name.toLowerCase(), found === true);
|
||||
node._pm.card.refresh();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- selection
|
||||
|
||||
const isLinked = (node, name) => node.inputs?.find((input) => input.name === name)?.link != null;
|
||||
|
||||
function isDirty(node) {
|
||||
const entry = entryOf(node);
|
||||
const text = findWidget(node, "text")?.value ?? "";
|
||||
return hasEdits(readState(node)) || (entry ? text !== (entry.prompt ?? "") : text.trim() !== "");
|
||||
}
|
||||
|
||||
async function mayLeave(node) {
|
||||
if (!isDirty(node) || app.ui.settings.getSettingValue("PromptManager.WarnUnsavedChanges") === false) return true;
|
||||
return confirm({ title: "Unsaved changes", message: "The prompt's text or LoRA edits are not saved. Discard them and switch?", confirmText: "Discard & Switch" });
|
||||
}
|
||||
|
||||
// Show a prompt: its saved text and no edits. The last run's rows no longer
|
||||
// stand for it (even a prompt just saved may differ from what ran), but its
|
||||
// connected LoRAs and trigger words still show.
|
||||
function select(node, category, name) {
|
||||
findWidget(node, "category").value = category;
|
||||
findWidget(node, "name").value = name;
|
||||
findWidget(node, "text").value = name ? node.prompts?.[category]?.[name]?.prompt ?? "" : "";
|
||||
if (node._pm.run) node._pm.run.key = null;
|
||||
writeState(node, {});
|
||||
checkAvailability(node);
|
||||
}
|
||||
|
||||
async function step(node, delta) {
|
||||
const list = allPrompts(node);
|
||||
if (!list.length || !(await mayLeave(node))) return;
|
||||
const { category, name } = selection(node);
|
||||
const at = list.findIndex((item) => item.category === category && item.name === name);
|
||||
const next = list[(at + delta + list.length) % list.length] ?? list[0];
|
||||
select(node, next.category, next.name);
|
||||
}
|
||||
|
||||
async function browse(node) {
|
||||
const { category, name } = selection(node);
|
||||
const picked = await showThumbnailBrowser(node, category, name, { endpointPrefix: ENDPOINT, loadPromptsFn: loadPrompts, filterEmptyCategories: true, showAllCategoriesToggle: true });
|
||||
if (!picked?.prompt || (picked.category === category && picked.prompt === name) || !(await mayLeave(node))) return;
|
||||
select(node, picked.category, picked.prompt);
|
||||
}
|
||||
|
||||
async function newPrompt(node) {
|
||||
if (!(await mayLeave(node))) return;
|
||||
select(node, selection(node).category, "");
|
||||
}
|
||||
|
||||
async function deletePrompt(node) {
|
||||
const { category, name } = selection(node);
|
||||
if (!name || !(await confirm({ title: "Delete prompt", message: `Delete "${name}" from ${category}? This cannot be undone.`, confirmText: "Delete", danger: true }))) return;
|
||||
const response = await api.fetchApi(`${ENDPOINT}/delete-prompt`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ category, name }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!result?.success) return toast(result?.error || "Could not delete the prompt.", { severity: "error" });
|
||||
node.prompts = result.prompts;
|
||||
select(node, category, "");
|
||||
}
|
||||
|
||||
function importPrompts(node, mode) {
|
||||
const input = el("input");
|
||||
input.type = "file";
|
||||
input.accept = ".json";
|
||||
input.addEventListener("change", async () => {
|
||||
const file = input.files?.[0];
|
||||
if (!file) return;
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(await file.text());
|
||||
} catch {
|
||||
return toast(`${file.name} is not valid JSON.`, { severity: "error" });
|
||||
}
|
||||
if (mode === "replace" && !(await confirm({ title: "Replace prompts", message: `Replace the whole prompt library with ${file.name}?`, confirmText: "Replace", danger: true }))) return;
|
||||
const response = await api.fetchApi(`${ENDPOINT}/import-prompts`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ data, mode }),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!result?.success) return toast(result?.error || "Could not import the prompts.", { severity: "error" });
|
||||
node.prompts = result.prompts;
|
||||
node._pm.card.refresh();
|
||||
toast(mode === "replace" ? "Prompts replaced." : "Prompts imported.");
|
||||
});
|
||||
input.click();
|
||||
}
|
||||
|
||||
// Save through the library's save dialog, edits included; the saved prompt
|
||||
// then carries them, so the node's edits are cleared.
|
||||
async function savePrompt(node) {
|
||||
const { category, name } = selection(node);
|
||||
const entry = entryOf(node);
|
||||
const initialName = name || "New Prompt";
|
||||
const loras = Object.fromEntries(SLOTS.map((slot) => [`loras_${slot}`, loraRows(node, slot).map((row) => ({
|
||||
name: row.name, path: row.path, strength: row.strength, clip_strength: row.clip_strength,
|
||||
active: row.active, available: row.available, fromInput: row.from_input === true,
|
||||
}))]));
|
||||
const words = wordRows(node).map((word) => ({ text: word.text, active: word.active }));
|
||||
await openPromptBrowserForSave({
|
||||
node,
|
||||
currentCategory: category,
|
||||
currentPrompt: name,
|
||||
title: "Save Prompt",
|
||||
saveButtonText: "Save",
|
||||
namePlaceholder: "Prompt name",
|
||||
initialName,
|
||||
saveWithEditPanel: true,
|
||||
saveMode: true,
|
||||
showNSFWOnOpen: Boolean(entry) && isNsfw(node, category, name),
|
||||
saveDraft: { category, name: initialName, text: findWidget(node, "text").value || "", thumbnail: entry?.thumbnail || null, workflow_data: entry?.workflow_data || null, ...loras, trigger_words: words },
|
||||
onSave: async ({ category: target, name: saveName, overwrite, text, thumbnail, ...edited }) => {
|
||||
const promptName = String(saveName || "").trim();
|
||||
const targetCategory = String(target || "").trim();
|
||||
if (!promptName || !targetCategory) return { success: false, error: "Category and prompt name are required." };
|
||||
const payload = { category: targetCategory, name: promptName, text: typeof text === "string" ? text : findWidget(node, "text").value || "", thumbnail };
|
||||
for (const slot of SLOTS) payload[`loras_${slot}`] = Array.isArray(edited[`loras_${slot}`]) ? edited[`loras_${slot}`] : loras[`loras_${slot}`];
|
||||
payload.trigger_words = Array.isArray(edited.trigger_words) ? edited.trigger_words : words;
|
||||
const response = await api.fetchApi(`${ENDPOINT}/save-prompt`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(buildSavePromptRequestBodyForEndpoint(ENDPOINT, payload)),
|
||||
});
|
||||
const result = await response.json();
|
||||
if (!result?.success) return { success: false, error: result?.error || "Could not save the prompt." };
|
||||
node.prompts = result.prompts;
|
||||
select(node, targetCategory, promptName);
|
||||
return { success: true, category: targetCategory, name: promptName, overwritten: overwrite === true };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- prompt bar
|
||||
|
||||
// The saved prompt's thumbnail at its own size above the bar, while hovered.
|
||||
function thumbnailHover(node, target) {
|
||||
const preview = el("div", "pm-v2-thumb");
|
||||
const image = el("img");
|
||||
preview.append(image);
|
||||
document.body.append(preview);
|
||||
chainCallback(node, "onRemoved", () => preview.remove());
|
||||
let timer = null;
|
||||
target.addEventListener("mouseenter", () => {
|
||||
timer = setTimeout(() => {
|
||||
const thumbnail = entryOf(node)?.thumbnail;
|
||||
if (!thumbnail || thumbnail === DEFAULT_THUMBNAIL) return;
|
||||
const probe = new Image();
|
||||
probe.onload = () => {
|
||||
image.src = thumbnail;
|
||||
const width = Math.min(probe.naturalWidth, 300);
|
||||
const height = Math.min(probe.naturalHeight, 300);
|
||||
const box = target.getBoundingClientRect();
|
||||
preview.style.left = `${Math.max(5, Math.min(box.left + box.width / 2 - width / 2, window.innerWidth - width - 5))}px`;
|
||||
preview.style.top = `${Math.max(5, Math.min(box.top - height - 8, window.innerHeight - height - 5))}px`;
|
||||
preview.style.display = "block";
|
||||
};
|
||||
probe.src = thumbnail;
|
||||
}, 300);
|
||||
});
|
||||
target.addEventListener("mouseleave", () => {
|
||||
clearTimeout(timer);
|
||||
preview.style.display = "none";
|
||||
});
|
||||
}
|
||||
|
||||
function promptBar(node) {
|
||||
ensureCss();
|
||||
const bar = el("div", "pm-v2-bar");
|
||||
const back = el("button", "pm-v2-arrow", "◀");
|
||||
const label = el("span", "label");
|
||||
const nsfw = el("span", "pm-v2-badge nsfw", "NSFW");
|
||||
const kind = el("span", "pm-v2-badge kind");
|
||||
const name = el("div", "pm-v2-name");
|
||||
const next = el("button", "pm-v2-arrow", "▶");
|
||||
back.title = "Previous prompt";
|
||||
next.title = "Next prompt";
|
||||
name.append(label, nsfw, kind);
|
||||
bar.append(back, name, next);
|
||||
back.addEventListener("click", () => step(node, -1));
|
||||
next.addEventListener("click", () => step(node, 1));
|
||||
name.addEventListener("click", () => browse(node));
|
||||
bar.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||
thumbnailHover(node, name);
|
||||
return {
|
||||
element: bar,
|
||||
sync() {
|
||||
const { category, name: prompt } = selection(node);
|
||||
label.textContent = `${category} : ${prompt || "new prompt"}`;
|
||||
name.title = `${label.textContent}\nClick to browse the prompt library`;
|
||||
const entry = entryOf(node);
|
||||
nsfw.hidden = !prompt || !isNsfw(node, category, prompt);
|
||||
// L, C or R: the entry also holds a layout, a Composer setup or a recipe.
|
||||
const compose = hasComposeLikePayload(entry);
|
||||
const layout = compose && hasLayoutPayload(entry);
|
||||
const recipe = !compose && hasRecipeLikePayload(entry);
|
||||
kind.hidden = !compose && !recipe;
|
||||
kind.textContent = layout ? "L" : compose ? "C" : "R";
|
||||
kind.style.background = layout ? "rgba(124,92,220,.95)" : compose ? "rgba(55,165,95,.95)" : "rgba(235,140,35,.95)";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function buttonBar(node) {
|
||||
const row = el("div", "pm-v2-buttons");
|
||||
const add = (text, title, onClick) => {
|
||||
const btn = button(text, { soft: true, grow: true, title, onClick });
|
||||
btn.classList.add("pm-v2-btn");
|
||||
row.append(btn);
|
||||
};
|
||||
add("Save Prompt", "Save the prompt, its LoRAs and trigger words to the library", () => savePrompt(node));
|
||||
add("New Prompt", "Start a new prompt", () => newPrompt(node));
|
||||
add("More ▼", "", (event) => {
|
||||
const box = event.currentTarget.getBoundingClientRect();
|
||||
openMenu(box.left, box.bottom + 4, [
|
||||
{ label: "Delete Prompt", danger: true, disabled: !selection(node).name, action: () => deletePrompt(node) },
|
||||
{ label: "Undo LoRA and trigger word edits", disabled: !hasEdits(readState(node)), action: () => writeState(node, {}) },
|
||||
null,
|
||||
{ label: "Export JSON", action: () => exportPromptsJSON(node) },
|
||||
{ label: "Import JSON", action: () => importPrompts(node, "merge") },
|
||||
{ label: "Replace JSON", action: () => importPrompts(node, "replace") },
|
||||
]);
|
||||
});
|
||||
row.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||
return { element: row };
|
||||
}
|
||||
|
||||
function textPanel(node) {
|
||||
const area = el("textarea", "fbui-text pm-v2-text");
|
||||
area.spellcheck = false;
|
||||
area.addEventListener("input", () => { findWidget(node, "text").value = area.value; });
|
||||
area.addEventListener("change", notifyChange);
|
||||
// Typing and selecting here must not drag the node or reach the canvas.
|
||||
area.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
area.addEventListener("keydown", (event) => event.stopPropagation());
|
||||
return {
|
||||
element: area,
|
||||
sync() {
|
||||
// With the prompt input on, its text from the last run, read-only.
|
||||
const fromInput = findWidget(node, "use_prompt_input")?.value === true && isLinked(node, "prompt");
|
||||
area.readOnly = fromInput;
|
||||
const shown = fromInput ? node._pm.run?.prompt_input ?? "" : findWidget(node, "text").value ?? "";
|
||||
if (area.value !== shown && document.activeElement !== area) area.value = shown;
|
||||
area.placeholder = fromInput ? "From the prompt input (shown after a run)" : "Enter prompt text";
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- stack cards
|
||||
|
||||
// A titled card with buttons at the right and a wrap of tags; it measures its
|
||||
// own height and asks the node's card to follow. Tags are rebuilt only when
|
||||
// what they show changes, and never under an open strength field.
|
||||
function stackCard(node, key, title, tools, renderTags) {
|
||||
const box = el("div", "pm-v2-stack");
|
||||
const head = el("div", "head");
|
||||
const buttons = el("div", "tools");
|
||||
for (const [text, hint, onClick] of tools) {
|
||||
const btn = el("button", "pm-v2-mini", text);
|
||||
btn.title = hint;
|
||||
btn.addEventListener("click", onClick);
|
||||
buttons.append(btn);
|
||||
}
|
||||
head.append(el("span", "title", title), buttons);
|
||||
const tags = el("div", "pm-v2-tags");
|
||||
box.append(head, tags);
|
||||
box.addEventListener("contextmenu", (event) => event.preventDefault());
|
||||
const measure = () => {
|
||||
const height = Math.ceil(box.scrollHeight);
|
||||
if (height && height !== node._pm.heights[key]) {
|
||||
node._pm.heights[key] = height;
|
||||
node._pm.card.refresh();
|
||||
}
|
||||
};
|
||||
new ResizeObserver(measure).observe(tags);
|
||||
let shown = null;
|
||||
return {
|
||||
element: box,
|
||||
sync() {
|
||||
// A strength being typed keeps its field; anything else (a button just clicked) redraws.
|
||||
if (box.contains(document.activeElement) && document.activeElement.classList.contains("pm-v2-strength")) return;
|
||||
const { signature, elements } = renderTags();
|
||||
if (signature === shown) return;
|
||||
shown = signature;
|
||||
tags.replaceChildren(...elements);
|
||||
requestAnimationFrame(measure);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function strengthField(node, slot, row) {
|
||||
const input = el("input", "pm-v2-strength");
|
||||
input.type = "text";
|
||||
input.value = Number(row.strength).toFixed(2);
|
||||
input.addEventListener("focus", () => input.select());
|
||||
input.addEventListener("blur", () => {
|
||||
const value = parseFloat(input.value);
|
||||
if (Number.isNaN(value) || value === row.strength) {
|
||||
input.value = Number(row.strength).toFixed(2);
|
||||
return;
|
||||
}
|
||||
editLoras(node, slot, [[row.name, (edit) => {
|
||||
if (value === row.base_strength) delete edit.strength;
|
||||
else edit.strength = value;
|
||||
return edit;
|
||||
}]]);
|
||||
});
|
||||
input.addEventListener("keydown", (event) => {
|
||||
event.stopPropagation();
|
||||
if (event.key === "Enter") input.blur();
|
||||
if (event.key === "Escape") {
|
||||
input.value = Number(row.strength).toFixed(2);
|
||||
input.blur();
|
||||
}
|
||||
});
|
||||
input.addEventListener("pointerdown", (event) => event.stopPropagation());
|
||||
input.addEventListener("click", (event) => event.stopPropagation());
|
||||
return input;
|
||||
}
|
||||
|
||||
function moveLora(node, slot, index, delta) {
|
||||
const names = loraRows(node, slot).map((row) => row.name.toLowerCase());
|
||||
const to = index + delta;
|
||||
if (to < 0 || to >= names.length) return;
|
||||
names.splice(to, 0, names.splice(index, 1)[0]);
|
||||
const state = readState(node);
|
||||
state.order ??= {};
|
||||
state.order[slot] = names;
|
||||
writeState(node, state);
|
||||
}
|
||||
|
||||
function loraTag(node, slot, row, index, count) {
|
||||
const missing = row.available === false;
|
||||
const tag = el("div", "pm-v2-tag lora");
|
||||
tag.classList.toggle("on", row.active);
|
||||
tag.classList.toggle("input", row.from_input === true);
|
||||
tag.classList.toggle("missing", missing);
|
||||
if (missing) tag.append(el("span", "warn", "⚠️"));
|
||||
tag.append(el("span", "name", row.name), strengthField(node, slot, row));
|
||||
tag.addEventListener("click", () => editLoras(node, slot, [[row.name, activeEdit(row, !row.active)]]));
|
||||
tag.addEventListener("contextmenu", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openMenu(event.clientX, event.clientY, [
|
||||
{ label: "Move Up", disabled: index === 0, action: () => moveLora(node, slot, index, -1) },
|
||||
{ label: "Move Down", disabled: index === count - 1, action: () => moveLora(node, slot, index, 1) },
|
||||
...(missing ? [{ label: "🔍 Search on CivitAI", action: () => window.open(`https://civitai.com/search/models?sortBy=models_v9&query=${encodeURIComponent(row.name)}&modelType=LORA`, "_blank") }] : []),
|
||||
null,
|
||||
{ label: "Delete", danger: true, action: () => editLoras(node, slot, [[row.name, (edit) => ({ ...edit, removed: true })]]) },
|
||||
]);
|
||||
});
|
||||
tag.title = missing
|
||||
? `${row.name}\n⚠️ NOT FOUND - This LoRA is missing from your system\nRight-click for options`
|
||||
: `${row.name}${row.from_input ? " (from the input)" : ""}\nStrength: ${Number(row.strength).toFixed(2)}\nClick to toggle on/off\nRight-click for options`;
|
||||
if (missing) return tag;
|
||||
// LoRA Manager's preview beside the tag when it is installed, in place of the plain tooltip.
|
||||
let timer = null;
|
||||
tag.addEventListener("mouseenter", () => {
|
||||
const box = tag.getBoundingClientRect();
|
||||
timer = setTimeout(async () => {
|
||||
const tooltip = await getLoraManagerPreviewTooltip();
|
||||
if (!tooltip) return;
|
||||
tag.removeAttribute("title");
|
||||
tooltip.show(row.name, box.right, box.top);
|
||||
}, 300);
|
||||
});
|
||||
tag.addEventListener("mouseleave", () => {
|
||||
clearTimeout(timer);
|
||||
getLoraManagerPreviewTooltip().then((tooltip) => tooltip?.hide());
|
||||
});
|
||||
return tag;
|
||||
}
|
||||
|
||||
function loraCard(node, slot) {
|
||||
return stackCard(node, slot, `LoRAs Stack ${slot.toUpperCase()}`, [
|
||||
["Reset Strength", "Reset all strength values to their original values", () => {
|
||||
editLoras(node, slot, loraRows(node, slot).map((row) => [row.name, (edit) => {
|
||||
delete edit.strength;
|
||||
return edit;
|
||||
}]));
|
||||
}],
|
||||
["Toggle All", "Switch all of this stack's LoRAs on, or off when they all are", () => {
|
||||
const rows = loraRows(node, slot);
|
||||
const active = !rows.every((row) => row.active);
|
||||
editLoras(node, slot, rows.map((row) => [row.name, activeEdit(row, active)]));
|
||||
}],
|
||||
], () => {
|
||||
const rows = loraRows(node, slot);
|
||||
return {
|
||||
signature: JSON.stringify(rows),
|
||||
elements: rows.map((row, index) => loraTag(node, slot, row, index, rows.length)),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function wordTag(node, word) {
|
||||
const tag = el("div", "pm-v2-tag word");
|
||||
tag.classList.toggle("on", word.active);
|
||||
tag.append(el("span", "name", word.text));
|
||||
tag.title = `${word.text}${word.from_input ? " (from the input)" : ""}\nClick to toggle on/off\nRight-click for options`;
|
||||
tag.addEventListener("click", () => editWords(node, [[word.text, activeEdit(word, !word.active)]]));
|
||||
tag.addEventListener("contextmenu", (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
openMenu(event.clientX, event.clientY, [{ label: "Delete", danger: true, action: () => editWords(node, [[word.text, (edit) => ({ ...edit, removed: true })]]) }]);
|
||||
});
|
||||
return tag;
|
||||
}
|
||||
|
||||
function wordsCard(node) {
|
||||
return stackCard(node, "words", "Trigger Words", [
|
||||
["Toggle All", "Switch all trigger words on, or off when they all are", () => {
|
||||
const words = wordRows(node);
|
||||
const active = !words.every((word) => word.active);
|
||||
editWords(node, words.map((word) => [word.text, activeEdit(word, active)]));
|
||||
}],
|
||||
], () => {
|
||||
const words = wordRows(node);
|
||||
return { signature: JSON.stringify(words), elements: words.map((word) => wordTag(node, word)) };
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- node
|
||||
|
||||
function setupNode(node) {
|
||||
ensureCss();
|
||||
const pm = { run: null, available: new Map(), heights: { a: STACK_HEAD + 28, b: STACK_HEAD + 28, c: STACK_HEAD + 28, d: STACK_HEAD + 28, words: STACK_HEAD + 28 } };
|
||||
node._pm = pm;
|
||||
// The card stands in for these; use_prompt_input and lora_mode are card rows.
|
||||
for (const name of ["category", "name", "text", "state"]) hideWidget(findWidget(node, name));
|
||||
pm.card = mountCard(node, {
|
||||
minWidth: MIN_WIDTH,
|
||||
rows: [
|
||||
{ widget: "use_prompt_input", label: "Prompt input" },
|
||||
{ widget: "lora_mode", label: "LoRA input", kind: "segment", labels: MODE_LABELS, titles: MODE_TITLES },
|
||||
{ panel: textPanel, grow: true, height: TEXT_MIN_HEIGHT },
|
||||
{ panel: promptBar, height: BAR_HEIGHT },
|
||||
{ panel: buttonBar, height: BUTTONS_HEIGHT },
|
||||
...SLOTS.map((slot) => ({ panel: (n) => loraCard(n, slot), height: () => pm.heights[slot], when: (_values, n) => loraRows(n, slot).length > 0 })),
|
||||
{ panel: wordsCard, height: () => pm.heights.words, when: (_values, n) => wordRows(n).length > 0 },
|
||||
],
|
||||
});
|
||||
helpBadge(node, GUIDE);
|
||||
chainCallback(node, "onRemoved", () => getLoraManagerPreviewTooltip().then((tooltip) => tooltip?.hide()));
|
||||
chainCallback(node, "onExecuted", (output) => {
|
||||
const panels = output?.prompt_manager?.[0];
|
||||
if (!panels) return;
|
||||
pm.run = { ...panels, key: runKey(panels.category, panels.name, panels.lora_mode) };
|
||||
node.properties[RUN_PROPERTY] = pm.run;
|
||||
pm.card.refresh();
|
||||
});
|
||||
chainCallback(node, "onConfigure", () => {
|
||||
pm.configured = true;
|
||||
pm.run = node.properties?.[RUN_PROPERTY] ?? null;
|
||||
loadPrompts(node).then(() => {
|
||||
pm.card.refresh();
|
||||
checkAvailability(node);
|
||||
});
|
||||
});
|
||||
queueMicrotask(() => {
|
||||
if (pm.configured) return;
|
||||
loadPrompts(node).then(() => pm.card.refresh());
|
||||
});
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "PromptManager.PromptManagerV2",
|
||||
beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== NODE_NAME) return;
|
||||
hideInputsInDef(nodeData, ["category", "name", "use_prompt_input", "lora_mode", "text", "state"]);
|
||||
chainCallback(nodeType.prototype, "onNodeCreated", function () {
|
||||
setupNode(this);
|
||||
});
|
||||
},
|
||||
});
|
||||
+32
-25
@@ -1,43 +1,50 @@
|
||||
// Shared UI palette used by Prompt Manager modals.
|
||||
// Keep this aligned with Workflow Builder's neutral + blue accent styling.
|
||||
// Prompt Manager's modal palette, now the FB UI kit's colours (js/fbui/theme.js)
|
||||
// under the names the modals already use. Selected and hover states follow
|
||||
// the kit: soft blue fill, solid blue edge.
|
||||
import { T } from "./fbui/theme.js";
|
||||
|
||||
export const PM_UI_PALETTE = {
|
||||
// Backdrop behind modal dialogs
|
||||
overlay: "hsl(0 0% 0% / 0.8)",
|
||||
overlay: T.overlay,
|
||||
// Main modal surface
|
||||
panel: "hsl(216 11% 15%)",
|
||||
panel: T.panel,
|
||||
// Outer border of modal containers
|
||||
panelBorder: "hsl(216 20% 65% / 0.24)",
|
||||
panelBorder: T.plateEdge,
|
||||
// Dividers between modal sections (header/body/footer)
|
||||
sectionBorder: "hsl(216 20% 65% / 0.20)",
|
||||
sectionBorder: T.rule,
|
||||
|
||||
// Text input/select control surface
|
||||
inputBg: "hsl(220 15% 10%)",
|
||||
inputBg: T.card,
|
||||
// Input/select/button neutral stroke
|
||||
inputBorder: "hsl(218 10% 41%)",
|
||||
// Neutral button/chip background
|
||||
buttonBg: "hsl(219 16% 18%)",
|
||||
inputBorder: T.plateEdge,
|
||||
// Neutral button/chip background, and its hover
|
||||
buttonBg: T.fill,
|
||||
buttonHover: T.fillHover,
|
||||
|
||||
// Primary foreground text
|
||||
textPrimary: "hsl(0 0% 87%)",
|
||||
textPrimary: T.inkSoft,
|
||||
// Titles and important labels
|
||||
textHeading: "hsl(220 13% 85%)",
|
||||
textHeading: T.ink,
|
||||
// Secondary text
|
||||
textMuted: "hsl(0 0% 67%)",
|
||||
textMuted: T.label,
|
||||
// Hints and helper text
|
||||
textHint: "hsl(216 15% 65%)",
|
||||
textHint: T.faint,
|
||||
|
||||
// Card/tile background (thumbnails, prompt cards)
|
||||
cardBg: "hsl(219 16% 18%)",
|
||||
cardBg: T.plate,
|
||||
// Card default border
|
||||
cardBorder: "hsl(217 12% 22%)",
|
||||
cardBorder: T.plateEdge,
|
||||
|
||||
// Exact Builder accent family (from workflow_builder.js)
|
||||
// Primary blue accent (focus/selected)
|
||||
accent: "hsl(208 73% 57% / 0.9)",
|
||||
// Slightly dimmed accent (hover/secondary accent)
|
||||
accentDim: "hsl(208 73% 57% / 0.7)",
|
||||
// Soft accent fill for selected backgrounds
|
||||
accentSoft: "hsl(208 73% 57% / 0.55)",
|
||||
// Accent border used on selected elements
|
||||
accentBorder: "hsl(208 73% 57% / 0.95)",
|
||||
// The accent (focus/selected), dimmed, as a soft fill, as an edge
|
||||
accent: T.brand,
|
||||
accentDim: T.brandInk,
|
||||
accentSoft: T.brandSoftHover,
|
||||
accentBorder: T.brand,
|
||||
// Text on a solid accent fill
|
||||
onAccent: T.onBrand,
|
||||
|
||||
// Destructive actions
|
||||
danger: T.danger,
|
||||
dangerSoft: T.dangerSoft,
|
||||
dangerInk: T.dangerInk,
|
||||
};
|
||||
|
||||
@@ -10,6 +10,7 @@ import json
|
||||
|
||||
import server
|
||||
|
||||
from ..py.prompt_store import load_prompts
|
||||
from ..py.thumbnail_utils import image_to_base64_thumbnail
|
||||
from ..py.workflow_data_utils import ensure_v2_recipe_data, get_v2_model_block, to_json_safe_workflow_data, build_v2_recipe_data_from_prompt
|
||||
from .prompt_manager_adv import PromptManagerAdvanced
|
||||
@@ -19,10 +20,12 @@ class LibraryManager(PromptManagerAdvanced):
|
||||
"""Workflow-focused manager for manager_data payloads with explicit thumbnail input."""
|
||||
|
||||
SOURCE_NAME = "LibraryManager"
|
||||
# Current, though the legacy Prompt Manager it builds on is deprecated.
|
||||
DEPRECATED = False
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
prompts_data = cls.load_prompts()
|
||||
prompts_data = load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Default"]
|
||||
|
||||
all_prompts = set()
|
||||
@@ -104,7 +107,7 @@ class LibraryManager(PromptManagerAdvanced):
|
||||
saved_workflow_data=None,
|
||||
**kwargs,
|
||||
):
|
||||
prompts_data = self.load_prompts()
|
||||
prompts_data = load_prompts()
|
||||
source_name = self.SOURCE_NAME
|
||||
recipe_data = manager_data
|
||||
if recipe_data is None:
|
||||
|
||||
+47
-71
@@ -5,6 +5,7 @@ import importlib
|
||||
import os
|
||||
import sys
|
||||
|
||||
from ..py.lora_stacks import coerce_lora_stack, normalize_lora_slots
|
||||
from ..py.lora_utils import resolve_lora_path
|
||||
try:
|
||||
from ..py.lora_utils import get_lora_relative_path
|
||||
@@ -220,56 +221,12 @@ class MultiLoraStackerLM:
|
||||
return (multi_lora_stack, combined_lora_stack, trigger_words_text)
|
||||
|
||||
|
||||
def _coerce_lora_stack(raw_stack):
|
||||
"""Normalize an incoming LORA_STACK-like payload to list[(path, model, clip)]."""
|
||||
if raw_stack is None:
|
||||
return []
|
||||
|
||||
if isinstance(raw_stack, dict) and "__value__" in raw_stack:
|
||||
raw_stack = raw_stack.get("__value__")
|
||||
|
||||
if not isinstance(raw_stack, list):
|
||||
return []
|
||||
|
||||
out = []
|
||||
for item in raw_stack:
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
path = str(item[0] or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item[1]) if len(item) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item[2]) if len(item) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
continue
|
||||
|
||||
if isinstance(item, dict):
|
||||
path = str(item.get("path") or item.get("name") or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item.get("model_strength", item.get("strength", 1.0)))
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item.get("clip_strength", model_strength))
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class MultiLoraCombine:
|
||||
"""Combine optional multi stack + optional A/B/C/D stacks into one MULTI_LORA_STACK."""
|
||||
|
||||
NAME = "Multi LoRA Combine"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DEPRECATED = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -311,23 +268,15 @@ class MultiLoraCombine:
|
||||
lora_stack_d=None,
|
||||
**kwargs,
|
||||
):
|
||||
# Start from empty payload when no multi input is connected.
|
||||
out_a = []
|
||||
out_b = []
|
||||
out_c = []
|
||||
out_d = []
|
||||
|
||||
if isinstance(multi_lora_stack, dict):
|
||||
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
|
||||
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
|
||||
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
|
||||
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
|
||||
# A plain LoRA stack (the Prompt Manager's when one slot has LoRAs) is slot A.
|
||||
slots = normalize_lora_slots(multi_lora_stack, "a")
|
||||
out_a, out_b, out_c, out_d = (slots[slot] for slot in "abcd")
|
||||
|
||||
# Append separate stack inputs to each slot (if connected).
|
||||
out_a.extend(_coerce_lora_stack(lora_stack_a))
|
||||
out_b.extend(_coerce_lora_stack(lora_stack_b))
|
||||
out_c.extend(_coerce_lora_stack(lora_stack_c))
|
||||
out_d.extend(_coerce_lora_stack(lora_stack_d))
|
||||
out_a.extend(coerce_lora_stack(lora_stack_a))
|
||||
out_b.extend(coerce_lora_stack(lora_stack_b))
|
||||
out_c.extend(coerce_lora_stack(lora_stack_c))
|
||||
out_d.extend(coerce_lora_stack(lora_stack_d))
|
||||
|
||||
merged = {
|
||||
"a": out_a,
|
||||
@@ -343,6 +292,7 @@ class MultiLoraSplitter:
|
||||
|
||||
NAME = "Multi LoRA Splitter"
|
||||
CATEGORY = "Prompt Manager"
|
||||
DEPRECATED = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
@@ -360,14 +310,40 @@ class MultiLoraSplitter:
|
||||
DESCRIPTION = "Split a MULTI_LORA_STACK payload into LORA_STACK outputs A/B/C/D."
|
||||
|
||||
def split_multi(self, multi_lora_stack, **kwargs):
|
||||
if not isinstance(multi_lora_stack, dict):
|
||||
return ([], [], [], [])
|
||||
# A plain LoRA stack (the Prompt Manager's when one slot has LoRAs) is slot A.
|
||||
slots = normalize_lora_slots(multi_lora_stack, "a")
|
||||
return tuple(slots[slot] for slot in "abcd")
|
||||
|
||||
out_a = _coerce_lora_stack(multi_lora_stack.get("a"))
|
||||
out_b = _coerce_lora_stack(multi_lora_stack.get("b"))
|
||||
out_c = _coerce_lora_stack(multi_lora_stack.get("c"))
|
||||
out_d = _coerce_lora_stack(multi_lora_stack.get("d"))
|
||||
return (out_a, out_b, out_c, out_d)
|
||||
|
||||
class MultiLoraRelay:
|
||||
"""LoRA stacks in and out as one set of slots A-D and as four plain stacks: a stack wired to a slot is appended
|
||||
to it, so the node combines and splits, and passes through on both ends like Recipe Relay."""
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
slots = {f"lora_stack_{slot}": ("LORA_STACK", {"tooltip": f"Appended to slot {slot.upper()}."}) for slot in "abcd"}
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"lora_stacks": ("LORA_STACK,MULTI_LORA_STACK", {
|
||||
"tooltip": "LoRA stacks for slots A-D, from a Prompt Manager or another relay; a plain LoRA stack is slot A.",
|
||||
}),
|
||||
**slots,
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MULTI_LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK", "LORA_STACK")
|
||||
RETURN_NAMES = ("lora_stacks", "lora_stack_a", "lora_stack_b", "lora_stack_c", "lora_stack_d")
|
||||
FUNCTION = "relay"
|
||||
DESCRIPTION = "Combine and split LoRA stacks: slots A-D come in as one set and as separate stacks, and go out both ways."
|
||||
|
||||
def relay(self, lora_stacks=None, lora_stack_a=None, lora_stack_b=None, lora_stack_c=None, lora_stack_d=None):
|
||||
incoming = normalize_lora_slots(lora_stacks, "a")
|
||||
added = {"a": lora_stack_a, "b": lora_stack_b, "c": lora_stack_c, "d": lora_stack_d}
|
||||
out = {slot: incoming[slot] + coerce_lora_stack(added[slot]) for slot in "abcd"}
|
||||
return (out, out["a"], out["b"], out["c"], out["d"])
|
||||
|
||||
|
||||
class LoraStackCombine:
|
||||
@@ -410,8 +386,8 @@ class LoraStackCombine:
|
||||
**kwargs,
|
||||
):
|
||||
merged = []
|
||||
merged.extend(_coerce_lora_stack(lora_stack_a))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_b))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_c))
|
||||
merged.extend(_coerce_lora_stack(lora_stack_d))
|
||||
merged.extend(coerce_lora_stack(lora_stack_a))
|
||||
merged.extend(coerce_lora_stack(lora_stack_b))
|
||||
merged.extend(coerce_lora_stack(lora_stack_c))
|
||||
merged.extend(coerce_lora_stack(lora_stack_d))
|
||||
return (merged,)
|
||||
|
||||
@@ -1,240 +0,0 @@
|
||||
"""Prompt Browser node with source-aware prompt selection and random multi-pick."""
|
||||
import json
|
||||
import random
|
||||
import time
|
||||
|
||||
import server
|
||||
|
||||
from ..py.prompt_composer_store import (
|
||||
PromptComposerStore,
|
||||
_find_category_case_insensitive,
|
||||
_find_prompt_case_insensitive,
|
||||
_get_category_prompts_map,
|
||||
)
|
||||
from .prompt_manager_basic import _get_workflow_node
|
||||
from .prompt_manager_basic import PromptManager
|
||||
from .prompt_generator import PromptGeneratorDataStore
|
||||
|
||||
|
||||
def _is_hidden_category_entry_key(name):
|
||||
normalized = str(name or "").strip().lower()
|
||||
return normalized in {"__meta__", "_base_prompt_", "_prompt_type_", "_prompts_"}
|
||||
|
||||
|
||||
def _iter_prompt_items(entries):
|
||||
if not isinstance(entries, dict):
|
||||
return []
|
||||
prompt_entries = _get_category_prompts_map(entries)
|
||||
if isinstance(prompt_entries, dict) and "_prompts_" in entries:
|
||||
return list(prompt_entries.items())
|
||||
return [
|
||||
(name, entry)
|
||||
for name, entry in entries.items()
|
||||
if not _is_hidden_category_entry_key(name)
|
||||
]
|
||||
|
||||
|
||||
class PromptBrowser:
|
||||
"""Browse prompts, select one or many, and emit a resolved prompt."""
|
||||
|
||||
SOURCE_COMPOSE = "Compose Data"
|
||||
SOURCE_PROMPT = "Prompt Data"
|
||||
SOURCE_SYSTEM_PROMPTS = "System Prompts"
|
||||
|
||||
@staticmethod
|
||||
def _load_prompts_for_source(source):
|
||||
if str(source or "") == PromptBrowser.SOURCE_PROMPT:
|
||||
return PromptManager.load_prompts()
|
||||
if str(source or "") == PromptBrowser.SOURCE_SYSTEM_PROMPTS:
|
||||
return PromptGeneratorDataStore.load()
|
||||
return PromptComposerStore.load_prompts()
|
||||
|
||||
@staticmethod
|
||||
def _pick_from_selected(selected_json, seed):
|
||||
try:
|
||||
names = json.loads(selected_json or "[]")
|
||||
except Exception:
|
||||
names = []
|
||||
if not isinstance(names, list) or not names:
|
||||
return ""
|
||||
|
||||
normalized = [str(name).strip() for name in names if str(name).strip()]
|
||||
if not normalized:
|
||||
return ""
|
||||
|
||||
try:
|
||||
seed_value = int(seed)
|
||||
except Exception:
|
||||
seed_value = 0
|
||||
|
||||
if seed_value == 0:
|
||||
return random.choice(normalized)
|
||||
|
||||
rng = random.Random(seed_value)
|
||||
return rng.choice(normalized)
|
||||
|
||||
@staticmethod
|
||||
def _has_multiple_selection(selected_json):
|
||||
try:
|
||||
names = json.loads(selected_json or "[]")
|
||||
except Exception:
|
||||
names = []
|
||||
return isinstance(names, list) and len(names) > 1
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
compose_data = PromptComposerStore.load_prompts()
|
||||
prompt_data = PromptManager.load_prompts()
|
||||
system_data = PromptGeneratorDataStore.load()
|
||||
|
||||
categories_set = set()
|
||||
for source_data in (compose_data, prompt_data, system_data):
|
||||
for category_name in source_data.keys():
|
||||
if category_name == "__meta__":
|
||||
continue
|
||||
categories_set.add(category_name)
|
||||
|
||||
categories = sorted(categories_set, key=str.lower)
|
||||
if not categories:
|
||||
categories = [""]
|
||||
|
||||
all_prompts = []
|
||||
first_prompt_text = ""
|
||||
first_prompt = ""
|
||||
for source_data in (compose_data, prompt_data, system_data):
|
||||
for cat in categories:
|
||||
entries = source_data.get(cat, {})
|
||||
if not isinstance(entries, dict):
|
||||
continue
|
||||
for name, entry in _iter_prompt_items(entries):
|
||||
all_prompts.append(name)
|
||||
if not first_prompt:
|
||||
first_prompt = name
|
||||
if isinstance(entry, dict):
|
||||
first_prompt_text = entry.get("prompt", "") or ""
|
||||
|
||||
all_prompts = sorted(all_prompts, key=str.lower)
|
||||
if not all_prompts:
|
||||
all_prompts = [""]
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"source": ([s.SOURCE_COMPOSE, s.SOURCE_PROMPT, s.SOURCE_SYSTEM_PROMPTS], {"default": s.SOURCE_SYSTEM_PROMPTS}),
|
||||
"category": (categories, {"default": categories[0]}),
|
||||
"name": (all_prompts, {"default": first_prompt}),
|
||||
"selected_prompts": ("STRING", {
|
||||
"default": "[]",
|
||||
"multiline": False,
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Internal: JSON list of selected prompts",
|
||||
}),
|
||||
"use_prompt_input": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"tooltip": "Toggle to use connected prompt input instead of internal text",
|
||||
}),
|
||||
"text": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": first_prompt_text,
|
||||
"placeholder": "Enter prompt fragment text",
|
||||
"dynamicPrompts": False,
|
||||
"tooltip": "Enter prompt fragment text directly",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"forceInput": True,
|
||||
"tooltip": "Connect a prompt input to pass through",
|
||||
}),
|
||||
},
|
||||
"hidden": {
|
||||
"seed": ("INT", {
|
||||
"default": 0,
|
||||
"min": 0,
|
||||
"max": 0xFFFFFFFFFFFFFFFF,
|
||||
}),
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO",
|
||||
"api_prompt": "PROMPT",
|
||||
}
|
||||
}
|
||||
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "Browse prompts from Prompt Data, Compose Data, or System Prompts with single or multi-random selection."
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("prompt",)
|
||||
FUNCTION = "get_prompt"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, name, **kwargs):
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", seed=0, prompt="", **kwargs):
|
||||
if cls._has_multiple_selection(selected_prompts):
|
||||
return (source, category, name, selected_prompts, use_prompt_input, text, time.time_ns(), prompt)
|
||||
return (source, category, name, selected_prompts, use_prompt_input, text, seed, prompt)
|
||||
|
||||
@staticmethod
|
||||
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
|
||||
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
|
||||
node_id = str(unique_id) if unique_id is not None else ""
|
||||
if not node_id:
|
||||
return
|
||||
|
||||
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
|
||||
if isinstance(workflow_node, dict):
|
||||
widgets = workflow_node.get("widgets_values")
|
||||
if isinstance(widgets, list):
|
||||
# Current layout: [source, category, name, selected_prompts, use_prompt_input, text]
|
||||
if len(widgets) > 4:
|
||||
widgets[4] = False
|
||||
if len(widgets) > 5:
|
||||
widgets[5] = output_text
|
||||
elif len(widgets) > 4:
|
||||
widgets[4] = output_text
|
||||
|
||||
if isinstance(api_prompt, dict):
|
||||
prompt_node = api_prompt.get(node_id)
|
||||
if isinstance(prompt_node, dict):
|
||||
inputs = prompt_node.get("inputs")
|
||||
if isinstance(inputs, dict):
|
||||
inputs["use_prompt_input"] = False
|
||||
inputs["text"] = output_text
|
||||
|
||||
def get_prompt(self, source, category, name, selected_prompts="[]", use_prompt_input=False, text="", prompt=None,
|
||||
seed=0, unique_id=None, extra_pnginfo=None, api_prompt=None):
|
||||
prompts_data = self._load_prompts_for_source(source)
|
||||
canonical_category = _find_category_case_insensitive(prompts_data, category) or category
|
||||
category_data = prompts_data.get(canonical_category, {})
|
||||
|
||||
chosen_name = name
|
||||
if self._has_multiple_selection(selected_prompts):
|
||||
picked = self._pick_from_selected(selected_prompts, seed)
|
||||
if picked:
|
||||
chosen_name = picked
|
||||
|
||||
entry, canonical_name = _find_prompt_case_insensitive(category_data, chosen_name)
|
||||
resolved_text = ""
|
||||
if isinstance(entry, dict):
|
||||
resolved_text = str(entry.get("prompt", "") or "")
|
||||
|
||||
if use_prompt_input and isinstance(prompt, str):
|
||||
output_text = prompt
|
||||
elif resolved_text.strip():
|
||||
output_text = resolved_text
|
||||
else:
|
||||
output_text = text
|
||||
|
||||
if unique_id is not None:
|
||||
server.PromptServer.instance.send_sync("prompt-manager-update-text", {
|
||||
"node_id": unique_id,
|
||||
"prompt": output_text,
|
||||
"use_prompt_input": use_prompt_input,
|
||||
"selected_name": canonical_name or chosen_name,
|
||||
"source": source,
|
||||
})
|
||||
|
||||
self._patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo, api_prompt)
|
||||
return (output_text,)
|
||||
@@ -120,10 +120,30 @@ def _exts_for_kind(kind):
|
||||
if kind == 'audiovideo':
|
||||
return AUDIO_EXTS | VIDEO_EXTS
|
||||
if kind == 'all':
|
||||
return ALL_MEDIA_EXTS
|
||||
return ALL_MEDIA_EXTS | JSON_EXTS
|
||||
return IMAGE_EXTS | VIDEO_EXTS
|
||||
|
||||
|
||||
def _load_hidden_names(directory):
|
||||
"""Names listed in a folder's .hidden file (one per line, # comments)."""
|
||||
hidden_names = set()
|
||||
try:
|
||||
with open(os.path.join(directory, '.hidden'), 'r', encoding='utf-8') as handle:
|
||||
for raw_line in handle:
|
||||
line = raw_line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
normalized = line.replace('\\', '/')
|
||||
while normalized.startswith('./'):
|
||||
normalized = normalized[2:]
|
||||
direct_child = normalized.strip('/').split('/', 1)[0]
|
||||
if direct_child and direct_child not in {'.', '..'}:
|
||||
hidden_names.add(direct_child)
|
||||
except OSError:
|
||||
pass
|
||||
return hidden_names
|
||||
|
||||
|
||||
def _probe_media_meta(file_path, ext):
|
||||
if ext not in VIDEO_EXTS and ext not in AUDIO_EXTS:
|
||||
return {"duration": None, "width": None, "height": None}
|
||||
@@ -549,9 +569,10 @@ async def prompt_extractor_path_browser_list(request):
|
||||
|
||||
dirs = []
|
||||
files = []
|
||||
hidden_names = _load_hidden_names(current)
|
||||
for entry in entries:
|
||||
name = entry.name
|
||||
if name.startswith('.'):
|
||||
if name.startswith('.') or name in hidden_names:
|
||||
continue
|
||||
try:
|
||||
if entry.is_dir(follow_symlinks=False):
|
||||
@@ -628,6 +649,36 @@ async def prompt_extractor_path_browser_file(request):
|
||||
return server.web.json_response({"ok": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-extractor/path-browser/delete")
|
||||
async def prompt_extractor_path_browser_delete(request):
|
||||
"""Delete one listed file, by absolute path or source + relative filename."""
|
||||
try:
|
||||
data = await request.json()
|
||||
source = (data.get('source') or '').strip().lower()
|
||||
filename = (data.get('filename') or '').strip()
|
||||
path = (data.get('path') or '').strip()
|
||||
|
||||
if source in ('input', 'output') and filename:
|
||||
base_dir = _resolve_source_base_dir(source)
|
||||
file_path = os.path.realpath(os.path.join(base_dir, filename.replace('/', os.sep)))
|
||||
if not _is_within(base_dir, file_path):
|
||||
return server.web.json_response({"ok": False, "error": "Invalid path"}, status=403)
|
||||
elif path:
|
||||
file_path = os.path.realpath(_safe_abspath(path))
|
||||
else:
|
||||
return server.web.json_response({"ok": False, "error": "Missing path"}, status=400)
|
||||
|
||||
if not os.path.isfile(file_path):
|
||||
return server.web.json_response({"ok": False, "error": "File not found"}, status=404)
|
||||
if os.path.splitext(file_path)[1].lower() not in ALL_MEDIA_EXTS | JSON_EXTS:
|
||||
return server.web.json_response({"ok": False, "error": "Unsupported file type"}, status=403)
|
||||
|
||||
os.remove(file_path)
|
||||
return server.web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return server.web.json_response({"ok": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-extractor/list-files")
|
||||
async def list_input_files(request):
|
||||
"""API endpoint to get list of supported files in input or output directory, including subfolders"""
|
||||
|
||||
@@ -19,7 +19,7 @@ import server
|
||||
import folder_paths
|
||||
from PIL import Image
|
||||
from io import BytesIO
|
||||
from ..py.backup_manager import atomic_save, load_with_fallback, check_backup
|
||||
from ..py.backup_manager import atomic_save, load_with_fallback
|
||||
from ..py.system_prompt_converter import convert_system_prompts, ensure_category_buckets
|
||||
|
||||
# ComfyUI-style ANSI console colors (matches app/logger.py)
|
||||
@@ -415,7 +415,6 @@ class PromptGeneratorDataStore:
|
||||
@staticmethod
|
||||
def load():
|
||||
data_path = _ensure_prompt_generator_data()
|
||||
check_backup(data_path)
|
||||
data = load_with_fallback(data_path, "PromptGeneratorDataStore")
|
||||
if not isinstance(data, dict):
|
||||
return {}
|
||||
@@ -531,6 +530,8 @@ async def generator_load_prompts_file(request):
|
||||
file_path = _safe_abspath(data.get("path", ""))
|
||||
if not file_path:
|
||||
return server.web.json_response({"success": False, "error": "Path is required"})
|
||||
if not file_path.lower().endswith(".json"):
|
||||
return server.web.json_response({"success": False, "error": "Only JSON files can be opened"}, status=400)
|
||||
if not os.path.isfile(file_path):
|
||||
return server.web.json_response({"success": False, "error": "JSON file not found"}, status=404)
|
||||
|
||||
|
||||
@@ -0,0 +1,302 @@
|
||||
"""Routes on the prompt library the Prompt Manager nodes share (py/prompt_store.py), each served under both the
|
||||
Basic (/prompt-manager) and the full node's (/prompt-manager-advanced) prefix. Each node's own save route stays in
|
||||
its module."""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import server
|
||||
|
||||
from ..py.backup_manager import atomic_save
|
||||
from ..py.prompt_store import is_hidden_key, load_prompts, save_prompts
|
||||
|
||||
PREFIXES = ("/prompt-manager", "/prompt-manager-advanced")
|
||||
|
||||
|
||||
def _route(method, name):
|
||||
"""Serve the handler at `name` under both prefixes. A failure answers as JSON, which the frontend shows."""
|
||||
def register(handler):
|
||||
async def respond(request):
|
||||
try:
|
||||
return await handler(request)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] {name} failed: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
for prefix in PREFIXES:
|
||||
getattr(server.PromptServer.instance.routes, method)(f"{prefix}/{name}")(respond)
|
||||
return handler
|
||||
return register
|
||||
|
||||
|
||||
def _fail(error, status=200):
|
||||
return server.web.json_response({"success": False, "error": error}, status=status)
|
||||
|
||||
|
||||
def _text(data, key):
|
||||
return str(data.get(key) or "").strip()
|
||||
|
||||
|
||||
def _find(entries, name):
|
||||
"""The prompt in `entries` named `name`, whatever its case (hidden category keys are not prompts)."""
|
||||
return next((key for key in entries if not is_hidden_key(key) and key.lower() == name.lower()), None)
|
||||
|
||||
|
||||
def _safe_abspath(path):
|
||||
return os.path.abspath(os.path.expanduser(path or ""))
|
||||
|
||||
|
||||
@_route("get", "get-prompts")
|
||||
async def get_prompts(request):
|
||||
return server.web.json_response(load_prompts())
|
||||
|
||||
|
||||
@_route("post", "save-category")
|
||||
async def save_category(request):
|
||||
data = await request.json()
|
||||
category = _text(data, "category_name")
|
||||
if not category:
|
||||
return _fail("Category name is required")
|
||||
|
||||
prompts = load_prompts()
|
||||
existing = {key.lower(): key for key in prompts}
|
||||
if category.lower() in existing:
|
||||
return _fail(f"Category already exists as '{existing[category.lower()]}'")
|
||||
|
||||
prompts[category] = {"__meta__": {"nsfw": True}} if data.get("nsfw") else {}
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
|
||||
@_route("post", "rename-category")
|
||||
async def rename_category(request):
|
||||
data = await request.json()
|
||||
old_category = _text(data, "old_category")
|
||||
new_category = _text(data, "new_category")
|
||||
if not old_category or not new_category:
|
||||
return _fail("Both old and new category names are required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if old_category not in prompts:
|
||||
return _fail(f"Category '{old_category}' not found")
|
||||
others = {key.lower(): key for key in prompts if key.lower() != old_category.lower()}
|
||||
if new_category.lower() in others:
|
||||
return _fail(f"Category already exists as '{others[new_category.lower()]}'")
|
||||
|
||||
prompts[new_category] = prompts.pop(old_category)
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_category": new_category})
|
||||
|
||||
|
||||
@_route("post", "delete-category")
|
||||
async def delete_category(request):
|
||||
data = await request.json()
|
||||
category = _text(data, "category")
|
||||
if not category:
|
||||
return _fail("Category name is required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if category not in prompts:
|
||||
return _fail("Category not found")
|
||||
|
||||
del prompts[category]
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
|
||||
@_route("post", "rename-prompt")
|
||||
async def rename_prompt(request):
|
||||
"""Rename a prompt, or move it to another category."""
|
||||
data = await request.json()
|
||||
category = _text(data, "category")
|
||||
old_name = _text(data, "old_name")
|
||||
new_name = _text(data, "new_name")
|
||||
new_category = _text(data, "new_category") or category
|
||||
if not category or not old_name or not new_name:
|
||||
return _fail("Category, old name, and new name are required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if category not in prompts:
|
||||
return _fail("Prompt not found")
|
||||
if new_category not in prompts:
|
||||
return _fail(f"Category '{new_category}' not found")
|
||||
|
||||
source, target = prompts[category], prompts[new_category]
|
||||
current = _find(source, old_name)
|
||||
if not current:
|
||||
return _fail("Prompt not found")
|
||||
clash = _find(target, new_name)
|
||||
if clash and not (new_category == category and clash == current):
|
||||
return _fail(f"A prompt named '{clash}' already exists in '{new_category}'")
|
||||
|
||||
target[new_name] = source.pop(current)
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
|
||||
|
||||
|
||||
@_route("post", "delete-prompt")
|
||||
async def delete_prompt(request):
|
||||
data = await request.json()
|
||||
category = _text(data, "category")
|
||||
name = _text(data, "name")
|
||||
if not category or not name:
|
||||
return _fail("Category and prompt name are required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return _fail("Prompt not found")
|
||||
|
||||
del prompts[category][name]
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
|
||||
@_route("post", "save-thumbnail")
|
||||
async def save_thumbnail(request):
|
||||
"""Set a prompt's thumbnail, or remove it when none is sent."""
|
||||
data = await request.json()
|
||||
category = _text(data, "category")
|
||||
name = _text(data, "name")
|
||||
thumbnail = data.get("thumbnail")
|
||||
if not category or not name:
|
||||
return _fail("Category and name required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return _fail("Prompt not found")
|
||||
|
||||
if thumbnail:
|
||||
prompts[category][name]["thumbnail"] = thumbnail
|
||||
else:
|
||||
prompts[category][name].pop("thumbnail", None)
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True})
|
||||
|
||||
|
||||
@_route("post", "toggle-nsfw")
|
||||
async def toggle_nsfw(request):
|
||||
"""Flip the NSFW flag of a category (type "category") or of a prompt (type "prompt")."""
|
||||
data = await request.json()
|
||||
kind = _text(data, "type")
|
||||
category = _text(data, "category")
|
||||
name = _text(data, "name")
|
||||
if not category:
|
||||
return _fail("Category is required")
|
||||
|
||||
prompts = load_prompts()
|
||||
if category not in prompts:
|
||||
return _fail("Category not found")
|
||||
|
||||
if kind == "category":
|
||||
meta = prompts[category].get("__meta__", {})
|
||||
meta["nsfw"] = not meta.get("nsfw", False)
|
||||
prompts[category]["__meta__"] = meta
|
||||
elif kind == "prompt":
|
||||
if not name or name not in prompts[category]:
|
||||
return _fail("Prompt not found")
|
||||
prompts[category][name]["nsfw"] = not prompts[category][name].get("nsfw", False)
|
||||
else:
|
||||
return _fail("Invalid type, must be 'category' or 'prompt'")
|
||||
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
|
||||
|
||||
@_route("post", "import-prompts")
|
||||
async def import_prompts(request):
|
||||
"""Import a library: "replace" starts from nothing, "skip_existing" keeps prompts already there, any other mode
|
||||
overwrites them."""
|
||||
data = await request.json()
|
||||
imported_data = data.get("data", {})
|
||||
mode = str(data.get("mode", "replace_existing") or "replace_existing").strip().lower()
|
||||
if not isinstance(imported_data, dict):
|
||||
return _fail("Invalid data format")
|
||||
|
||||
prompts = {} if mode == "replace" else load_prompts()
|
||||
imported_prompts = skipped_prompts = created_categories = 0
|
||||
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
created_categories += 1
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
# Hidden category metadata keys (not prompt entries); the base prompt and prefix are plain text.
|
||||
if is_hidden_key(prompt_name):
|
||||
if mode != "skip_existing" or prompt_name not in prompts[category]:
|
||||
prompts[category][prompt_name] = prompt_data
|
||||
continue
|
||||
|
||||
# Older exports stored a prompt as its text alone.
|
||||
if isinstance(prompt_data, str):
|
||||
prompt_data = {"prompt": prompt_data}
|
||||
elif not isinstance(prompt_data, dict):
|
||||
continue
|
||||
|
||||
if prompt_name in prompts[category] and mode == "skip_existing":
|
||||
skipped_prompts += 1
|
||||
continue
|
||||
|
||||
# Every field the entry carries (recipe data, negative prompt, thumbnail, flags) comes along; the lists
|
||||
# a prompt always has default to empty.
|
||||
prompts[category][prompt_name] = {
|
||||
"prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"loras_c": [],
|
||||
"loras_d": [],
|
||||
"trigger_words": [],
|
||||
**prompt_data,
|
||||
}
|
||||
imported_prompts += 1
|
||||
|
||||
save_prompts(prompts)
|
||||
return server.web.json_response({
|
||||
"success": True,
|
||||
"prompts": prompts,
|
||||
"imported_prompts": imported_prompts,
|
||||
"skipped_prompts": skipped_prompts,
|
||||
"created_categories": created_categories,
|
||||
})
|
||||
|
||||
|
||||
@_route("post", "load-prompts-file")
|
||||
async def load_prompts_file(request):
|
||||
"""A library JSON file the user picked with the file browser."""
|
||||
data = await request.json()
|
||||
file_path = _safe_abspath(data.get("path", ""))
|
||||
if not file_path:
|
||||
return _fail("Path is required")
|
||||
if not file_path.lower().endswith(".json"):
|
||||
return _fail("Only JSON files can be opened", 400)
|
||||
if not os.path.isfile(file_path):
|
||||
return _fail("JSON file not found", 404)
|
||||
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if not isinstance(loaded, dict):
|
||||
return _fail("Invalid JSON data format", 400)
|
||||
return server.web.json_response({"success": True, "data": loaded, "path": file_path})
|
||||
|
||||
|
||||
@_route("post", "export-prompts-file")
|
||||
async def export_prompts_file(request):
|
||||
"""Write a library to a JSON file the user picked with the file browser."""
|
||||
data = await request.json()
|
||||
raw_path = data.get("path", "")
|
||||
export_path = _safe_abspath(raw_path) if raw_path else ""
|
||||
if export_path and not export_path.lower().endswith(".json"):
|
||||
export_path = f"{export_path}.json"
|
||||
exported_data = data.get("data", {})
|
||||
if not export_path:
|
||||
return _fail("Export path is required")
|
||||
if not isinstance(exported_data, dict):
|
||||
return _fail("Invalid data format")
|
||||
|
||||
parent_dir = os.path.dirname(export_path)
|
||||
if not parent_dir or not os.path.isdir(parent_dir):
|
||||
return _fail("Target folder does not exist")
|
||||
if not atomic_save(export_path, exported_data, "PromptManagerExport"):
|
||||
return _fail("Failed to save export file", 500)
|
||||
return server.web.json_response({"success": True, "path": export_path})
|
||||
+196
-1545
File diff suppressed because it is too large
Load Diff
+14
-429
@@ -1,93 +1,21 @@
|
||||
import os
|
||||
import json
|
||||
import shutil
|
||||
import time
|
||||
import folder_paths
|
||||
import server
|
||||
from ..py.backup_manager import atomic_save, load_with_fallback, check_backup
|
||||
|
||||
|
||||
def _safe_abspath(path):
|
||||
return os.path.abspath(os.path.expanduser(path or ""))
|
||||
|
||||
|
||||
def _normalize_export_path(raw_path):
|
||||
candidate = _safe_abspath(raw_path)
|
||||
if not candidate:
|
||||
return ""
|
||||
if not candidate.lower().endswith(".json"):
|
||||
candidate = f"{candidate}.json"
|
||||
return candidate
|
||||
|
||||
|
||||
def _get_workflow_node(extra_pnginfo, node_id: str):
|
||||
"""Find workflow node by id, including nested subgraphs (id chains like a:b:c)."""
|
||||
if not isinstance(extra_pnginfo, dict):
|
||||
return None
|
||||
|
||||
workflow = extra_pnginfo.get("workflow")
|
||||
if not isinstance(workflow, dict):
|
||||
return None
|
||||
|
||||
nodes_list = workflow.get("nodes", []) if isinstance(workflow.get("nodes"), list) else []
|
||||
subgraphs = []
|
||||
definitions = workflow.get("definitions")
|
||||
if isinstance(definitions, dict):
|
||||
maybe_subgraphs = definitions.get("subgraphs")
|
||||
if isinstance(maybe_subgraphs, list):
|
||||
subgraphs = maybe_subgraphs
|
||||
|
||||
found = None
|
||||
for part in str(node_id).split(":"):
|
||||
found = next((n for n in nodes_list if isinstance(n, dict) and str(n.get("id")) == part), None)
|
||||
if not isinstance(found, dict):
|
||||
return None
|
||||
|
||||
subgraph = next((sg for sg in subgraphs if isinstance(sg, dict) and str(sg.get("id")) == str(found.get("type"))), None)
|
||||
if isinstance(subgraph, dict) and isinstance(subgraph.get("nodes"), list):
|
||||
nodes_list = subgraph.get("nodes", [])
|
||||
|
||||
return found
|
||||
|
||||
|
||||
def _patch_runtime_prompt_metadata(unique_id, output_text, extra_pnginfo=None, api_prompt=None):
|
||||
"""Persist resolved prompt into workflow/api metadata for downstream save nodes."""
|
||||
node_id = str(unique_id) if unique_id is not None else ""
|
||||
if not node_id:
|
||||
return
|
||||
|
||||
# Patch workflow metadata (EXTRA_PNGINFO).
|
||||
workflow_node = _get_workflow_node(extra_pnginfo, node_id)
|
||||
if isinstance(workflow_node, dict):
|
||||
widgets = workflow_node.get("widgets_values")
|
||||
if isinstance(widgets, list):
|
||||
# PromptManager widgets order:
|
||||
# [category, name, use_external, text]
|
||||
if len(widgets) > 2:
|
||||
widgets[2] = False
|
||||
if len(widgets) > 3:
|
||||
widgets[3] = output_text
|
||||
|
||||
# Patch API prompt metadata (PROMPT).
|
||||
if isinstance(api_prompt, dict):
|
||||
prompt_node = api_prompt.get(node_id)
|
||||
if isinstance(prompt_node, dict):
|
||||
inputs = prompt_node.get("inputs")
|
||||
if isinstance(inputs, dict):
|
||||
inputs["use_external"] = False
|
||||
inputs["text"] = output_text
|
||||
from ..py.prompt_metadata import record_prompt
|
||||
from ..py.prompt_store import is_hidden_key, load_prompts, save_prompts
|
||||
|
||||
|
||||
class PromptManager:
|
||||
"""Legacy: kept for saved workflows; Prompt Manager (PromptManagerV2) replaces it."""
|
||||
|
||||
DEPRECATED = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
prompts_data = PromptManager.load_prompts()
|
||||
prompts_data = load_prompts()
|
||||
categories = list(prompts_data.keys()) if prompts_data else ["Character"]
|
||||
|
||||
all_prompts = set()
|
||||
for category_prompts in prompts_data.values():
|
||||
all_prompts.update(k for k in category_prompts.keys() if k != "__meta__")
|
||||
all_prompts.update(k for k in category_prompts.keys() if not is_hidden_key(k))
|
||||
|
||||
all_prompts.add("")
|
||||
all_prompts_list = sorted(list(all_prompts))
|
||||
@@ -98,7 +26,7 @@ class PromptManager:
|
||||
first_prompt = ""
|
||||
first_prompt_text = ""
|
||||
if prompts_data and first_category in prompts_data and prompts_data[first_category]:
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if k != "__meta__"]
|
||||
first_category_prompts = [k for k in prompts_data[first_category].keys() if not is_hidden_key(k)]
|
||||
first_prompt = sorted(first_category_prompts, key=str.lower)[0] if first_category_prompts else ""
|
||||
if first_prompt:
|
||||
first_prompt_text = prompts_data[first_category][first_prompt].get("prompt", "")
|
||||
@@ -133,65 +61,6 @@ class PromptManager:
|
||||
# Return True to accept any value - this allows new prompts to be tested before saving
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def get_prompts_path():
|
||||
"""Get the path to the prompts JSON file in user/default folder"""
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", "prompt_manager_data.json")
|
||||
|
||||
@staticmethod
|
||||
def get_default_prompts_path():
|
||||
"""Get the path to the default prompts JSON file"""
|
||||
return os.path.join(os.path.dirname(os.path.dirname(__file__)), "prompts", "default_prompts.json")
|
||||
|
||||
@classmethod
|
||||
def load_prompts(cls):
|
||||
"""Load prompts from user folder or default"""
|
||||
user_path = cls.get_prompts_path()
|
||||
default_path = cls.get_default_prompts_path()
|
||||
|
||||
check_backup(user_path)
|
||||
|
||||
data = load_with_fallback(user_path, "PromptManager")
|
||||
if isinstance(data, dict):
|
||||
return data
|
||||
|
||||
if os.path.exists(default_path):
|
||||
try:
|
||||
with open(default_path, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
cls.save_prompts(data)
|
||||
return data
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error loading default prompts: {e}")
|
||||
|
||||
# Return empty structure if all else fails
|
||||
print("[PromptManager] Warning: No prompt files found, starting with empty data")
|
||||
return {}
|
||||
|
||||
@staticmethod
|
||||
def sort_prompts_data(data):
|
||||
"""Sort categories and prompts alphabetically (case-insensitive), preserving __meta__"""
|
||||
sorted_data = {}
|
||||
for category in sorted(data.keys(), key=str.lower):
|
||||
cat_data = data[category]
|
||||
meta = cat_data.get("__meta__")
|
||||
sorted_prompts = dict(sorted(
|
||||
((k, v) for k, v in cat_data.items() if k != "__meta__"),
|
||||
key=lambda item: item[0].lower()
|
||||
))
|
||||
if meta is not None:
|
||||
sorted_prompts["__meta__"] = meta
|
||||
sorted_data[category] = sorted_prompts
|
||||
return sorted_data
|
||||
return sorted_data
|
||||
|
||||
@classmethod
|
||||
def save_prompts(cls, data):
|
||||
"""Save prompts to user folder"""
|
||||
user_path = cls.get_prompts_path()
|
||||
sorted_data = cls.sort_prompts_data(data)
|
||||
atomic_save(user_path, sorted_data, "PromptManager")
|
||||
|
||||
def get_prompt(self, category, name, use_external, text="", llm_input="", unique_id=None, extra_pnginfo=None, api_prompt=None):
|
||||
"""Return the appropriate text based on use_external toggle and broadcast update"""
|
||||
|
||||
@@ -212,12 +81,7 @@ class PromptManager:
|
||||
|
||||
# Save resolved runtime prompt into execution metadata so saver nodes
|
||||
# embed the final prompt value, not the unresolved linked input state.
|
||||
_patch_runtime_prompt_metadata(
|
||||
unique_id=unique_id,
|
||||
output_text=output_text,
|
||||
extra_pnginfo=extra_pnginfo,
|
||||
api_prompt=api_prompt,
|
||||
)
|
||||
record_prompt(unique_id, output_text, extra_pnginfo, api_prompt, toggle="use_external", link_input="llm_input", text_index=3)
|
||||
return (output_text,)
|
||||
|
||||
def check_lazy_status(self, category, name, use_external, text, llm_input=None, unique_id=None,
|
||||
@@ -228,43 +92,6 @@ class PromptManager:
|
||||
return needed
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.get("/prompt-manager/get-prompts")
|
||||
async def get_prompts(request):
|
||||
"""API endpoint to get all prompts"""
|
||||
try:
|
||||
prompts = PromptManager.load_prompts()
|
||||
return server.web.json_response(prompts)
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in get_prompts API: {e}")
|
||||
return server.web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-category")
|
||||
async def save_category(request):
|
||||
"""API endpoint to create a new category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category_name = data.get("category_name", "").strip()
|
||||
|
||||
if not category_name:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
# Case-insensitive check for existing category
|
||||
existing_categories_lower = {k.lower(): k for k in prompts.keys()}
|
||||
if category_name.lower() in existing_categories_lower:
|
||||
return server.web.json_response({"success": False, "error": f"Category already exists as '{existing_categories_lower[category_name.lower()]}'"})
|
||||
|
||||
prompts[category_name] = {}
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-prompt")
|
||||
async def save_prompt(request):
|
||||
"""API endpoint to save a prompt"""
|
||||
@@ -279,7 +106,7 @@ async def save_prompt(request):
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
prompts = load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
@@ -320,255 +147,13 @@ async def save_prompt(request):
|
||||
print(f"[PromptManager] Removing old casing '{casing_name}' before saving as '{name}'")
|
||||
del prompts[category][casing_name]
|
||||
|
||||
# Save prompt in dict, preserving any existing lora data, trigger words, thumbnail, and nsfw from PromptManagerAdvanced
|
||||
prompts[category][name] = {
|
||||
"prompt": text,
|
||||
"loras_a": existing_data.get("loras_a", []),
|
||||
"loras_b": existing_data.get("loras_b", []),
|
||||
"trigger_words": existing_data.get("trigger_words", []),
|
||||
"thumbnail": existing_data.get("thumbnail")
|
||||
}
|
||||
# Preserve nsfw flag if it was set
|
||||
if existing_data.get("nsfw"):
|
||||
prompts[category][name]["nsfw"] = existing_data["nsfw"]
|
||||
# Only the text changes: LoRAs, trigger words, recipe data, thumbnail and flags saved by the full
|
||||
# Prompt Manager stay with the prompt.
|
||||
prompts[category][name] = {**existing_data, "prompt": text} if isinstance(existing_data, dict) else {"prompt": text}
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/rename-prompt")
|
||||
async def rename_prompt(request):
|
||||
"""API endpoint to rename or move a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
old_name = data.get("old_name", "").strip()
|
||||
new_name = data.get("new_name", "").strip()
|
||||
new_category = data.get("new_category", "").strip() or category
|
||||
|
||||
if not category or not old_name or not new_name:
|
||||
return server.web.json_response({"success": False, "error": "Category, old name, and new name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
if new_category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": f"Category '{new_category}' not found"})
|
||||
|
||||
source_prompts = prompts.get(category, {}) if isinstance(prompts.get(category), dict) else {}
|
||||
target_prompts = prompts.get(new_category, {}) if isinstance(prompts.get(new_category), dict) else {}
|
||||
existing_old_name = next((key for key in source_prompts.keys() if str(key).lower() == old_name.lower()), None)
|
||||
if not existing_old_name:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
existing_target_name = next((key for key in target_prompts.keys() if str(key).lower() == new_name.lower()), None)
|
||||
if existing_target_name:
|
||||
same_entry = new_category == category and str(existing_target_name).lower() == str(existing_old_name).lower()
|
||||
if not same_entry:
|
||||
return server.web.json_response({
|
||||
"success": False,
|
||||
"error": f"A prompt named '{existing_target_name}' already exists in '{new_category}'"
|
||||
})
|
||||
|
||||
entry = source_prompts.pop(existing_old_name)
|
||||
target_prompts[new_name] = entry
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts, "new_name": new_name, "new_category": new_category})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in rename_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/save-thumbnail")
|
||||
async def save_thumbnail(request):
|
||||
"""API endpoint to save or remove a thumbnail for a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
thumbnail = data.get("thumbnail") # Can be None to remove thumbnail
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and name required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
# Update or remove thumbnail
|
||||
if thumbnail:
|
||||
prompts[category][name]["thumbnail"] = thumbnail
|
||||
elif "thumbnail" in prompts[category][name]:
|
||||
del prompts[category][name]["thumbnail"]
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in save_thumbnail API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-category")
|
||||
async def delete_category(request):
|
||||
"""API endpoint to delete a category"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
|
||||
if not category:
|
||||
return server.web.json_response({"success": False, "error": "Category name is required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts:
|
||||
return server.web.json_response({"success": False, "error": "Category not found"})
|
||||
|
||||
del prompts[category]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_category API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/delete-prompt")
|
||||
async def delete_prompt(request):
|
||||
"""API endpoint to delete a prompt"""
|
||||
try:
|
||||
data = await request.json()
|
||||
category = data.get("category", "").strip()
|
||||
name = data.get("name", "").strip()
|
||||
|
||||
if not category or not name:
|
||||
return server.web.json_response({"success": False, "error": "Category and prompt name are required"})
|
||||
|
||||
prompts = PromptManager.load_prompts()
|
||||
|
||||
if category not in prompts or name not in prompts[category]:
|
||||
return server.web.json_response({"success": False, "error": "Prompt not found"})
|
||||
|
||||
del prompts[category][name]
|
||||
PromptManager.save_prompts(prompts)
|
||||
|
||||
return server.web.json_response({"success": True, "prompts": prompts})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in delete_prompt API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/import-prompts")
|
||||
async def import_prompts(request):
|
||||
"""API endpoint to import prompts from JSON"""
|
||||
try:
|
||||
data = await request.json()
|
||||
imported_data = data.get("data", {})
|
||||
mode = str(data.get("mode", "replace_existing") or "replace_existing").strip().lower()
|
||||
|
||||
if not isinstance(imported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
if mode == "replace":
|
||||
# Replace all existing prompts
|
||||
PromptManager.save_prompts(imported_data)
|
||||
return server.web.json_response({"success": True, "prompts": imported_data})
|
||||
else:
|
||||
# Merge with existing prompts
|
||||
prompts = PromptManager.load_prompts()
|
||||
imported_prompts = 0
|
||||
skipped_prompts = 0
|
||||
created_categories = 0
|
||||
|
||||
for category, category_prompts in imported_data.items():
|
||||
if not isinstance(category_prompts, dict):
|
||||
continue
|
||||
|
||||
if category not in prompts:
|
||||
prompts[category] = {}
|
||||
created_categories += 1
|
||||
|
||||
for prompt_name, prompt_data in category_prompts.items():
|
||||
if prompt_name == "__meta__":
|
||||
if mode != "skip_existing" or "__meta__" not in prompts[category]:
|
||||
prompts[category][prompt_name] = prompt_data
|
||||
continue
|
||||
|
||||
if prompt_name in prompts[category] and mode == "skip_existing":
|
||||
skipped_prompts += 1
|
||||
continue
|
||||
|
||||
# Merge prompt data, preserving structure
|
||||
if isinstance(prompt_data, dict):
|
||||
prompts[category][prompt_name] = prompt_data
|
||||
elif isinstance(prompt_data, str):
|
||||
# Legacy format: just the prompt text
|
||||
prompts[category][prompt_name] = {"prompt": prompt_data}
|
||||
else:
|
||||
continue
|
||||
imported_prompts += 1
|
||||
|
||||
PromptManager.save_prompts(prompts)
|
||||
return server.web.json_response({
|
||||
"success": True,
|
||||
"prompts": prompts,
|
||||
"imported_prompts": imported_prompts,
|
||||
"skipped_prompts": skipped_prompts,
|
||||
"created_categories": created_categories,
|
||||
})
|
||||
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in import_prompts API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/load-prompts-file")
|
||||
async def load_prompts_file(request):
|
||||
try:
|
||||
data = await request.json()
|
||||
file_path = _safe_abspath(data.get("path", ""))
|
||||
if not file_path:
|
||||
return server.web.json_response({"success": False, "error": "Path is required"})
|
||||
if not os.path.isfile(file_path):
|
||||
return server.web.json_response({"success": False, "error": "JSON file not found"}, status=404)
|
||||
|
||||
with open(file_path, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if not isinstance(loaded, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid JSON data format"}, status=400)
|
||||
|
||||
return server.web.json_response({"success": True, "data": loaded, "path": file_path})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in load_prompts_file API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
|
||||
@server.PromptServer.instance.routes.post("/prompt-manager/export-prompts-file")
|
||||
async def export_prompts_file(request):
|
||||
try:
|
||||
data = await request.json()
|
||||
export_path = _normalize_export_path(data.get("path", ""))
|
||||
exported_data = data.get("data", {})
|
||||
|
||||
if not export_path:
|
||||
return server.web.json_response({"success": False, "error": "Export path is required"})
|
||||
if not isinstance(exported_data, dict):
|
||||
return server.web.json_response({"success": False, "error": "Invalid data format"})
|
||||
|
||||
parent_dir = os.path.dirname(export_path)
|
||||
if not parent_dir or not os.path.isdir(parent_dir):
|
||||
return server.web.json_response({"success": False, "error": "Target folder does not exist"})
|
||||
|
||||
if not atomic_save(export_path, exported_data, "PromptManagerExport"):
|
||||
return server.web.json_response({"success": False, "error": "Failed to save export file"}, status=500)
|
||||
|
||||
return server.web.json_response({"success": True, "path": export_path})
|
||||
except Exception as e:
|
||||
print(f"[PromptManager] Error in export_prompts_file API: {e}")
|
||||
return server.web.json_response({"success": False, "error": str(e)}, status=500)
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
"""Prompt Manager: a saved prompt, typed or taken from the prompt input, with the LoRA stacks and trigger words that
|
||||
go with it. The node face only shows what is in use: one LoRA panel per slot that has LoRAs, trigger words when there
|
||||
are any. On/off and strength edits live in the `state` widget, as overrides by slot and LoRA name; the rows the panels
|
||||
show go back to the frontend as the node's UI output."""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
from ..py.lora_stacks import (
|
||||
LORA_MODE_COMBINE,
|
||||
LORA_MODE_INPUT_ONLY,
|
||||
LORA_MODE_PROMPT_ONLY,
|
||||
LORA_MODES,
|
||||
MODEL_SLOT_KEYS,
|
||||
PROMPT_MANAGER_RECIPE_KEY,
|
||||
derive_prompt_fields,
|
||||
flatten_lora_slots,
|
||||
merge_prompt_composer_input_data,
|
||||
normalize_lora_slots,
|
||||
)
|
||||
from ..py.lora_utils import get_available_loras, get_lora_relative_path, normalize_path_separators, strip_lora_extension
|
||||
from ..py.prompt_metadata import record_prompt
|
||||
from ..py.prompt_store import is_hidden_key, load_prompts
|
||||
from ..py.workflow_data_utils import build_v2_recipe_data_from_prompt, ensure_v2_recipe_data
|
||||
|
||||
|
||||
def _saved_entry(category, name):
|
||||
entry = load_prompts().get(category, {}).get(name, {})
|
||||
return entry if isinstance(entry, dict) else {}
|
||||
|
||||
|
||||
def _parse_state(state):
|
||||
"""The node's edits: {"loras": {slot: {name: {"active", "strength", "removed"}}}, "order": {slot: [name]},
|
||||
"trigger_words": {text: {"active", "removed"}}}, names and texts in lower case."""
|
||||
try:
|
||||
parsed = json.loads(state) if isinstance(state, str) and state else {}
|
||||
except json.JSONDecodeError:
|
||||
return {}
|
||||
return parsed if isinstance(parsed, dict) else {}
|
||||
|
||||
|
||||
def _lora_name(path):
|
||||
return strip_lora_extension(os.path.basename(normalize_path_separators(path)))
|
||||
|
||||
|
||||
def _saved_row(lora):
|
||||
"""A LoRA saved with the prompt (or in its recipe), as a panel row; found among the local LoRAs by name."""
|
||||
name = str(lora.get("name", "")).strip()
|
||||
strength = float(lora.get("strength", lora.get("model_strength", 1.0)))
|
||||
path, available = get_lora_relative_path(name)
|
||||
return {
|
||||
"name": name,
|
||||
"path": path if available else name,
|
||||
"strength": strength,
|
||||
"clip_strength": float(lora.get("clip_strength", strength)),
|
||||
"active": lora.get("active", True) is not False,
|
||||
"available": available,
|
||||
"from_input": False,
|
||||
}
|
||||
|
||||
|
||||
def _input_row(path, model_strength, clip_strength, lora_files):
|
||||
"""A LoRA from the lora_stacks input, as a panel row."""
|
||||
name = _lora_name(path)
|
||||
available = path in lora_files
|
||||
if not available:
|
||||
found_path, available = get_lora_relative_path(name)
|
||||
if available:
|
||||
path = found_path
|
||||
return {
|
||||
"name": name,
|
||||
"path": path,
|
||||
"strength": float(model_strength),
|
||||
"clip_strength": float(clip_strength),
|
||||
"active": True,
|
||||
"available": available,
|
||||
"from_input": True,
|
||||
}
|
||||
|
||||
|
||||
def _apply_override(row, override):
|
||||
"""The row with the node's on/off, strength and removal edits; clip strength follows the strength by the same
|
||||
ratio. The row keeps its own strength and state as base_strength and base_active, for the frontend's reset."""
|
||||
row["base_strength"] = row["strength"]
|
||||
row["base_active"] = row["active"]
|
||||
row["removed"] = override.get("removed") is True
|
||||
if "active" in override:
|
||||
row["active"] = override["active"] is not False
|
||||
if isinstance(override.get("strength"), (int, float)):
|
||||
strength = float(override["strength"])
|
||||
row["clip_strength"] *= strength / row["strength"] if row["strength"] else 1.0
|
||||
row["strength"] = strength
|
||||
return row
|
||||
|
||||
|
||||
def _slot_rows(prompt_loras, input_stack, mode, overrides, order, lora_files):
|
||||
"""One slot's panel rows: the prompt's LoRAs, the input's, or both (the prompt's first, an input LoRA of the same
|
||||
name left out), with the node's edits, in the node's order (LoRAs it does not name after, as they came)."""
|
||||
rows = []
|
||||
if mode != LORA_MODE_INPUT_ONLY:
|
||||
rows += [_saved_row(lora) for lora in prompt_loras if isinstance(lora, dict) and str(lora.get("name", "")).strip()]
|
||||
if mode != LORA_MODE_PROMPT_ONLY:
|
||||
rows += [_input_row(*item, lora_files) for item in input_stack]
|
||||
unique, seen = [], set()
|
||||
for row in rows:
|
||||
key = row["name"].lower()
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
unique.append(_apply_override(row, overrides.get(key, {})))
|
||||
unique.sort(key=lambda row: order.index(row["name"].lower()) if row["name"].lower() in order else len(order))
|
||||
return unique
|
||||
|
||||
|
||||
def _trigger_rows(saved_words, connected_words, overrides):
|
||||
"""Trigger words saved with the prompt, then the connected ones not already there, with the node's on/off and
|
||||
removal edits. Connected words come as one string, groups split by ",," (as LoRA Manager sends them)."""
|
||||
rows, seen = [], set()
|
||||
candidates = [(word.get("text", "") if isinstance(word, dict) else word, word.get("active", True) if isinstance(word, dict) else True, False)
|
||||
for word in saved_words or []]
|
||||
if isinstance(connected_words, str):
|
||||
candidates += [(word, True, True) for word in connected_words.split(",,")]
|
||||
for text, active, from_input in candidates:
|
||||
text = str(text or "").strip()
|
||||
if text and text.lower() not in seen:
|
||||
seen.add(text.lower())
|
||||
override = overrides.get(text.lower(), {})
|
||||
rows.append({"text": text, "active": override.get("active", active is not False) is not False, "base_active": active is not False,
|
||||
"removed": override.get("removed") is True, "from_input": from_input})
|
||||
return rows
|
||||
|
||||
|
||||
def _with_trigger_words(prompt, words):
|
||||
"""Trigger words before the prompt, the block ending in punctuation."""
|
||||
block = ", ".join(words).strip()
|
||||
if not block:
|
||||
return prompt
|
||||
if not block.endswith((".", ",", ":")):
|
||||
block += ","
|
||||
prompt = str(prompt or "").strip()
|
||||
return f"{block} {prompt}" if prompt else block
|
||||
|
||||
|
||||
class PromptManagerV2:
|
||||
CATEGORY = "Prompt Manager"
|
||||
DESCRIPTION = "A saved prompt, typed or from the prompt input, with its LoRA stacks and trigger words. LoRA stacks go out as a plain LoRA stack when one slot has LoRAs, as a multi LoRA stack when several do."
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
prompts = load_prompts()
|
||||
categories = list(prompts) or ["Default"]
|
||||
names = sorted({key for entries in prompts.values() for key in entries if not is_hidden_key(key)} | {""}, key=str.lower)
|
||||
return {
|
||||
"required": {
|
||||
"category": (categories, {"default": categories[0]}),
|
||||
"name": (names, {"default": ""}),
|
||||
"use_prompt_input": ("BOOLEAN", {"default": False, "tooltip": "Use the connected prompt instead of the typed one."}),
|
||||
"lora_mode": (list(LORA_MODES), {"default": LORA_MODE_COMBINE, "tooltip": "Which LoRAs go out: the prompt's, both (the prompt's first), or the input's."}),
|
||||
"text": ("STRING", {"multiline": True, "default": "", "dynamicPrompts": False}),
|
||||
},
|
||||
"optional": {
|
||||
"prompt": ("STRING", {"forceInput": True, "lazy": True, "tooltip": "A prompt to use instead of the typed one."}),
|
||||
"lora_stacks": ("LORA_STACK,MULTI_LORA_STACK", {"forceInput": True, "tooltip": "LoRA stacks to combine with the prompt's; a plain LoRA stack is slot A."}),
|
||||
"manager_data": ("MANAGER_DATA", {"forceInput": True, "tooltip": "A recipe: its LoRAs are the prompt's, its prompt is used when none is typed."}),
|
||||
"trigger_words": ("STRING", {"forceInput": True, "tooltip": "Trigger words to put before the prompt, groups separated by ,,"}),
|
||||
"state": ("STRING", {"default": "{}"}),
|
||||
},
|
||||
"hidden": {
|
||||
"unique_id": "UNIQUE_ID",
|
||||
"extra_pnginfo": "EXTRA_PNGINFO",
|
||||
"api_prompt": "PROMPT",
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "LORA_STACK,MULTI_LORA_STACK", "MANAGER_DATA")
|
||||
RETURN_NAMES = ("prompt", "lora_stacks", "manager_data")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The prompt, its active trigger words first.",
|
||||
"The active LoRAs: a plain LoRA stack when one slot has LoRAs, a multi LoRA stack (slots A-D) when several do.",
|
||||
"The prompt and its LoRAs as a recipe.",
|
||||
)
|
||||
FUNCTION = "get_prompt"
|
||||
# Runs on its own (ComfyUI's run-node button) to pull in a prompt from a generator upstream.
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def VALIDATE_INPUTS(cls, category, name):
|
||||
# A prompt or category renamed or deleted since the workflow was saved still runs, from its typed text.
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, category, name, **kwargs):
|
||||
# The prompt's saved LoRAs and trigger words can change in the library without any input changing.
|
||||
return json.dumps(_saved_entry(category, name), sort_keys=True, default=str)
|
||||
|
||||
def check_lazy_status(self, use_prompt_input, prompt=None, **kwargs):
|
||||
return ["prompt"] if use_prompt_input else []
|
||||
|
||||
def get_prompt(self, category, name, use_prompt_input, lora_mode, text, prompt=None, lora_stacks=None, manager_data=None,
|
||||
trigger_words=None, state="{}", unique_id=None, extra_pnginfo=None, api_prompt=None):
|
||||
overrides = _parse_state(state)
|
||||
entry = _saved_entry(category, name)
|
||||
stored_recipe = entry.get("workflow_data")
|
||||
recipe = (ensure_v2_recipe_data(manager_data, source="PromptManager") if isinstance(manager_data, dict)
|
||||
else ensure_v2_recipe_data(stored_recipe, source="PromptManager") if isinstance(stored_recipe, dict) else None)
|
||||
fields = derive_prompt_fields(recipe)
|
||||
|
||||
# The prompt input when it is on and has text, else the typed text, else the recipe's prompt.
|
||||
if use_prompt_input and prompt:
|
||||
output_text = prompt
|
||||
else:
|
||||
output_text = text if text.strip() else fields["prompt"]
|
||||
|
||||
inputs = normalize_lora_slots(lora_stacks, "a")
|
||||
lora_files = get_available_loras()
|
||||
lora_overrides = overrides.get("loras") if isinstance(overrides.get("loras"), dict) else {}
|
||||
orders = overrides.get("order") if isinstance(overrides.get("order"), dict) else {}
|
||||
shown, rows, stacks = {}, {}, {}
|
||||
for slot in MODEL_SLOT_KEYS:
|
||||
# The prompt's LoRAs: the connected recipe's, else the saved prompt's, else its saved recipe's.
|
||||
prompt_loras = fields[f"loras_{slot}"] if isinstance(manager_data, dict) else (entry.get(f"loras_{slot}") or fields[f"loras_{slot}"])
|
||||
slot_overrides = lora_overrides.get(slot) if isinstance(lora_overrides.get(slot), dict) else {}
|
||||
order = orders.get(slot) if isinstance(orders.get(slot), list) else []
|
||||
shown[slot] = _slot_rows(prompt_loras, inputs[slot], lora_mode, slot_overrides, order, lora_files)
|
||||
rows[slot] = [row for row in shown[slot] if not row["removed"]]
|
||||
stacks[slot] = [(row["path"], row["strength"], row["clip_strength"]) for row in rows[slot] if row["active"] and row["available"]]
|
||||
|
||||
word_overrides = overrides.get("trigger_words") if isinstance(overrides.get("trigger_words"), dict) else {}
|
||||
shown_words = _trigger_rows(entry.get("trigger_words"), trigger_words, word_overrides)
|
||||
final_output = _with_trigger_words(output_text, [word["text"] for word in shown_words if word["active"] and not word["removed"]])
|
||||
|
||||
# Saver nodes embed the final prompt as typed text, not the link that fed it.
|
||||
record_prompt(unique_id, final_output, extra_pnginfo, api_prompt, toggle="use_prompt_input", link_input="prompt", text_index=4)
|
||||
|
||||
filled = [slot for slot in MODEL_SLOT_KEYS if stacks[slot]]
|
||||
lora_output = stacks if len(filled) > 1 else (stacks[filled[0]] if filled else [])
|
||||
|
||||
recipe_out = build_v2_recipe_data_from_prompt(
|
||||
prompt_text=final_output,
|
||||
negative_prompt=fields["negative_prompt"],
|
||||
**{f"loras_{slot}": rows[slot] for slot in MODEL_SLOT_KEYS},
|
||||
source="PromptManager",
|
||||
base_recipe_data=recipe,
|
||||
)
|
||||
prompt_input_text = prompt or ""
|
||||
recipe_out = merge_prompt_composer_input_data(
|
||||
recipe_out,
|
||||
input_prompt=prompt_input_text,
|
||||
prompt_enabled=bool(use_prompt_input and prompt_input_text),
|
||||
input_lora_stack=flatten_lora_slots(stacks),
|
||||
)
|
||||
recipe_out[PROMPT_MANAGER_RECIPE_KEY] = {"category": category, "name": name}
|
||||
|
||||
# The panels' rows for the frontend (onExecuted), for the prompt they were made for; removed rows included,
|
||||
# so undoing a removal needs no new run.
|
||||
panels = {"category": category, "name": name, "lora_mode": lora_mode, "loras": shown, "trigger_words": shown_words, "prompt_input": prompt if use_prompt_input else None}
|
||||
return {"ui": {"prompt_manager": [panels]}, "result": (final_output, lora_output, recipe_out)}
|
||||
@@ -10,6 +10,11 @@
|
||||
"prompt": "You are a realistic photography prompt director. Transform the user's idea into a photoreal prompt with clear subject, scene, lens/framing cues, lighting direction, material detail, and natural color grading. Prioritize believable anatomy, physical plausibility, and coherent environment interactions. Return a single polished prompt only."
|
||||
}
|
||||
},
|
||||
"Edit": {
|
||||
"Generate Prompt MiniMax Outpaint": {
|
||||
"prompt": "You are an expert prompt writer for outpainting with the MiniMax H3 Image edit model. The user provides **one image, the outpaint canvas**: their picture placed on a larger canvas, with the new area to be painted shown as flat neutral gray around it. They may also add a short text saying what they want in the new area; it can be empty. Write the edit prompt that extends the picture into the gray area.\n\n#### What the model sees:\n- The model is given only the original picture as <Picture 1>, never the gray canvas. Refer to the picture only as <Picture 1>, and never mention gray, padding, borders, bars, a canvas or a mask in the prompt.\n\n#### Workflow:\n- First, find which sides of the canvas are gray (top, bottom, left, right) and roughly how far each reaches compared with the picture. Only those sides get new content.\n- Next, read the picture as a scene: its medium (photograph, film still, 3D render, painting, drawing, anime...), camera angle and lens, horizon line and vanishing points, lighting direction, time of day, weather, color grading, and every element cut off by an edge on a gray side (a building facade, a road, a sidewalk, a crowd, a shoreline, the sky, a ceiling, a floor).\n- Then, decide what lies beyond each of those edges: continue every cut-off element naturally, keeping perspective, scale, lighting and style, and fill the rest with what plausibly surrounds such a scene. The larger the new area, the more surroundings it shows.\n- Follow the user's text: place what they ask for in the new area, on the side they name or wherever it fits best, at a scale that matches the scene. Their wishes override your own ideas for the new area, but never <Picture 1> itself.\n\n#### Rules:\n- <Picture 1> stays exactly as it is, at the same position and size. Never ask to change, move, recolor or restyle anything already in it.\n- Do not repeat the main subject of <Picture 1> in the new area (no second car, person or building that mirrors it) unless the user asks for it.\n- Keep new subjects secondary to <Picture 1> unless the user asks otherwise.\n- Be concrete and visual; avoid metaphor. Enclose any text the user wants written in the image in English double quotes.\n\n#### Output Format:\n- Output only the final prompt, in English, as one paragraph of at most about 150 words, with no headings or explanations.\n- Start with: Outpaint <Picture 1>: extend it into a wider view of the same scene.\n- Then describe, side by side, what the new areas show beyond each extended edge.\n- End with: <Picture 1> stays exactly as it is, at the same position and size. The new areas continue its surroundings seamlessly beyond every edge in exactly the same medium, rendering and look as <Picture 1>: a photograph stays a real photograph with the same camera, lens, depth of field, lighting and color grading; a drawing or painting keeps the same art style. One continuous image."
|
||||
}
|
||||
},
|
||||
"Bbox": {
|
||||
"MOSS Layout - Create": {
|
||||
"prompt": "You are a layout director for MOSS-Image, an image model that reads a JSON layout: one caption for the whole scene plus boxed regions, each with its own description. Turn the user's request into one complete layout.\n\nOutput only the JSON object inside a ```json code block, with no text before or after it.\n\n## Coordinates\n- Boxes are percentages of the canvas: 0 is the top or left edge, 100 is the bottom or right edge. Both axes always run from 0 to 100, whatever the aspect ratio.\n- Every \"bbox\" is [top, left, bottom, right], with top < bottom and left < right.\n- Use numbers from 0 to 100 with at most one decimal.\n- Set \"bbox_coord_space\" to \"percent\" and \"bbox_format\" to \"yxyx\".\n- Each axis scales separately, so a box that is square in percent is only square on a square canvas. Size boxes for the canvas shape the user asks for, and assume a square canvas when none is given.\n\n## Summary\n- \"caption\": two to five sentences describing the whole image: subject, setting, composition, lighting, mood and style.\n- \"meta\": one to four short style tags, such as \"photograph\", \"poster\", \"illustration\" or \"3d render\".\n- \"canvas\": \"single\" for one image, \"multi_panel\" for comic pages or storyboards, \"collage\" for collages.\n- \"palette\": optional, three to six dominant colors as \"#RRGGBB\".\n\n## Items\n- One item per region that matters, ordered from back to front: large background regions first, foreground subjects last.\n- \"label\": \"character\" for a person or creature with an identity, \"text\" for written words, \"object\" for everything else.\n- \"caption\": what the region looks like (appearance, pose, material, color) and how it relates to its neighbours. Keep it consistent with the box position and size.\n- Text items also need \"text\" with the exact words to render. Their caption describes the typography and placement.\n- \"palette\": optional, one to four \"#RRGGBB\" colors specific to the region.\n- Overlap boxes only when one subject is in front of, or part of, another.\n- Keep the user's spelling and capitalization for text, and do not invent text unless the request implies it, such as a poster title, a sign or a label.\n- Size each box to the full extent of its subject: a standing full-body figure is tall and narrow, a close-up face is large. Leave margins unless the subject should touch the edge. A full-bleed background is [0, 0, 100, 100].\n\n## Format\n```json\n{\n \"summary\": {\n \"meta\": [\"poster\"],\n \"canvas\": \"single\",\n \"caption\": \"A minimalist travel poster of a lighthouse on a rocky cape at dusk, flat vector shapes, warm sky over a deep blue sea.\",\n \"palette\": [\"#F2A65A\", \"#1D3557\", \"#F1FAEE\"]\n },\n \"items\": [\n {\n \"label\": \"object\",\n \"caption\": \"Dusk sky fading from orange at the horizon to deep blue above, over a calm sea.\",\n \"bbox\": [0, 0, 100, 100]\n },\n {\n \"label\": \"object\",\n \"caption\": \"White lighthouse with a red band on a dark rocky cape, its beam reaching left.\",\n \"bbox\": [28, 55, 88, 80]\n },\n {\n \"label\": \"character\",\n \"caption\": \"A small figure in a yellow raincoat standing on the rocks, looking up at the lighthouse.\",\n \"bbox\": [70, 40, 86, 47]\n },\n {\n \"label\": \"text\",\n \"text\": \"CAPE LIGHT\",\n \"caption\": \"Bold cream sans-serif title centered across the top.\",\n \"bbox\": [6, 15, 18, 85]\n }\n ],\n \"bbox_coord_space\": \"percent\",\n \"bbox_format\": \"yxyx\"\n}\n```\n\nBefore answering, check that the JSON is valid, every bbox has four numbers in the order [top, left, bottom, right], and every text item has \"text\"."
|
||||
|
||||
+33
-58
@@ -21,16 +21,10 @@ def _get_backups_dir():
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", BACKUPS_DIR_NAME)
|
||||
|
||||
|
||||
def _ensure_backups_dir():
|
||||
path = _get_backups_dir()
|
||||
os.makedirs(path, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def _backup_path(data_path, index):
|
||||
"""Return the path for the i-th numbered backup (1-based)."""
|
||||
filename = os.path.basename(data_path)
|
||||
return os.path.join(_ensure_backups_dir(), f"{filename}_bak_{index:02d}")
|
||||
return os.path.join(_get_backups_dir(), f"{filename}_bak_{index:02d}")
|
||||
|
||||
|
||||
def _rotate_backups(data_path):
|
||||
@@ -50,15 +44,14 @@ def _rotate_backups(data_path):
|
||||
pass
|
||||
|
||||
|
||||
def _is_valid_json_file(path):
|
||||
if not os.path.exists(path):
|
||||
return False
|
||||
def _read_json_dict(path):
|
||||
"""The JSON object stored at path, or None when it is missing, unreadable or not an object."""
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return isinstance(data, dict)
|
||||
except Exception:
|
||||
return False
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
return data if isinstance(data, dict) else None
|
||||
|
||||
|
||||
def _backup_is_from_today(backup_path):
|
||||
@@ -73,53 +66,24 @@ def _backup_is_from_today(backup_path):
|
||||
return False
|
||||
|
||||
|
||||
def refresh_backup(data_path):
|
||||
"""
|
||||
Rotate backups and copy the current data file to *_bak_01 if valid.
|
||||
This is the daily backup entry point; it should NOT be called on every save.
|
||||
"""
|
||||
if not _is_valid_json_file(data_path):
|
||||
return
|
||||
if _backup_is_from_today(_backup_path(data_path, 1)):
|
||||
return
|
||||
_rotate_backups(data_path)
|
||||
try:
|
||||
_ensure_backups_dir()
|
||||
backup_path = _backup_path(data_path, 1)
|
||||
shutil.copy2(data_path, backup_path)
|
||||
# Record the backup creation time so _backup_is_from_today() works.
|
||||
os.utime(backup_path, None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def load_with_fallback(data_path, log_prefix="PromptManager"):
|
||||
"""
|
||||
Load JSON from data_path. If corrupt, try *_bak_01..*_bak_05 and return
|
||||
the newest valid backup. The main file is NOT overwritten here.
|
||||
Load JSON from data_path. If it is unreadable, return the newest valid
|
||||
*_bak_01..*_bak_05 instead. The main file is NOT overwritten here. None
|
||||
when there is no file and no backup.
|
||||
"""
|
||||
if _is_valid_json_file(data_path):
|
||||
try:
|
||||
with open(data_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[{log_prefix}] Error loading {data_path}: {e}")
|
||||
else:
|
||||
print(f"[{log_prefix}] Data file missing or corrupt: {data_path}")
|
||||
|
||||
data = _read_json_dict(data_path)
|
||||
if data is not None:
|
||||
return data
|
||||
exists = os.path.exists(data_path)
|
||||
for i in range(1, MAX_BACKUPS + 1):
|
||||
candidate = _backup_path(data_path, i)
|
||||
if not _is_valid_json_file(candidate):
|
||||
continue
|
||||
try:
|
||||
with open(candidate, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
print(f"[{log_prefix}] Recovered data from backup: {candidate}")
|
||||
data = _read_json_dict(candidate)
|
||||
if data is not None:
|
||||
print(f"[{log_prefix}] {data_path} is unreadable; using the backup {candidate}")
|
||||
return data
|
||||
except Exception as be:
|
||||
print(f"[{log_prefix}] Backup load failed ({candidate}): {be}")
|
||||
|
||||
print(f"[{log_prefix}] No valid backup found for {data_path}.")
|
||||
if exists:
|
||||
print(f"[{log_prefix}] {data_path} is unreadable and no backup could be read")
|
||||
return None
|
||||
|
||||
|
||||
@@ -151,9 +115,20 @@ def atomic_save(data_path, data, log_prefix="PromptManager"):
|
||||
|
||||
def check_backup(data_path):
|
||||
"""
|
||||
Called on startup for each registered data file. Creates a daily backup if
|
||||
one does not already exist for today.
|
||||
Called on startup for each registered data file: rotate backups and copy
|
||||
the current data file to *_bak_01 if it is valid and today has no backup
|
||||
yet. Not called on every load or save.
|
||||
"""
|
||||
if not _is_valid_json_file(data_path):
|
||||
if _read_json_dict(data_path) is None:
|
||||
return
|
||||
refresh_backup(data_path)
|
||||
if _backup_is_from_today(_backup_path(data_path, 1)):
|
||||
return
|
||||
_rotate_backups(data_path)
|
||||
try:
|
||||
os.makedirs(_get_backups_dir(), exist_ok=True)
|
||||
backup_path = _backup_path(data_path, 1)
|
||||
shutil.copy2(data_path, backup_path)
|
||||
# Record the backup creation time so _backup_is_from_today() works.
|
||||
os.utime(backup_path, None)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
"""LoRA stacks and recipe data as the Prompt Manager nodes read them: four model slots A-D, connected stacks
|
||||
normalized into them, and the prompt and LoRAs a v2 recipe (manager_data) carries."""
|
||||
|
||||
import os
|
||||
|
||||
from .lora_utils import normalize_path_separators
|
||||
from .workflow_data_utils import ensure_v2_recipe_data
|
||||
|
||||
|
||||
def has_meaningful_workflow_data(workflow_data):
|
||||
"""Return True when v2 recipe data contains authored prompt/model/lora content."""
|
||||
for block in workflow_data.get("models", {}).values():
|
||||
if not isinstance(block, dict):
|
||||
continue
|
||||
loras = block.get("loras")
|
||||
has_loras = isinstance(loras, list) and any(isinstance(lora, dict) and str(lora.get("name", "")).strip() for lora in loras)
|
||||
if str(block.get("positive_prompt", "")).strip() or str(block.get("model", "")).strip() or has_loras:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def normalize_workflow_loras(loras):
|
||||
"""Normalize workflow_data LoRA list to prompt-manager LoRA schema."""
|
||||
normalized = []
|
||||
if not isinstance(loras, list):
|
||||
return normalized
|
||||
for lora in loras:
|
||||
if not isinstance(lora, dict):
|
||||
continue
|
||||
name = str(lora.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
strength = lora.get("strength", lora.get("model_strength", 1.0))
|
||||
clip_strength = lora.get("clip_strength", strength)
|
||||
normalized.append({
|
||||
"name": name,
|
||||
"path": str(lora.get("path", name) or name),
|
||||
"strength": strength,
|
||||
"clip_strength": clip_strength,
|
||||
"active": lora.get("active", True),
|
||||
"available": bool(lora.get("available", True)),
|
||||
})
|
||||
return normalized
|
||||
|
||||
|
||||
def derive_prompt_fields(workflow_data):
|
||||
"""Derive prompt + LoRA compatibility fields from v2 workflow_data model blocks."""
|
||||
if not isinstance(workflow_data, dict):
|
||||
return {
|
||||
"prompt": "",
|
||||
"negative_prompt": "",
|
||||
"loras_a": [],
|
||||
"loras_b": [],
|
||||
"loras_c": [],
|
||||
"loras_d": [],
|
||||
"model_a": "",
|
||||
"model_b": "",
|
||||
"model_c": "",
|
||||
"model_d": "",
|
||||
}
|
||||
|
||||
wf_v2 = ensure_v2_recipe_data(workflow_data, source="PromptManagerAdvanced")
|
||||
wf_models = wf_v2.get("models", {}) if isinstance(wf_v2.get("models"), dict) else {}
|
||||
model_a_block = wf_models.get("model_a") if isinstance(wf_models.get("model_a"), dict) else {}
|
||||
model_b_block = wf_models.get("model_b") if isinstance(wf_models.get("model_b"), dict) else {}
|
||||
model_c_block = wf_models.get("model_c") if isinstance(wf_models.get("model_c"), dict) else {}
|
||||
model_d_block = wf_models.get("model_d") if isinstance(wf_models.get("model_d"), dict) else {}
|
||||
|
||||
return {
|
||||
"prompt": str(model_a_block.get("positive_prompt", "") or ""),
|
||||
"negative_prompt": str(model_a_block.get("negative_prompt", "") or ""),
|
||||
"loras_a": normalize_workflow_loras(model_a_block.get("loras", [])),
|
||||
"loras_b": normalize_workflow_loras(model_b_block.get("loras", [])),
|
||||
"loras_c": normalize_workflow_loras(model_c_block.get("loras", [])),
|
||||
"loras_d": normalize_workflow_loras(model_d_block.get("loras", [])),
|
||||
"model_a": str(model_a_block.get("model", "") or ""),
|
||||
"model_b": str(model_b_block.get("model", "") or ""),
|
||||
"model_c": str(model_c_block.get("model", "") or ""),
|
||||
"model_d": str(model_d_block.get("model", "") or ""),
|
||||
}
|
||||
|
||||
|
||||
MODEL_SLOT_KEYS = ("a", "b", "c", "d")
|
||||
LORA_MODE_PROMPT_ONLY = "Prompt LoRAs Only"
|
||||
LORA_MODE_COMBINE = "Combine LoRAs"
|
||||
LORA_MODE_INPUT_ONLY = "Input LoRAs Only"
|
||||
_PROMPT_COMPOSER_RECIPE_KEY = "prompt_composer"
|
||||
# Marks manager_data produced by Prompt Manager, next to "prompt_composer" and "prompt_layout".
|
||||
PROMPT_MANAGER_RECIPE_KEY = "prompt_manager"
|
||||
LORA_MODES = (
|
||||
LORA_MODE_PROMPT_ONLY,
|
||||
LORA_MODE_COMBINE,
|
||||
LORA_MODE_INPUT_ONLY,
|
||||
)
|
||||
|
||||
|
||||
def coerce_lora_stack(raw_stack):
|
||||
"""Normalize a LORA_STACK-like payload into list[(path, model, clip)]."""
|
||||
if raw_stack is None:
|
||||
return []
|
||||
|
||||
if isinstance(raw_stack, dict) and "__value__" in raw_stack:
|
||||
raw_stack = raw_stack.get("__value__")
|
||||
|
||||
if not isinstance(raw_stack, list):
|
||||
return []
|
||||
|
||||
out = []
|
||||
for item in raw_stack:
|
||||
if isinstance(item, (list, tuple)) and len(item) >= 1:
|
||||
path = str(item[0] or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item[1]) if len(item) >= 2 else 1.0
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item[2]) if len(item) >= 3 else model_strength
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
continue
|
||||
|
||||
if isinstance(item, dict):
|
||||
path = str(item.get("path") or item.get("name") or "").strip()
|
||||
if not path:
|
||||
continue
|
||||
try:
|
||||
model_strength = float(item.get("model_strength", item.get("strength", 1.0)))
|
||||
except Exception:
|
||||
model_strength = 1.0
|
||||
try:
|
||||
clip_strength = float(item.get("clip_strength", model_strength))
|
||||
except Exception:
|
||||
clip_strength = model_strength
|
||||
out.append((path, model_strength, clip_strength))
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def normalize_lora_slots(raw_input, primary_slot):
|
||||
"""Normalize one PMA input socket into 4 slots (A/B/C/D)."""
|
||||
slots = {k: [] for k in MODEL_SLOT_KEYS}
|
||||
|
||||
plain = coerce_lora_stack(raw_input)
|
||||
if plain:
|
||||
slots[primary_slot] = plain
|
||||
return slots
|
||||
|
||||
if not isinstance(raw_input, dict):
|
||||
return slots
|
||||
|
||||
for slot_key, suffix in (("model_a", "a"), ("model_b", "b"), ("model_c", "c"), ("model_d", "d")):
|
||||
candidate = None
|
||||
if slot_key in raw_input:
|
||||
candidate = raw_input.get(slot_key)
|
||||
elif suffix in raw_input:
|
||||
candidate = raw_input.get(suffix)
|
||||
slots[suffix] = coerce_lora_stack(candidate)
|
||||
|
||||
return slots
|
||||
|
||||
|
||||
def combine_lora_inputs(input_a, input_b):
|
||||
"""Combine PMA A/B sockets into a single multi-slot payload."""
|
||||
normalized_a = normalize_lora_slots(input_a, "a")
|
||||
normalized_b = normalize_lora_slots(input_b, "b")
|
||||
|
||||
out = {}
|
||||
for slot in MODEL_SLOT_KEYS:
|
||||
out[slot] = [*(normalized_a.get(slot) or []), *(normalized_b.get(slot) or [])]
|
||||
return out
|
||||
|
||||
|
||||
def flatten_lora_slots(multi_slots):
|
||||
flat = []
|
||||
if not isinstance(multi_slots, dict):
|
||||
return flat
|
||||
for slot in MODEL_SLOT_KEYS:
|
||||
flat.extend(coerce_lora_stack(multi_slots.get(slot)))
|
||||
return flat
|
||||
|
||||
|
||||
def _normalize_prompt_composer_input_loras(raw_loras):
|
||||
normalized = []
|
||||
for path, model_strength, clip_strength in coerce_lora_stack(raw_loras):
|
||||
normalized.append({
|
||||
"name": str(os.path.splitext(os.path.basename(normalize_path_separators(path)))[0] or "").strip(),
|
||||
"path": str(path or "").strip(),
|
||||
"model_strength": float(model_strength),
|
||||
"clip_strength": float(clip_strength),
|
||||
"active": True,
|
||||
"available": True,
|
||||
"source": "upstream",
|
||||
})
|
||||
return [entry for entry in normalized if entry.get("name")]
|
||||
|
||||
|
||||
def _prompt_composer_lora_key(item):
|
||||
raw_path = str(item.get("path", item.get("name", "")) or "").replace("\\", "/").strip().lower()
|
||||
leaf = os.path.basename(raw_path)
|
||||
stem, _ext = os.path.splitext(leaf)
|
||||
return stem or leaf
|
||||
|
||||
|
||||
def merge_prompt_composer_input_data(recipe_data, input_prompt="", prompt_enabled=False, input_lora_stack=None):
|
||||
if not isinstance(recipe_data, dict):
|
||||
return recipe_data
|
||||
|
||||
payload = recipe_data.get(_PROMPT_COMPOSER_RECIPE_KEY)
|
||||
if not isinstance(payload, dict):
|
||||
return recipe_data
|
||||
|
||||
input_data = payload.get("input_data") if isinstance(payload.get("input_data"), dict) else {}
|
||||
prompt_data = payload.get("prompt_data") if isinstance(payload.get("prompt_data"), dict) else {}
|
||||
existing_prompt = str(input_data.get("prompt", payload.get("input_prompt", "")) or "").strip()
|
||||
incoming_prompt = str(input_prompt or "").strip()
|
||||
merged_prompt = existing_prompt if existing_prompt else (incoming_prompt if prompt_enabled and incoming_prompt else "")
|
||||
|
||||
existing_loras = _normalize_prompt_composer_input_loras(
|
||||
input_data.get("lora_stack", payload.get("input_lora_stack", []))
|
||||
)
|
||||
added_loras = _normalize_prompt_composer_input_loras(input_lora_stack or []) if input_lora_stack is not None else []
|
||||
prompt_loras = _normalize_prompt_composer_input_loras(
|
||||
prompt_data.get("lora_stack", payload.get("prompt_lora_stack", []))
|
||||
)
|
||||
prompt_lora_keys = {
|
||||
_prompt_composer_lora_key(item)
|
||||
for item in prompt_loras
|
||||
if _prompt_composer_lora_key(item)
|
||||
}
|
||||
|
||||
merged_loras = []
|
||||
seen = set()
|
||||
for item in [*existing_loras, *added_loras]:
|
||||
key = _prompt_composer_lora_key(item)
|
||||
if not key:
|
||||
continue
|
||||
if key in prompt_lora_keys:
|
||||
continue
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
merged_loras.append(item)
|
||||
|
||||
payload["input_data"] = {
|
||||
**input_data,
|
||||
"source": "upstream",
|
||||
"prompt": merged_prompt,
|
||||
"lora_stack": merged_loras,
|
||||
}
|
||||
recipe_data[_PROMPT_COMPOSER_RECIPE_KEY] = payload
|
||||
return recipe_data
|
||||
@@ -0,0 +1,54 @@
|
||||
"""The prompt a Prompt Manager node output, written into the workflow and API prompt that save nodes embed, so a
|
||||
saved file carries it as typed text instead of a link to the node that fed it."""
|
||||
|
||||
|
||||
def get_workflow_node(extra_pnginfo, node_id):
|
||||
"""Find workflow node by id, including nested subgraphs (id chains like a:b:c)."""
|
||||
if not isinstance(extra_pnginfo, dict):
|
||||
return None
|
||||
|
||||
workflow = extra_pnginfo.get("workflow")
|
||||
if not isinstance(workflow, dict):
|
||||
return None
|
||||
|
||||
nodes_list = workflow.get("nodes", []) if isinstance(workflow.get("nodes"), list) else []
|
||||
subgraphs = []
|
||||
definitions = workflow.get("definitions")
|
||||
if isinstance(definitions, dict):
|
||||
maybe_subgraphs = definitions.get("subgraphs")
|
||||
if isinstance(maybe_subgraphs, list):
|
||||
subgraphs = maybe_subgraphs
|
||||
|
||||
found = None
|
||||
for part in str(node_id).split(":"):
|
||||
found = next((n for n in nodes_list if isinstance(n, dict) and str(n.get("id")) == part), None)
|
||||
if not isinstance(found, dict):
|
||||
return None
|
||||
|
||||
subgraph = next((sg for sg in subgraphs if isinstance(sg, dict) and str(sg.get("id")) == str(found.get("type"))), None)
|
||||
if isinstance(subgraph, dict) and isinstance(subgraph.get("nodes"), list):
|
||||
nodes_list = subgraph.get("nodes", [])
|
||||
|
||||
return found
|
||||
|
||||
|
||||
def record_prompt(unique_id, text, extra_pnginfo, api_prompt, toggle, link_input, text_index):
|
||||
"""Store `text` as the node's typed prompt with its input `toggle` off (widget 2) and drop the `link_input` link:
|
||||
`text_index` is the text widget's position in widgets_values."""
|
||||
node_id = str(unique_id) if unique_id is not None else ""
|
||||
if not node_id:
|
||||
return
|
||||
|
||||
workflow_node = get_workflow_node(extra_pnginfo, node_id)
|
||||
widgets = workflow_node.get("widgets_values") if isinstance(workflow_node, dict) else None
|
||||
if isinstance(widgets, list):
|
||||
if len(widgets) > 2:
|
||||
widgets[2] = False
|
||||
if len(widgets) > text_index:
|
||||
widgets[text_index] = text
|
||||
|
||||
inputs = api_prompt.get(node_id, {}).get("inputs") if isinstance(api_prompt, dict) else None
|
||||
if isinstance(inputs, dict):
|
||||
inputs[toggle] = False
|
||||
inputs["text"] = text
|
||||
inputs.pop(link_input, None)
|
||||
@@ -0,0 +1,48 @@
|
||||
"""The prompt library the Prompt Manager nodes share: user/default/prompt_manager_data.json, seeded from
|
||||
prompts/default_prompts.json the first time. Backups are made once a day at startup (backup_manager.check_backup)."""
|
||||
|
||||
import json
|
||||
import os
|
||||
|
||||
import folder_paths
|
||||
|
||||
from .backup_manager import atomic_save, load_with_fallback
|
||||
|
||||
DEFAULT_PROMPTS_PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "prompts", "default_prompts.json")
|
||||
|
||||
# Category entries that are not prompts: the category's metadata, and its base prompt and prompt prefix.
|
||||
HIDDEN_KEYS = {"__meta__", "_base_prompt_", "_prompt_prefix_"}
|
||||
|
||||
|
||||
def is_hidden_key(name):
|
||||
return str(name or "").strip().lower() in HIDDEN_KEYS
|
||||
|
||||
|
||||
def prompts_path():
|
||||
return os.path.join(folder_paths.get_user_directory(), "default", "prompt_manager_data.json")
|
||||
|
||||
|
||||
def load_prompts():
|
||||
"""The library; the default prompts when there is no library yet. An unreadable file with no readable backup
|
||||
loads as empty, never overwritten here."""
|
||||
data = load_with_fallback(prompts_path(), "PromptManager")
|
||||
if data is not None:
|
||||
return data
|
||||
if os.path.exists(prompts_path()):
|
||||
return {}
|
||||
with open(DEFAULT_PROMPTS_PATH, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
save_prompts(data)
|
||||
return data
|
||||
|
||||
|
||||
def save_prompts(data):
|
||||
"""Save with categories and their prompts sorted case-insensitively, a category's __meta__ last."""
|
||||
sorted_data = {}
|
||||
for category in sorted(data, key=str.lower):
|
||||
entries = data[category]
|
||||
sorted_entries = dict(sorted(((k, v) for k, v in entries.items() if k != "__meta__"), key=lambda item: item[0].lower()))
|
||||
if "__meta__" in entries:
|
||||
sorted_entries["__meta__"] = entries["__meta__"]
|
||||
sorted_data[category] = sorted_entries
|
||||
atomic_save(prompts_path(), sorted_data, "PromptManager")
|
||||
@@ -0,0 +1,41 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
if "%~1"=="" (
|
||||
echo Usage: Drag and drop a video file onto this BAT.
|
||||
echo.
|
||||
echo This will create a JSON file next to the video.
|
||||
pause
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
set "VIDEO=%~1"
|
||||
set "OUT=%~dp1%~n1.json"
|
||||
set "SCRIPT_DIR=%~dp0"
|
||||
set "SCRIPT=%SCRIPT_DIR%extract_video_workflow.py"
|
||||
|
||||
if not exist "%SCRIPT%" (
|
||||
echo Error: Python script not found:
|
||||
echo %SCRIPT%
|
||||
pause
|
||||
exit /b 2
|
||||
)
|
||||
|
||||
echo Extracting workflow...
|
||||
echo Input : %VIDEO%
|
||||
echo Output: %OUT%
|
||||
echo.
|
||||
|
||||
py "%SCRIPT%" "%VIDEO%" --out "%OUT%"
|
||||
if errorlevel 1 (
|
||||
echo.
|
||||
echo Extraction failed.
|
||||
pause
|
||||
exit /b 3
|
||||
)
|
||||
|
||||
echo.
|
||||
echo Done. Workflow saved to:
|
||||
echo %OUT%
|
||||
pause
|
||||
exit /b 0
|
||||
@@ -0,0 +1,135 @@
|
||||
"""
|
||||
Extract embedded ComfyUI workflow JSON from a video file.
|
||||
|
||||
Usage:
|
||||
python extract_video_workflow.py <video_path>
|
||||
python extract_video_workflow.py <video_path> --out workflow.json
|
||||
|
||||
Notes:
|
||||
- Accepts only true workflow payloads (full Comfy workflow JSON).
|
||||
- Ignores prompt-only metadata payloads.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def _run_ffprobe(video_path: Path) -> dict:
|
||||
"""Return ffprobe JSON for format metadata."""
|
||||
cmd = [
|
||||
"ffprobe",
|
||||
"-v",
|
||||
"quiet",
|
||||
"-print_format",
|
||||
"json",
|
||||
"-show_format",
|
||||
str(video_path),
|
||||
]
|
||||
|
||||
result = subprocess.run(cmd, capture_output=True, text=True)
|
||||
|
||||
if result.returncode != 0:
|
||||
err = result.stderr.strip() or "ffprobe failed"
|
||||
raise RuntimeError(err)
|
||||
|
||||
try:
|
||||
return json.loads(result.stdout)
|
||||
except json.JSONDecodeError as e:
|
||||
raise RuntimeError(f"ffprobe returned invalid JSON: {e}") from e
|
||||
|
||||
|
||||
def _json_load_maybe(value):
|
||||
"""Parse JSON string if possible, otherwise return the input unchanged."""
|
||||
if not isinstance(value, str):
|
||||
return value
|
||||
try:
|
||||
return json.loads(value)
|
||||
except json.JSONDecodeError:
|
||||
return value
|
||||
|
||||
|
||||
def _is_valid_workflow_dict(data):
|
||||
"""Strict workflow check: reject prompt-only/API graph payloads."""
|
||||
if not isinstance(data, dict):
|
||||
return False
|
||||
|
||||
if isinstance(data.get("nodes"), list) and isinstance(data.get("links"), list):
|
||||
return True
|
||||
if isinstance(data.get("nodes"), list) and "last_node_id" in data:
|
||||
return True
|
||||
|
||||
wrapped = data.get("workflow")
|
||||
if isinstance(wrapped, dict):
|
||||
return _is_valid_workflow_dict(wrapped)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def extract_workflow(video_path: Path):
|
||||
"""Extract true workflow object from Comfy video metadata payload."""
|
||||
ffprobe_data = _run_ffprobe(video_path)
|
||||
tags = ffprobe_data.get("format", {}).get("tags", {})
|
||||
|
||||
# Preferred: direct workflow tag.
|
||||
workflow = _json_load_maybe(tags.get("workflow"))
|
||||
if _is_valid_workflow_dict(workflow):
|
||||
return workflow
|
||||
|
||||
# Fallback: workflow nested in comment JSON payload.
|
||||
comment = _json_load_maybe(tags.get("comment"))
|
||||
if isinstance(comment, dict):
|
||||
workflow = _json_load_maybe(comment.get("workflow"))
|
||||
if _is_valid_workflow_dict(workflow):
|
||||
return workflow
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Extract embedded ComfyUI workflow JSON from a video file"
|
||||
)
|
||||
parser.add_argument("video_path", help="Path to the video file")
|
||||
parser.add_argument(
|
||||
"--out",
|
||||
dest="output_path",
|
||||
default=None,
|
||||
help="Optional path to save extracted workflow JSON",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
video_path = Path(args.video_path)
|
||||
if not video_path.exists() or not video_path.is_file():
|
||||
print(f"Error: file not found: {video_path}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
try:
|
||||
workflow = extract_workflow(video_path)
|
||||
except FileNotFoundError:
|
||||
print("Error: ffprobe is not installed or not in PATH.", file=sys.stderr)
|
||||
return 2
|
||||
except Exception as e:
|
||||
print(f"Error: {e}", file=sys.stderr)
|
||||
return 3
|
||||
|
||||
if workflow is None:
|
||||
print("No embedded workflow metadata found.", file=sys.stderr)
|
||||
return 4
|
||||
|
||||
output_json = json.dumps(workflow, indent=2, ensure_ascii=False)
|
||||
|
||||
if args.output_path:
|
||||
output_path = Path(args.output_path)
|
||||
output_path.write_text(output_json, encoding="utf-8")
|
||||
print(f"Workflow extracted to: {output_path}")
|
||||
else:
|
||||
print(output_json)
|
||||
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user