import { app } from "../../scripts/app.js"; const NODE_NAME = "ManualRefCollage"; const IMAGE_COLORS = ["#4f9cff", "#ff5c5c", "#4fd36f", "#ff5cff", "#44e7e7"]; const DEFAULT_PROMPT = "person"; const DEFAULT_WIDTH = 1280; const DEFAULT_HEIGHT = 1280; const DEFAULT_BG = "black"; const DEFAULT_OPACITY = 0.3; const MAX_STAGE_SIZE = 512; const MIN_NODE_WIDTH = 420; const MIN_NODE_HEIGHT = 260; const MIN_DOM_HEIGHT = 48; const INACTIVE_NODE_MODES = new Set([2, 4]); const MEDIA_EXTENSIONS = [".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".mp4", ".mov", ".m4v", ".avi", ".webm", ".mkv"]; const HELP_ICON_SIZE = 14; const HELP_ICON_MARGIN = 4; const CSS = ` .fh-manual-collage { position: relative; width: 100%; height: 100%; box-sizing: border-box; display: flex; flex-direction: column; gap: 3px; padding: 3px 3px 12px; color: var(--fg-color, var(--input-text, #ddd)); user-select: none; pointer-events: none; overflow: visible; } .fh-manual-collage > * { pointer-events: auto; } .fh-prompt { width: 100%; min-height: 56px; max-height: 88px; resize: vertical; box-sizing: border-box; border: 1px solid var(--border-color, var(--border, #555)); border-radius: 8px; padding: 8px 10px; background: var(--comfy-input-bg, var(--input-bg, #222)); color: var(--input-text, var(--fg-color, #ddd)); outline: none; font: inherit; } .fh-load-row, .fh-size-row { display: flex; flex-wrap: wrap; gap: 3px; align-items: stretch; width: 100%; } .fh-btn { appearance: none; cursor: pointer; font: 12px sans-serif; line-height: 1.2; min-width: 0; min-height: 24px; padding: 4px 10px; color: var(--input-text, var(--fg-color, #ddd)); background: var(--comfy-input-bg, var(--input-bg, #222)); border: 1px solid var(--border-color, var(--border, #555)); border-radius: 3px; box-sizing: border-box; display: inline-flex; align-items: center; justify-content: center; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); } .fh-btn:hover:not(:disabled) { background: color-mix(in srgb, var(--comfy-input-bg, var(--input-bg, #222)) 88%, white 12%); } .fh-btn:active:not(:disabled) { transform: translateY(0.5px); } .fh-btn:disabled { opacity: 0.55; cursor: default; } .fh-native-widget-host { flex: 1 1 0; min-width: 0; } .fh-load-btn { width: 100%; min-height: 26px; } .fh-body { flex: 1 1 auto; min-height: 0; display: flex; align-items: stretch; } .fh-stage-pane { flex: 1 1 auto; min-width: 0; min-height: 0; display: flex; flex-direction: column; gap: 0; } .fh-stage-viewport { flex: 1 1 auto; min-height: 120px; min-width: 0; display: flex; align-items: center; justify-content: center; overflow: hidden; padding: 0 1px 1px; box-sizing: border-box; pointer-events: auto; } .fh-stage { position: relative; overflow: hidden; border: 1px solid var(--border-color, var(--border, #555)); border-radius: 8px; background: #000; box-sizing: border-box; } .fh-stage.white { background: #fff; } .fh-stage-bg { position: absolute; inset: 0; pointer-events: none; } .fh-stage-bg.hidden { display: none; } .fh-stage-bg img { display: block; width: 100%; height: 100%; object-fit: fill; } .fh-items { position: absolute; inset: 0; pointer-events: none; contain: layout style paint; } .fh-empty { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--fg-color, #999); font-size: 13px; pointer-events: none; } .fh-stage.white .fh-empty { color: #444; } .fh-item { position: absolute; transform: translate(-50%, -50%); transform-origin: center center; box-sizing: border-box; will-change: left, top, width, height; pointer-events: auto; } .fh-item img { display: block; width: 100%; height: 100%; object-fit: contain; pointer-events: none; user-select: none; } .fh-item-box { position: absolute; inset: 0; border: 2px solid var(--fh-color); box-sizing: border-box; pointer-events: none; } .fh-item-label { position: absolute; top: -18px; left: 0; color: var(--fh-color); font: 13px/1 sans-serif; white-space: nowrap; text-shadow: 0 1px 1px #000; pointer-events: none; } .fh-stage.white .fh-item-label { text-shadow: 0 1px 1px #fff; } .fh-overlay { position: absolute; inset: 0; pointer-events: none; } .fh-selection-box { position: absolute; box-sizing: border-box; border: 2px solid var(--fh-color, #fff); box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); cursor: move; pointer-events: auto; } .fh-selection-label { position: absolute; top: -18px; left: 0; color: var(--fh-color, #fff); font: 13px/1 sans-serif; white-space: nowrap; text-shadow: 0 1px 1px #000; pointer-events: none; } .fh-stage.white .fh-selection-label { text-shadow: 0 1px 1px #fff; } .fh-selection-handle { position: absolute; width: 10px; height: 10px; border-radius: 2px; background: var(--comfy-input-bg, #222); border: 2px solid var(--fh-color, #fff); box-sizing: border-box; pointer-events: auto; } .fh-selection-handle.tl { left: -6px; top: -6px; cursor: nwse-resize; } .fh-selection-handle.tr { right: -6px; top: -6px; cursor: nesw-resize; } .fh-selection-handle.bl { left: -6px; bottom: -6px; cursor: nesw-resize; } .fh-selection-handle.br { right: -6px; bottom: -6px; cursor: nwse-resize; } .fh-apply-btn, .fh-reset-btn, .fh-bg-btn { flex: 1 1 0; min-height: 26px; } .fh-help-panel { position: fixed; z-index: 115; width: 260px; padding: 10px 12px; display: none; line-height: 1.45; text-align: left; pointer-events: auto; } .fh-help-title { font-weight: 600; margin-bottom: 6px; } .fh-help-item { margin: 0 0 6px; } `; function ensureStyle() { if (document.getElementById("fh-manual-collage-style")) return; const style = document.createElement("style"); style.id = "fh-manual-collage-style"; style.textContent = CSS; document.head.appendChild(style); } function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } function num(value, fallback) { const n = Number(value); return Number.isFinite(n) ? n : fallback; } function looksLikeMediaName(value) { if (typeof value !== "string") return false; const stripped = value.trim().toLowerCase(); if (!stripped) return false; return MEDIA_EXTENSIONS.some((ext) => stripped.endsWith(ext) || stripped.includes(`${ext} `) || stripped.includes(`${ext}[`) || stripped.includes(`${ext}?`)); } function hexToRgb(hex) { if (!hex || typeof hex !== "string") return null; const clean = hex.trim().replace(/^#/, ""); if (/^[0-9a-fA-F]{3}$/.test(clean)) { return { r: parseInt(clean[0] + clean[0], 16), g: parseInt(clean[1] + clean[1], 16), b: parseInt(clean[2] + clean[2], 16), }; } if (/^[0-9a-fA-F]{6}$/.test(clean)) { return { r: parseInt(clean.slice(0, 2), 16), g: parseInt(clean.slice(2, 4), 16), b: parseInt(clean.slice(4, 6), 16), }; } return null; } function rgba(hex, alpha) { const rgb = hexToRgb(hex); if (!rgb) return `rgba(255,255,255,${alpha})`; return `rgba(${rgb.r},${rgb.g},${rgb.b},${alpha})`; } function makeDefaultItems(count, width, height) { if (count <= 0) return []; const minScale = Math.min(width / Math.max(1, height), height / Math.max(1, width)); const scale = Math.max(0.2, Math.min(0.55, 0.38 * minScale + 0.14)); return Array.from({ length: count }, (_, index) => ({ x: (index + 0.5) / count, y: 0.72, scale, z: count - index, })); } function parseLayout(layoutJson, count, width, height, background, options = {}) { let layout = {}; if (typeof layoutJson === "string" && layoutJson.trim()) { try { const parsed = JSON.parse(layoutJson); if (parsed && typeof parsed === "object") layout = parsed; } catch { layout = {}; } } const useLayoutWidth = options.useLayoutWidth ?? options.useLayoutSize ?? true; const useLayoutHeight = options.useLayoutHeight ?? options.useLayoutSize ?? true; const outWidth = clamp(Math.round(num(useLayoutWidth ? layout.width : undefined, width)), 64, 8192); const outHeight = clamp(Math.round(num(useLayoutHeight ? layout.height : undefined, height)), 64, 8192); const outBg = String(layout.background || background || DEFAULT_BG).toLowerCase() === "white" ? "white" : "black"; const defaults = makeDefaultItems(count, outWidth, outHeight); const rawItems = Array.isArray(layout.items) ? layout.items : []; const items = defaults.map((fallback, index) => { const item = rawItems[index] && typeof rawItems[index] === "object" ? rawItems[index] : {}; return { x: clamp(num(item.x, fallback.x), -1, 2), y: clamp(num(item.y, fallback.y), -1, 2), scale: clamp(num(item.scale, fallback.scale), 0.02, 4), z: Number.isFinite(Number(item.z)) ? Number(item.z) : fallback.z, }; }); return { width: outWidth, height: outHeight, background: outBg, items }; } function syncWidgetValue(state, widget, value) { if (!widget) return; state.syncing = true; widget.value = value; if (typeof widget.callback === "function") widget.callback.call(widget, value); state.syncing = false; } function setHiddenWidget(widget) { if (!widget) return; widget.hidden = true; widget.computeSize = () => [0, -4]; } function findWidget(node, name) { return node.widgets?.find((widget) => widget && widget.name === name) || null; } function hasLinkedInput(node, inputName) { const input = node.inputs?.find((slot) => slot && slot.name === inputName); return !!input?.link; } function getLinkedSourceNode(node, inputName) { const input = node.inputs?.find((slot) => slot && slot.name === inputName); if (!input?.link) return null; const link = app.graph?.links?.[input.link]; if (!link) return null; return app.graph?.getNodeById?.(link.origin_id) || null; } function isNodeActive(node) { if (!node) return false; return !INACTIVE_NODE_MODES.has(Number(node.mode)); } function isLinkedInputActive(node, inputName) { const input = node.inputs?.find((slot) => slot && slot.name === inputName); if (!input?.link) return false; return isNodeActive(getLinkedSourceNode(node, inputName)); } function getLinkedMediaName(node, inputName, visited = new Set()) { const source = getLinkedSourceNode(node, inputName); if (!source || !isNodeActive(source)) return ""; const sourceId = String(source.id); if (visited.has(sourceId)) return ""; visited.add(sourceId); const preferredNames = ["image", "video", "upload", "filename", "file", "path", "image_name", "video_file", "media"]; const widgetValues = source.widgets || []; for (const widget of widgetValues) { const name = String(widget?.name || "").toLowerCase(); if (preferredNames.includes(name) && looksLikeMediaName(widget?.value)) { return String(widget.value); } } for (const widget of widgetValues) { if (looksLikeMediaName(widget?.value)) { return String(widget.value); } } for (const upstream of source.inputs || []) { if (!upstream?.name) continue; const resolved = getLinkedMediaName(source, upstream.name, visited); if (resolved) return resolved; } return ""; } function numericFromValue(value, preferredNames = []) { if (value == null || typeof value === "boolean") return null; if (typeof value === "number") return Number.isFinite(value) ? value : null; if (typeof value === "string") { const parsed = Number(value.trim()); return Number.isFinite(parsed) ? parsed : null; } if (Array.isArray(value)) { for (const item of value) { const found = numericFromValue(item, preferredNames); if (found != null) return found; } return null; } if (typeof value === "object") { for (const name of preferredNames) { if (Object.prototype.hasOwnProperty.call(value, name)) { const found = numericFromValue(value[name], preferredNames); if (found != null) return found; } } if (Object.prototype.hasOwnProperty.call(value, "value")) { const found = numericFromValue(value.value, preferredNames); if (found != null) return found; } for (const item of Object.values(value)) { const found = numericFromValue(item, preferredNames); if (found != null) return found; } } return null; } function numericNamesForInput(inputName) { if (inputName === "width") return ["width", "w", "value", "number", "int", "integer", "宽度", "宽"]; if (inputName === "height") return ["height", "h", "value", "number", "int", "integer", "高度", "高"]; return ["value", inputName, "number", "int", "integer"]; } function getGraphNodes() { const graph = app.graph; if (!graph) return []; if (Array.isArray(graph._nodes)) return graph._nodes; if (Array.isArray(graph.nodes)) return graph.nodes; return []; } function normalizedVariableKey(value) { if (value == null) return ""; return String(value) .trim() .replace(/^(get|set|获取|读取|设置|写入)[\s_:\-:]*/i, "") .replace(/[\s_:\-:]+/g, "") .toLowerCase(); } function pushVariableKey(keys, value) { const key = normalizedVariableKey(value); if (key && !keys.includes(key)) keys.push(key); } function variableModeMatches(value, mode) { if (!mode) return true; const normalized = String(value || "").toLowerCase(); if (mode === "get") return ["get", "获取", "读取"].includes(normalized); if (mode === "set") return ["set", "设置", "写入"].includes(normalized); return normalized === mode; } function collectVariableKeysFromNode(node, mode = "") { const keys = []; const namedFields = new Set([ "key", "name", "variable", "variable_name", "var_name", "id", "label", "text", "string", "value", "变量", "变量名", "名称", "名字", ]); const titles = [node?.title, node?.type, node?.comfyClass, node?.constructor?.type]; for (const value of titles) { if (typeof value !== "string") continue; const match = value.match(/(?:^|[\s_:\-:])(get|set)[\s_:\-:]+(.+)$/i) || value.match(/(?:^|[\s_:\-:])(获取|读取|设置|写入)[\s_:\-:]*(.+)$/i); if (match && variableModeMatches(match[1], mode)) { pushVariableKey(keys, match[2]); } } for (const widget of node?.widgets || []) { const name = String(widget?.name || "").toLowerCase(); if (namedFields.has(name)) { pushVariableKey(keys, widget?.value ?? widget?.inputEl?.value); } } for (const [name, value] of Object.entries(node?.properties || {})) { if (namedFields.has(String(name).toLowerCase())) { pushVariableKey(keys, value); } } return keys; } function nodeLooksLikeVariableNode(node, mode) { const marker = mode === "set" ? /(^|[\s_:\-:])(set|设置|写入)([\s_:\-:]|$)/i : /(^|[\s_:\-:])(get|获取|读取)([\s_:\-:]|$)/i; return [node?.title, node?.type, node?.comfyClass, node?.constructor?.type] .some((value) => typeof value === "string" && marker.test(value)); } function getNodeOwnNumericValue(source, wantedName, preferredOnly = false) { const preferredNames = numericNamesForInput(wantedName); for (const widget of source.widgets || []) { const widgetName = String(widget?.name || "").toLowerCase(); if (!preferredNames.includes(widgetName)) continue; const found = numericFromValue(widget?.value ?? widget?.inputEl?.value, preferredNames); if (found != null) return found; } if (preferredOnly) return null; for (const widget of source.widgets || []) { const found = numericFromValue(widget?.value ?? widget?.inputEl?.value, preferredNames); if (found != null) return found; } for (const container of [source.widgets_values, source.properties]) { const found = numericFromValue(container, preferredNames); if (found != null) return found; } return null; } function getLinkedInputNumericValue(source, wantedName, visited = new Set()) { const inputs = [...(source?.inputs || [])].filter((slot) => slot?.name && slot?.link); const preferredNames = numericNamesForInput(wantedName); inputs.sort((a, b) => { const aName = String(a.name || "").toLowerCase(); const bName = String(b.name || "").toLowerCase(); const aScore = preferredNames.includes(aName) ? 0 : aName === "value" ? 1 : 2; const bScore = preferredNames.includes(bName) ? 0 : bName === "value" ? 1 : 2; return aScore - bScore; }); for (const upstream of inputs) { const found = getLinkedNumericValue(source, upstream.name, wantedName, visited); if (found != null) return found; } return null; } function getVariableSetNumericValue(getNode, wantedName, visited = new Set()) { if (!nodeLooksLikeVariableNode(getNode, "get")) return null; const getKeys = collectVariableKeysFromNode(getNode, "get"); if (!getKeys.length) return null; for (const candidate of getGraphNodes()) { if (!candidate || candidate === getNode || !isNodeActive(candidate)) continue; if (!nodeLooksLikeVariableNode(candidate, "set")) continue; const setKeys = collectVariableKeysFromNode(candidate, "set"); if (!setKeys.some((key) => getKeys.includes(key))) continue; const localVisited = new Set(visited); const candidateId = String(candidate.id ?? ""); if (candidateId && localVisited.has(candidateId)) continue; if (candidateId) localVisited.add(candidateId); const linked = getLinkedInputNumericValue(candidate, wantedName, localVisited); if (linked != null) return linked; const own = getNodeOwnNumericValue(candidate, wantedName); if (own != null) return own; } return null; } function getNodeNumericValue(source, wantedName, visited = new Set()) { if (!source || !isNodeActive(source)) return null; const sourceId = String(source.id ?? ""); if (sourceId && visited.has(sourceId)) return null; if (sourceId) visited.add(sourceId); const ownPreferred = getNodeOwnNumericValue(source, wantedName, true); if (ownPreferred != null) return ownPreferred; const variableValue = getVariableSetNumericValue(source, wantedName, visited); if (variableValue != null) return variableValue; const own = getNodeOwnNumericValue(source, wantedName); if (own != null) return own; for (const upstream of source.inputs || []) { if (!upstream?.name) continue; const found = getLinkedNumericValue(source, upstream.name, wantedName, visited); if (found != null) return found; } return null; } function getLinkedNumericValue(node, inputName, wantedName = inputName, visited = new Set()) { const source = getLinkedSourceNode(node, inputName); if (!source) return null; return getNodeNumericValue(source, wantedName, visited); } function readNumericInputValue(node, inputName, widget, fallback) { if (hasLinkedInput(node, inputName)) { const linked = getLinkedNumericValue(node, inputName); if (linked != null) return clamp(Math.round(linked), 64, 8192); } return clamp(Math.round(num(widget?.value, fallback)), 64, 8192); } function createButton(text, className = "") { const button = document.createElement("button"); button.type = "button"; button.className = `fh-btn ${className}`.trim(); button.textContent = text; return button; } function computeNodeDomHeight(node, size) { const baseHeight = size?.[1] || node?.size?.[1] || MIN_NODE_HEIGHT; const widgetY = node?._fhDomWidget?.last_y; const offset = widgetY != null ? widgetY + 10 : 220; return Math.max(MIN_DOM_HEIGHT, Math.round(baseHeight - offset)); } function clampNodeSize(node, size) { if (!node) return size || [MIN_NODE_WIDTH, MIN_NODE_HEIGHT]; const minSize = node._fhMinSize || [MIN_NODE_WIDTH, MIN_NODE_HEIGHT]; const target = size || node.size || [MIN_NODE_WIDTH, MIN_NODE_HEIGHT]; const width = Math.max(target[0] || MIN_NODE_WIDTH, minSize[0] || MIN_NODE_WIDTH); const height = Math.max(target[1] || MIN_NODE_HEIGHT, minSize[1] || MIN_NODE_HEIGHT); if (size) { size[0] = width; size[1] = height; } if (node.size) { node.size[0] = width; node.size[1] = height; } return [width, height]; } function applyNodeDomHeight(node, size) { if (!node?._fhDomWidget?.element) return; const nextSize = clampNodeSize(node, size || node.size); const domHeight = computeNodeDomHeight(node, nextSize); if (node._fhDomHeight !== domHeight) { node._fhDomHeight = domHeight; node._fhDomWidget.element.style.height = `${domHeight}px`; } else if (!node._fhDomWidget.element.style.height) { node._fhDomWidget.element.style.height = `${domHeight}px`; } } function buildManualUI(node) { ensureStyle(); const layoutWidget = findWidget(node, "layout_json"); const promptWidget = findWidget(node, "prompt"); const widthWidget = findWidget(node, "width"); const heightWidget = findWidget(node, "height"); const backgroundWidget = findWidget(node, "background"); const thresholdWidget = findWidget(node, "detection_threshold"); const opacityWidget = findWidget(node, "background_opacity"); for (const widget of [layoutWidget, promptWidget, backgroundWidget, thresholdWidget]) { setHiddenWidget(widget); } const initialWidth = clamp(Math.round(num(widthWidget?.value, DEFAULT_WIDTH)), 64, 8192); const initialHeight = clamp(Math.round(num(heightWidget?.value, DEFAULT_HEIGHT)), 64, 8192); const initial = parseLayout( layoutWidget?.value || "", 5, initialWidth, initialHeight, backgroundWidget?.value || DEFAULT_BG, ); const state = { syncing: false, prompt: String(promptWidget?.value || DEFAULT_PROMPT), width: initial.width, height: initial.height, pendingWidth: initial.width, pendingHeight: initial.height, background: initial.background, initialBackground: initial.background, backgroundOpacity: clamp(num(opacityWidget?.value, DEFAULT_OPACITY), 0, 1), selected: 0, images: ["", "", "", "", ""], imageMeta: [null, null, null, null, null], backgroundPreview: "", items: initial.items.map((item) => ({ ...item })), stageScale: 1, stageW: 1, stageH: 1, loading: false, renderQueued: false, transformQueued: false, helpVisible: false, }; const root = document.createElement("div"); root.className = "fh-manual-collage"; const prompt = document.createElement("textarea"); prompt.className = "fh-prompt"; prompt.spellcheck = false; prompt.value = state.prompt; const loadRow = document.createElement("div"); loadRow.className = "fh-load-row"; const loadBtn = createButton("载入图片", "fh-load-btn"); loadRow.append(loadBtn); const body = document.createElement("div"); body.className = "fh-body"; const stagePane = document.createElement("div"); stagePane.className = "fh-stage-pane"; const stageViewport = document.createElement("div"); stageViewport.className = "fh-stage-viewport"; const stage = document.createElement("div"); stage.className = "fh-stage"; const backgroundLayer = document.createElement("div"); backgroundLayer.className = "fh-stage-bg hidden"; const backgroundImage = document.createElement("img"); backgroundImage.alt = "video_frame"; backgroundLayer.appendChild(backgroundImage); const itemsLayer = document.createElement("div"); itemsLayer.className = "fh-items"; const overlay = document.createElement("div"); overlay.className = "fh-overlay"; const selectionBox = document.createElement("div"); selectionBox.className = "fh-selection-box"; selectionBox.style.display = "none"; const selectionLabel = document.createElement("div"); selectionLabel.className = "fh-selection-label"; selectionBox.appendChild(selectionLabel); for (const pos of ["tl", "tr", "bl", "br"]) { const handle = document.createElement("div"); handle.className = `fh-selection-handle ${pos}`; handle.dataset.handle = pos; selectionBox.appendChild(handle); } overlay.appendChild(selectionBox); const empty = document.createElement("div"); empty.className = "fh-empty"; empty.textContent = "点击载入图片"; stage.append(backgroundLayer, itemsLayer, overlay, empty); stageViewport.appendChild(stage); stagePane.append(stageViewport); body.appendChild(stagePane); const sizeRow = document.createElement("div"); sizeRow.className = "fh-size-row"; const widthHost = document.createElement("div"); widthHost.className = "fh-native-widget-host"; const heightHost = document.createElement("div"); heightHost.className = "fh-native-widget-host"; const opacityHost = document.createElement("div"); opacityHost.className = "fh-native-widget-host"; sizeRow.append(widthHost, heightHost, opacityHost); const actionRow = document.createElement("div"); actionRow.className = "fh-size-row"; const applyBtn = createButton("应用尺寸", "fh-apply-btn"); const resetBtn = createButton("重置排版", "fh-reset-btn"); const bgBtn = createButton("背景切换", "fh-bg-btn"); actionRow.append(applyBtn, resetBtn, bgBtn); const helpText = document.createElement("div"); helpText.className = "comfy-menu fh-help-panel"; helpText.innerHTML = [ '