Files
DumasNodes/js/dumas_resolution.js
T

210 lines
16 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { app } from "/scripts/app.js";
const CLASS = "DumasResolution";
const STATE_PROP = "dumasResolutionState";
const HIDDEN = "ResolutionState";
const DEFAULT = {
mode: "preset", ratio: "1:1", w: 1024, h: 1024,
custom_w: 1024, custom_h: 1024, custom_ratio_w: 4, custom_ratio_h: 3,
snap: 16, batch: 1,
};
const SIZES = {
"1:1": [[512,512],[768,768],[1024,1024],[1280,1280],[1328,1328],[1408,1408],[1536,1536],[2048,2048]],
"16:9": [[832,480],[1280,720],[1344,768],[1536,864],[1600,896],[1664,928],[1792,1008],[1920,1088]],
"9:16": [[480,832],[720,1280],[768,1344],[864,1536],[896,1600],[928,1664],[1008,1792],[1088,1920]],
"2:1": [[512,256],[1024,512],[1280,640],[1536,768],[1600,800],[1792,896],[1920,960],[2048,1024]],
"3:2": [[768,512],[1024,680],[1152,768],[1344,896],[1536,1024],[1632,1088],[1728,1152],[1920,1280]],
"2:3": [[512,768],[680,1024],[768,1152],[896,1344],[1024,1536],[1088,1632],[1152,1728],[1280,1920]],
"4:3": [[512,384],[640,480],[768,576],[1024,768],[1280,960],[1408,1056],[1600,1200],[1920,1440]],
"3:4": [[384,512],[480,640],[576,768],[768,1024],[960,1280],[1056,1408],[1200,1600],[1440,1920]],
"4:5": [[512,640],[640,800],[768,960],[832,1040],[1024,1280],[1152,1440],[1280,1600],[1536,1920]],
};
const DEFAULT_SIZE = {"1:1":[1024,1024],"16:9":[1280,720],"9:16":[720,1280],"2:1":[1280,640],"3:2":[1152,768],"2:3":[768,1152],"4:3":[1024,768],"3:4":[768,1024],"4:5":[1024,1280]};
const RATIOS = Object.keys(SIZES);
const clamp = (n) => Math.max(64, Math.min(4096, Number(n) || 1024));
const snap = (n, step) => Math.round(n / step) * step;
const gcd = (a, b) => { while (b) [a, b] = [b, a % b]; return a || 1; };
function read(node) {
const raw = node.properties?.[STATE_PROP];
if (raw) { try { return {...DEFAULT, ...JSON.parse(raw)}; } catch {} }
return {...DEFAULT};
}
function write(node, value) {
node.properties ||= {};
node.properties[STATE_PROP] = JSON.stringify({...DEFAULT, ...value});
node.setDirtyCanvas?.(true, true);
}
function ratioPair(raw, rw, rh, step) {
let w = snap(clamp(raw), step);
let h = snap(w * rh / rw, step);
if (h > 4096) { h = 4096 - (4096 % step); w = snap(h * rw / rh, step); }
if (h < 64) { h = step; w = snap(h * rw / rh, step); }
return [clamp(w), clamp(h)];
}
function stateText(node) { return JSON.stringify(read(node)); }
function collectNodes(graph, output = []) {
if (!graph) return output;
for (const node of graph._nodes || graph.nodes || []) {
if (node) output.push(node);
const inner = node?.subgraph || node?.graph || node?._graph;
if (inner && inner !== graph) collectNodes(inner, output);
}
return output;
}
function injectState(result, nodes) {
for (const id in result?.output || {}) {
const entry = result.output[id];
if (entry?.class_type !== CLASS) continue;
const node = nodes.find((n) => String(n.id) === String(id) || String(n.id) === String(id).split(":").pop());
entry.inputs ||= {};
entry.inputs[HIDDEN] = stateText(node || {properties: {}});
}
}
const style = document.createElement("style");
style.textContent = `
.dumas-res { box-sizing:border-box; width:100%; padding:6px; background:#292929; color:#ddd; font:11px system-ui; }
.dumas-res .section { margin-top:6px; padding-top:5px; border-top:1px solid #444; }
.dumas-res .section:first-child { margin-top:0; padding-top:0; border-top:0; }
.dumas-res .section-title { margin-bottom:4px; color:#aaa; font-size:10px; font-weight:600; letter-spacing:.02em; text-transform:uppercase; }
.dumas-res .chips { display:grid; grid-template-columns:repeat(3,minmax(0,1fr)); gap:3px; }
.dumas-res button { min-height:25px; padding:2px 4px; border:1px solid #555; border-radius:4px; background:#1d1d1d; color:#ddd; cursor:pointer; font:inherit; }
.dumas-res button.active { background:#b9573d; color:white; border-color:#ef8c6d; }
.dumas-res .ratio-button { display:flex; align-items:center; justify-content:center; gap:5px; }
.dumas-res .ratio-icon { display:inline-block; width:10px; height:10px; border:1px solid currentColor; border-radius:1px; opacity:.9; flex:0 0 auto; }
.dumas-res .ratio-icon.tall { height:12px; width:8px; }
.dumas-res .ratio-icon.wide { height:8px; width:13px; }
.dumas-res .sizes { display:grid; grid-template-columns:repeat(2,minmax(0,1fr)); gap:3px; max-height:154px; overflow:auto; }
.dumas-res .size { min-height:31px; text-align:left; font-family:ui-monospace,monospace; line-height:1.15; }
.dumas-res .size small { display:block; color:#999; font-size:9px; }
.dumas-res .batch { display:grid; grid-template-columns:26px 1fr 26px; gap:3px; align-items:center; }
.dumas-res .batch button { min-height:24px; font-size:15px; line-height:1; }
.dumas-res .batch input { text-align:center; }
.dumas-res .custom { display:grid; grid-template-columns:1fr 1fr; gap:4px; margin-top:6px; }
.dumas-res .custom-row { display:grid; grid-template-columns:1fr 28px 1fr; gap:4px; grid-column:1/-1; }
.dumas-res .custom-row button { min-height:28px; }
.dumas-res .custom-row input { min-width:0; }
.dumas-res .target-row { display:grid; grid-template-columns:repeat(4,1fr); gap:3px; grid-column:1/-1; }
.dumas-res .target-row button { min-height:25px; }
.dumas-res .dimension-row { display:grid; grid-template-columns:1fr 1fr; gap:4px; grid-column:1/-1; }
.dumas-res .dimension-row input { color:#9dd8a5; text-align:center; }
.dumas-res .preview { grid-column:1/-1; display:flex; justify-content:center; align-items:center; min-height:38px; margin-top:2px; }
.dumas-res .preview-shape { border:1px solid #8cc63f; background:#273b1c; max-width:100%; max-height:42px; }
.dumas-res input { width:100%; box-sizing:border-box; background:#181818; color:#eee; border:1px solid #555; border-radius:3px; padding:4px; }
.dumas-res .label { grid-column:1/-1; color:#aaa; }
.dumas-res .meta { margin-top:6px; padding-top:5px; border-top:1px solid #444; color:#9dd8a5; font-family:ui-monospace,monospace; }
`;
document.head.appendChild(style);
function render(node, root) {
const s = read(node), ratio = s.ratio || "1:1";
root.replaceChildren();
const ratioSection = document.createElement("div"); ratioSection.className = "section";
const ratioTitle = document.createElement("div"); ratioTitle.className = "section-title"; ratioTitle.textContent = "Aspect ratio";
ratioSection.append(ratioTitle);
const chips = document.createElement("div"); chips.className = "chips";
[...RATIOS, "custom_ratio", "custom"].forEach((id) => {
const button = document.createElement("button");
button.className = `ratio-button ${(s.mode === "preset" && id === ratio) || (s.mode === id) ? "active" : ""}`;
if (RATIOS.includes(id)) {
const icon = document.createElement("span"); icon.className = "ratio-icon";
const [rw, rh] = id.split(":").map(Number);
if (rw / rh > 1.25) icon.classList.add("wide");
else if (rw / rh < 0.8) icon.classList.add("tall");
button.append(icon, document.createTextNode(id));
} else button.textContent = id === "custom_ratio" ? "Custom Ratio" : "Custom Resolution";
button.dataset.id = id; chips.append(button);
});
ratioSection.append(chips); root.append(ratioSection);
const batchSection = document.createElement("div"); batchSection.className = "section";
const batchTitle = document.createElement("div"); batchTitle.className = "section-title"; batchTitle.textContent = "Batch";
const batch = document.createElement("div"); batch.className = "batch";
for (const [text, delta] of [["−", -1], ["+", 1]]) {
const button = document.createElement("button"); button.textContent = text; button.dataset.batchDelta = delta; batch.append(button);
if (delta < 0) batch.prepend(button);
}
const batchInput = document.createElement("input"); batchInput.type = "number"; batchInput.min = "1"; batchInput.max = "64"; batchInput.step = "1"; batchInput.value = Math.max(1, Math.min(64, Number(s.batch) || 1)); batchInput.dataset.key = "batch";
batch.insertBefore(batchInput, batch.lastChild);
batchSection.append(batchTitle, batch); root.append(batchSection);
if (s.mode === "custom" || s.mode === "custom_ratio") {
const customSection = document.createElement("div"); customSection.className = "section";
const customTitle = document.createElement("div"); customTitle.className = "section-title"; customTitle.textContent = s.mode === "custom" ? "Custom resolution" : "Custom ratio";
const panel = document.createElement("div"); panel.className = "custom";
const label = document.createElement("div"); label.className = "label"; label.textContent = s.mode === "custom" ? "Width · height · snap" : "Ratio · target width · snap"; panel.append(label);
if (s.mode === "custom_ratio") {
const ratioRow = document.createElement("div"); ratioRow.className = "custom-row";
for (const key of ["custom_ratio_w", "custom_ratio_h"]) { const input=document.createElement("input"); input.dataset.key=key; input.type="number"; input.min="1"; input.value=s[key]; ratioRow.append(input); if (key === "custom_ratio_w") { const swap=document.createElement("button"); swap.textContent="⇄"; swap.title="Swap ratio"; swap.dataset.swapRatio="1"; ratioRow.append(swap); } }
panel.append(ratioRow);
const targetLabel=document.createElement("div"); targetLabel.className="label"; targetLabel.textContent="Target width"; panel.append(targetLabel);
const targets=document.createElement("div"); targets.className="target-row";
for (const width of [512,768,1024,1536]) { const b=document.createElement("button"); b.textContent=width; b.dataset.widthTarget=width; if(Number(s.w)===width) b.classList.add("active"); targets.append(b); }
panel.append(targets);
const dimensionLabel=document.createElement("div"); dimensionLabel.className="label"; dimensionLabel.textContent="Output dimensions"; panel.append(dimensionLabel);
const dimensions=document.createElement("div"); dimensions.className="dimension-row";
const widthInput=document.createElement("input"); widthInput.type="number"; widthInput.dataset.key="w"; widthInput.value=s.w; widthInput.title="Width";
const heightInput=document.createElement("input"); heightInput.type="number"; heightInput.value=s.h; heightInput.title="Height"; heightInput.readOnly=true;
dimensions.append(widthInput,heightInput); panel.append(dimensions);
const preview=document.createElement("div"); preview.className="preview";
const shape=document.createElement("div"); shape.className="preview-shape";
const shapeWidth=Math.min(90, Math.max(34, 90 * Number(s.w) / Math.max(Number(s.h), Number(s.w))));
shape.style.width=`${shapeWidth}px`; shape.style.height="42px";
preview.append(shape); panel.append(preview);
} else {
const fields = [["custom_w", "Width"],["custom_h", "Height"]];
for (const [key, text] of fields) { const input=document.createElement("input"); input.dataset.key=key; input.type="number"; input.title=text; input.value=s[key]; input.placeholder=text; panel.append(input); }
}
const snapLabel=document.createElement("div"); snapLabel.className="label"; snapLabel.textContent="Snap step"; panel.append(snapLabel);
for (const step of [8,16,32,64]) { const b=document.createElement("button"); b.textContent=`${step}px`; b.dataset.snap=step; b.className=Number(s.snap)===step?"active":""; panel.append(b); }
customSection.append(customTitle, panel); root.append(customSection);
} else {
const sizeSection = document.createElement("div"); sizeSection.className = "section";
const sizeTitle = document.createElement("div"); sizeTitle.className = "section-title"; sizeTitle.textContent = `Resolution presets · ${ratio}`;
const sizes = document.createElement("div"); sizes.className="sizes";
for (const [w,h] of (SIZES[ratio] || [])) { const b=document.createElement("button"); b.className="size"; b.dataset.w=w; b.dataset.h=h; b.innerHTML=`${w} × ${h}<small>${(w*h/1e6).toFixed(2)} MP</small>`; if (w===Number(s.w)&&h===Number(s.h)) b.classList.add("active"); sizes.append(b); }
sizeSection.append(sizeTitle, sizes); root.append(sizeSection);
}
const meta=document.createElement("div"); meta.className="meta"; meta.textContent=`Output ${s.w} × ${s.h} · ${(s.w*s.h/1e6).toFixed(2)} MP · batch ${Math.max(1,Math.min(64,Number(s.batch)||1))}`; root.append(meta);
}
function setup(node) {
node.resizable = false;
const root=document.createElement("div"); root.className="dumas-res";
const widget=node.addDOMWidget("dumas_resolution_ui", "custom", root, {serialize:false, getValue:()=>read(node), setValue:()=>{}, getMinHeight:()=>570});
// Keep the LiteGraph frame at least as tall as the rendered controls.
// The DOM widget otherwise keeps its old compact minimum and overhangs
// the node even when the node itself is marked non-resizable.
widget.computeLayoutSize=()=>({minHeight:570,minWidth:1});
root.addEventListener("click", (event) => {
const button=event.target.closest("button"); if (!button) return;
const s=read(node), id=button.dataset.id;
if (button.dataset.batchDelta) { s.batch=Math.max(1,Math.min(64,(Number(s.batch)||1)+Number(button.dataset.batchDelta))); write(node,s); render(node,root); return; }
if (button.dataset.swapRatio) { [s.custom_ratio_w,s.custom_ratio_h]=[s.custom_ratio_h,s.custom_ratio_w]; [s.w,s.h]=ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap); write(node,s); render(node,root); return; }
if (button.dataset.widthTarget) { s.w=snap(clamp(Number(button.dataset.widthTarget)),s.snap); [s.w,s.h]=ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap); write(node,s); render(node,root); return; }
if (id && SIZES[id]) { const [w,h]=DEFAULT_SIZE[id]; write(node,{...s,mode:"preset",ratio:id,w,h}); }
else if (id === "custom") write(node,{...s,mode:"custom",w:s.custom_w,h:s.custom_h});
else if (id === "custom_ratio") write(node,{...s,mode:"custom_ratio",w:ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap)[0],h:ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap)[1]});
else if (button.dataset.w) write(node,{...s,w:Number(button.dataset.w),h:Number(button.dataset.h)});
else if (button.dataset.snap) { const step=Number(button.dataset.snap); const next={...s,snap:step}; if(s.mode==="custom") { next.w=snap(clamp(s.custom_w),step); next.h=snap(clamp(s.custom_h),step); } else if(s.mode==="custom_ratio") [next.w,next.h]=ratioPair(s.w,s.custom_ratio_w,s.custom_ratio_h,step); write(node,next); return; }
render(node,root);
});
root.addEventListener("change", (event) => { const key=event.target.dataset.key; if(!key)return; const s=read(node), value=key==="batch" ? Math.max(1,Math.min(64,Number(event.target.value)||1)) : Math.max(1,Math.min(16384,Number(event.target.value)||1)); s[key]=value; if(s.mode==="custom") { s.w=snap(clamp(s.custom_w),s.snap); s.h=snap(clamp(s.custom_h),s.snap); } else if(s.mode==="custom_ratio") { [s.w,s.h]=ratioPair(key==="w" ? value : s.w,s.custom_ratio_w,s.custom_ratio_h,s.snap); } write(node,s); render(node,root); });
node._dumasResolutionRoot=root; node.size=[300,640]; queueMicrotask(()=>render(node,root));
}
const originalGraphToPrompt=app.graphToPrompt?.bind(app);
if (originalGraphToPrompt && !app.__dumasResolutionPromptHook) {
app.__dumasResolutionPromptHook=true;
app.graphToPrompt=async (...args)=>{ const result=await originalGraphToPrompt(...args); injectState(result,collectNodes(app.graph)); return result; };
}
app.registerExtension({
name:"Dumas.Resolution",
beforeRegisterNodeDef(nodeType,nodeData) {
if(nodeData?.name!==CLASS)return;
const oldConfigure=nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure=function(...args){const result=oldConfigure?.apply(this,args); if(this._dumasResolutionRoot)render(this,this._dumasResolutionRoot); return result;};
nodeType.prototype.onResize=function(){this.size=[300,640];};
},
nodeCreated(node){if(node.comfyClass===CLASS)setup(node);},
});