2748 lines
114 KiB
JavaScript
2748 lines
114 KiB
JavaScript
/**
|
||
* Photoshop Lite · Obsidian Liquid Studio
|
||
* Professional Image Manipulation Suite & Universal Batch Automation
|
||
*/
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// GLOBAL APPLICATION STATE
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let currentTool = "crop";
|
||
let filesList = []; // Array of { file, name, size, type, dataUrl, naturalW, naturalH }
|
||
let activeIndex = 0;
|
||
let zoomFactor = 1.0;
|
||
let activeSessionId = "";
|
||
|
||
// Centralized Tool Parameters State (always available, regardless of active tab)
|
||
const toolState = {
|
||
crop: {
|
||
aspect: "free",
|
||
x: 0, y: 0, w: 0, h: 0
|
||
},
|
||
resize: {
|
||
width: 0,
|
||
height: 0,
|
||
maintain_aspect: true
|
||
},
|
||
rotate: {
|
||
operation: "90",
|
||
angle: 0
|
||
},
|
||
adjust: {
|
||
brightness: 0,
|
||
contrast: 0,
|
||
saturation: 0,
|
||
gamma: 1.0
|
||
},
|
||
filter: {
|
||
filter: "BLUR"
|
||
},
|
||
round_corners: {
|
||
radius: 35,
|
||
is_circle: false
|
||
},
|
||
border: {
|
||
border_width: 20,
|
||
border_color: "#ffffff",
|
||
pad_aspect: "none"
|
||
},
|
||
watermark: {
|
||
position: "bottom_right",
|
||
opacity: 60,
|
||
base64: "",
|
||
fileName: ""
|
||
},
|
||
masker: {
|
||
brush_size: 40,
|
||
mode: "brush",
|
||
color: "rgba(244, 63, 94, 0.70)",
|
||
opacity: 70
|
||
},
|
||
convert: {
|
||
format: "png",
|
||
quality: 95
|
||
},
|
||
compress: {
|
||
format: "original",
|
||
quality: 80,
|
||
target_size_mb: 0
|
||
},
|
||
strip_metadata: {
|
||
format: "original",
|
||
quality: 95
|
||
}
|
||
};
|
||
|
||
// Crop Drag State
|
||
let cropInteraction = null;
|
||
|
||
// Masker Canvas State
|
||
let maskCanvas = null;
|
||
let maskCtx = null;
|
||
let isDrawing = false;
|
||
let maskStrokes = [];
|
||
|
||
window.toolState = toolState;
|
||
window.filesList = filesList;
|
||
window.maskStrokes = maskStrokes;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// PROXY-SAFE API URL RESOLVER
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function getApiUrl(endpoint) {
|
||
const p = endpoint.startsWith("/") ? endpoint : "/" + endpoint;
|
||
if (window.location.pathname.startsWith("/tool/image-manipulator")) {
|
||
return "/tool/image-manipulator" + p;
|
||
}
|
||
return p;
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// INITIALIZATION
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
document.addEventListener("DOMContentLoaded", () => {
|
||
setupDragAndDrop();
|
||
setupKeyboardShortcuts();
|
||
setupCropDragEvents();
|
||
renderToolOptions();
|
||
renderToolControls();
|
||
updateQueueUI();
|
||
refreshBackgroundJobs();
|
||
startJobPolling();
|
||
});
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// FILE INGESTION & DRAG AND DROP
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function setupDragAndDrop() {
|
||
const dropTargets = [
|
||
document.getElementById("ps-empty-dropzone"),
|
||
document.getElementById("ps-viewport"),
|
||
document.body
|
||
];
|
||
|
||
dropTargets.forEach(target => {
|
||
if (!target) return;
|
||
["dragenter", "dragover", "dragleave", "drop"].forEach(evtName => {
|
||
target.addEventListener(evtName, (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
}, false);
|
||
});
|
||
|
||
["dragenter", "dragover"].forEach(evtName => {
|
||
target.addEventListener(evtName, () => {
|
||
const emptyDrop = document.getElementById("ps-empty-dropzone");
|
||
if (emptyDrop) emptyDrop.classList.add("dragover");
|
||
}, false);
|
||
});
|
||
|
||
["dragleave", "drop"].forEach(evtName => {
|
||
target.addEventListener(evtName, () => {
|
||
const emptyDrop = document.getElementById("ps-empty-dropzone");
|
||
if (emptyDrop) emptyDrop.classList.remove("dragover");
|
||
}, false);
|
||
});
|
||
|
||
target.addEventListener("drop", async (e) => {
|
||
const items = e.dataTransfer.items;
|
||
if (items && items.length > 0) {
|
||
const scannedFiles = [];
|
||
const scanEntry = async (entry, path = "") => {
|
||
if (entry.isFile) {
|
||
const file = await new Promise(resolve => entry.file(resolve));
|
||
Object.defineProperty(file, "webkitRelativePath", {
|
||
value: path ? `${path}/${file.name}` : file.name,
|
||
writable: false
|
||
});
|
||
scannedFiles.push(file);
|
||
} else if (entry.isDirectory) {
|
||
const dirReader = entry.createReader();
|
||
const readEntries = async () => {
|
||
const entries = await new Promise(resolve => dirReader.readEntries(resolve));
|
||
if (entries.length > 0) {
|
||
for (const sub of entries) {
|
||
await scanEntry(sub, path ? `${path}/${entry.name}` : entry.name);
|
||
}
|
||
await readEntries();
|
||
}
|
||
};
|
||
await readEntries();
|
||
}
|
||
};
|
||
|
||
for (let i = 0; i < items.length; i++) {
|
||
const it = items[i];
|
||
if (it.webkitGetAsEntry) {
|
||
const entry = it.webkitGetAsEntry();
|
||
if (entry) await scanEntry(entry);
|
||
} else if (it.kind === "file") {
|
||
const f = it.getAsFile();
|
||
if (f) scannedFiles.push(f);
|
||
}
|
||
}
|
||
|
||
if (scannedFiles.length > 0) {
|
||
ingestFiles(scannedFiles);
|
||
return;
|
||
}
|
||
}
|
||
|
||
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||
ingestFiles(e.dataTransfer.files);
|
||
}
|
||
}, false);
|
||
});
|
||
}
|
||
|
||
function handleFileInputChange(input) {
|
||
if (input.files && input.files.length > 0) {
|
||
ingestFiles(input.files);
|
||
input.value = "";
|
||
}
|
||
}
|
||
window.handleFileInputChange = handleFileInputChange;
|
||
|
||
async function ingestFiles(newFileList) {
|
||
const validFiles = Array.from(newFileList).filter(f => {
|
||
const name = f.name.toLowerCase();
|
||
return f.type.startsWith("image/") ||
|
||
name.endsWith(".png") || name.endsWith(".jpg") || name.endsWith(".jpeg") ||
|
||
name.endsWith(".webp") || name.endsWith(".heic") || name.endsWith(".avif") ||
|
||
name.endsWith(".bmp") || name.endsWith(".tiff") || name.endsWith(".ico") || name.endsWith(".gif");
|
||
});
|
||
|
||
if (validFiles.length === 0) {
|
||
showToast("No valid image files found", "error");
|
||
return;
|
||
}
|
||
|
||
showToast(`Loading ${validFiles.length} file(s)...`, "info");
|
||
|
||
for (const file of validFiles) {
|
||
const dataUrl = await readFileAsDataURL(file);
|
||
const dims = await getImageDimensions(dataUrl);
|
||
|
||
filesList.push({
|
||
file: file,
|
||
name: file.webkitRelativePath || file.name,
|
||
size: file.size,
|
||
type: file.type || "image/jpeg",
|
||
dataUrl: dataUrl,
|
||
naturalW: dims.w,
|
||
naturalH: dims.h
|
||
});
|
||
}
|
||
|
||
if (filesList.length > 0) {
|
||
if (activeIndex >= filesList.length) activeIndex = 0;
|
||
const cur = filesList[activeIndex];
|
||
historySnapshots = [{
|
||
id: "init_" + activeIndex,
|
||
label: "Original",
|
||
time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
|
||
dataUrl: cur.dataUrl,
|
||
w: cur.naturalW,
|
||
h: cur.naturalH
|
||
}];
|
||
renderActiveImage();
|
||
updateSplitImages();
|
||
renderHistoryTab();
|
||
}
|
||
|
||
updateQueueUI();
|
||
showToast(`Loaded ${filesList.length} image(s) into workspace`, "success");
|
||
}
|
||
window.ingestFiles = ingestFiles;
|
||
|
||
function readFileAsDataURL(file) {
|
||
return new Promise((resolve) => {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => resolve(e.target.result);
|
||
reader.readAsDataURL(file);
|
||
});
|
||
}
|
||
|
||
function getImageDimensions(dataUrl) {
|
||
return new Promise((resolve) => {
|
||
const img = new Image();
|
||
img.onload = () => resolve({ w: img.naturalWidth, h: img.naturalHeight });
|
||
img.onerror = () => resolve({ w: 800, h: 600 });
|
||
img.src = dataUrl;
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// STAGE & FILMSTRIP RENDERING
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function renderActiveImage() {
|
||
const emptyZone = document.getElementById("ps-empty-dropzone");
|
||
const stage = document.getElementById("ps-stage-container");
|
||
const imgEl = document.getElementById("ps-active-img");
|
||
const filmstrip = document.getElementById("ps-filmstrip");
|
||
|
||
if (!filesList || filesList.length === 0) {
|
||
if (emptyZone) emptyZone.style.display = "flex";
|
||
if (stage) stage.style.display = "none";
|
||
if (filmstrip) filmstrip.style.display = "none";
|
||
updateInspectorInfo(null);
|
||
return;
|
||
}
|
||
|
||
const current = filesList[activeIndex];
|
||
if (!current) return;
|
||
|
||
if (emptyZone) emptyZone.style.display = "none";
|
||
if (stage) stage.style.display = "inline-flex";
|
||
if (filmstrip) filmstrip.style.display = "flex";
|
||
|
||
imgEl.src = current.dataUrl;
|
||
|
||
imgEl.onload = () => {
|
||
current.naturalW = imgEl.naturalWidth;
|
||
current.naturalH = imgEl.naturalHeight;
|
||
|
||
// Auto-update resize defaults if currently active
|
||
if (!toolState.resize.width || toolState.resize.width <= 0) {
|
||
toolState.resize.width = current.naturalW;
|
||
toolState.resize.height = current.naturalH;
|
||
}
|
||
|
||
updateInspectorInfo(current);
|
||
setupActiveToolStage();
|
||
renderFilmstrip();
|
||
};
|
||
}
|
||
|
||
function updateQueueUI() {
|
||
const counterPill = document.getElementById("ps-file-counter");
|
||
const btnBatchHeader = document.getElementById("btn-batch-all");
|
||
const btnBatchFooter = document.getElementById("btn-batch-footer");
|
||
const hubCount = document.getElementById("batch-hub-count");
|
||
const hubSize = document.getElementById("batch-hub-size");
|
||
|
||
const count = filesList.length;
|
||
const totalBytes = filesList.reduce((acc, f) => acc + f.size, 0);
|
||
const totalMb = (totalBytes / (1024 * 1024)).toFixed(2);
|
||
|
||
if (counterPill) {
|
||
counterPill.innerHTML = `<i class="fa-regular fa-images"></i> <span>${count} image${count === 1 ? "" : "s"} (${totalMb} MB)</span>`;
|
||
if (count > 0) counterPill.classList.add("has-files");
|
||
else counterPill.classList.remove("has-files");
|
||
}
|
||
|
||
if (btnBatchHeader) {
|
||
if (count > 1) {
|
||
btnBatchHeader.style.display = "inline-flex";
|
||
btnBatchHeader.innerHTML = `<i class="fa-solid fa-layer-group"></i> Batch All (${count})`;
|
||
} else {
|
||
btnBatchHeader.style.display = "none";
|
||
}
|
||
}
|
||
|
||
if (btnBatchFooter) {
|
||
if (count > 1) {
|
||
btnBatchFooter.style.display = "inline-flex";
|
||
btnBatchFooter.innerHTML = `<i class="fa-solid fa-layer-group"></i> Apply to All (${count} Files)`;
|
||
} else {
|
||
btnBatchFooter.style.display = "none";
|
||
}
|
||
}
|
||
|
||
if (hubCount) hubCount.textContent = count.toString();
|
||
if (hubSize) hubSize.textContent = `${totalMb} MB`;
|
||
}
|
||
|
||
function renderFilmstrip() {
|
||
const tray = document.getElementById("ps-filmstrip-tray");
|
||
if (!tray) return;
|
||
|
||
tray.innerHTML = "";
|
||
filesList.forEach((item, index) => {
|
||
const card = document.createElement("div");
|
||
card.className = `ps-thumb-card ${index === activeIndex ? "active" : ""}`;
|
||
card.onclick = () => selectActiveImage(index);
|
||
|
||
const sizeKb = (item.size / 1024).toFixed(0);
|
||
card.innerHTML = `
|
||
<img src="${item.dataUrl}" class="ps-thumb-img" alt="thumb">
|
||
<div class="ps-thumb-meta">
|
||
<span class="ps-thumb-name" title="${item.name}">${item.name}</span>
|
||
<span class="ps-thumb-size">${item.naturalW}×${item.naturalH} · ${sizeKb}KB</span>
|
||
</div>
|
||
<button class="ps-thumb-close" onclick="removeImage(${index}, event)" title="Remove image">
|
||
<i class="fa-solid fa-xmark"></i>
|
||
</button>
|
||
`;
|
||
tray.appendChild(card);
|
||
});
|
||
}
|
||
|
||
function selectActiveImage(index) {
|
||
if (index >= 0 && index < filesList.length) {
|
||
activeIndex = index;
|
||
const cur = filesList[index];
|
||
historySnapshots = [{
|
||
id: "init_" + index,
|
||
label: "Original",
|
||
time: new Date().toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }),
|
||
dataUrl: cur.dataUrl,
|
||
w: cur.naturalW,
|
||
h: cur.naturalH
|
||
}];
|
||
renderActiveImage();
|
||
updateSplitImages();
|
||
renderHistoryTab();
|
||
}
|
||
}
|
||
window.selectActiveImage = selectActiveImage;
|
||
|
||
function removeImage(index, event) {
|
||
if (event) event.stopPropagation();
|
||
filesList.splice(index, 1);
|
||
if (activeIndex >= filesList.length) {
|
||
activeIndex = Math.max(0, filesList.length - 1);
|
||
}
|
||
renderActiveImage();
|
||
updateQueueUI();
|
||
}
|
||
window.removeImage = removeImage;
|
||
|
||
function resetWorkspace() {
|
||
filesList = [];
|
||
activeIndex = 0;
|
||
toolState.crop.x = 0;
|
||
toolState.crop.y = 0;
|
||
toolState.crop.w = 0;
|
||
toolState.crop.h = 0;
|
||
maskStrokes = [];
|
||
renderActiveImage();
|
||
updateQueueUI();
|
||
showToast("Workspace cleared", "info");
|
||
}
|
||
window.resetWorkspace = resetWorkspace;
|
||
|
||
function updateInspectorInfo(item) {
|
||
const fn = document.getElementById("info-filename");
|
||
const dim = document.getElementById("info-dimensions");
|
||
const asp = document.getElementById("info-aspect");
|
||
const sz = document.getElementById("info-filesize");
|
||
const mime = document.getElementById("info-mimetype");
|
||
|
||
if (!item) {
|
||
if (fn) fn.textContent = "--";
|
||
if (dim) dim.textContent = "--";
|
||
if (asp) asp.textContent = "--";
|
||
if (sz) sz.textContent = "--";
|
||
if (mime) mime.textContent = "--";
|
||
return;
|
||
}
|
||
|
||
const gcd = (a, b) => (b === 0 ? a : gcd(b, a % b));
|
||
const div = gcd(item.naturalW, item.naturalH) || 1;
|
||
const ratioStr = `${item.naturalW / div}:${item.naturalH / div}`;
|
||
const mb = (item.size / (1024 * 1024)).toFixed(2);
|
||
|
||
if (fn) fn.textContent = item.name;
|
||
if (dim) dim.textContent = `${item.naturalW} × ${item.naturalH} px`;
|
||
if (asp) asp.textContent = `${(item.naturalW / item.naturalH).toFixed(2)} (${ratioStr})`;
|
||
if (sz) sz.textContent = `${mb} MB (${(item.size / 1024).toFixed(0)} KB)`;
|
||
if (mime) mime.textContent = item.type;
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// TOOL SELECTION & DYNAMIC OPTION STRIP
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function selectTool(toolName, btnElement) {
|
||
currentTool = toolName;
|
||
|
||
document.querySelectorAll(".ps-tool-btn").forEach(btn => btn.classList.remove("active"));
|
||
if (btnElement) btnElement.classList.add("active");
|
||
else {
|
||
const match = document.querySelector(`.ps-tool-btn[data-tool="${toolName}"]`);
|
||
if (match) match.classList.add("active");
|
||
}
|
||
|
||
renderToolOptions();
|
||
renderToolControls();
|
||
setupActiveToolStage();
|
||
}
|
||
window.selectTool = selectTool;
|
||
|
||
function setupActiveToolStage() {
|
||
const cropOverlay = document.getElementById("ps-crop-overlay");
|
||
const maskCanvasEl = document.getElementById("ps-mask-canvas");
|
||
const brushRing = document.getElementById("brush-cursor-ring");
|
||
|
||
if (cropOverlay) cropOverlay.style.display = (currentTool === "crop" && filesList.length > 0) ? "block" : "none";
|
||
if (maskCanvasEl) maskCanvasEl.style.display = (currentTool === "masker" && filesList.length > 0) ? "block" : "none";
|
||
if (brushRing) brushRing.style.display = (currentTool === "masker" && filesList.length > 0) ? "block" : "none";
|
||
|
||
if (currentTool === "crop" && filesList.length > 0) {
|
||
initCropBox();
|
||
}
|
||
|
||
if (currentTool === "masker" && filesList.length > 0) {
|
||
initMaskCanvas();
|
||
}
|
||
|
||
if (currentTool === "resize" && filesList.length > 0) {
|
||
const cur = filesList[activeIndex];
|
||
if (cur) {
|
||
if (!toolState.resize.width || toolState.resize.width <= 0) {
|
||
toolState.resize.width = cur.naturalW;
|
||
toolState.resize.height = cur.naturalH;
|
||
}
|
||
const wIn = document.getElementById("param-width");
|
||
const hIn = document.getElementById("param-height");
|
||
if (wIn) wIn.value = toolState.resize.width;
|
||
if (hIn) hIn.value = toolState.resize.height;
|
||
}
|
||
}
|
||
|
||
if (currentTool === "compress" && filesList.length > 0) {
|
||
simulateCompressionDebounced();
|
||
}
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// VISUAL CROPPER ENGINE (Photoshop Interactive Box & 8 Handles)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function initCropBox() {
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img || !img.clientWidth || !img.clientHeight) {
|
||
setTimeout(initCropBox, 50);
|
||
return;
|
||
}
|
||
|
||
const stageW = img.clientWidth;
|
||
const stageH = img.clientHeight;
|
||
|
||
// Initial box: 85% centered
|
||
const w = Math.round(stageW * 0.85);
|
||
const h = Math.round(stageH * 0.85);
|
||
const x = Math.round((stageW - w) / 2);
|
||
const y = Math.round((stageH - h) / 2);
|
||
|
||
toolState.crop.x = x;
|
||
toolState.crop.y = y;
|
||
toolState.crop.w = w;
|
||
toolState.crop.h = h;
|
||
|
||
applyAspectRatioConstraint(toolState.crop.aspect);
|
||
updateCropVisuals();
|
||
}
|
||
|
||
function setCropAspect(aspect) {
|
||
toolState.crop.aspect = aspect;
|
||
document.querySelectorAll(".crop-aspect-btn").forEach(b => {
|
||
b.classList.toggle("active", b.getAttribute("data-aspect") === aspect);
|
||
});
|
||
const aspectSel = document.getElementById("param-crop-aspect");
|
||
if (aspectSel) aspectSel.value = aspect;
|
||
|
||
applyAspectRatioConstraint(aspect);
|
||
updateCropVisuals();
|
||
}
|
||
window.setCropAspect = setCropAspect;
|
||
|
||
function resetCropToFull() {
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img) return;
|
||
toolState.crop.x = 0;
|
||
toolState.crop.y = 0;
|
||
toolState.crop.w = img.clientWidth;
|
||
toolState.crop.h = img.clientHeight;
|
||
applyAspectRatioConstraint(toolState.crop.aspect);
|
||
updateCropVisuals();
|
||
}
|
||
window.resetCropToFull = resetCropToFull;
|
||
|
||
function applyAspectRatioConstraint(aspect) {
|
||
if (aspect === "free") return;
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img) return;
|
||
|
||
const ratios = {
|
||
"1:1": 1.0,
|
||
"16:9": 16 / 9,
|
||
"9:16": 9 / 16,
|
||
"4:5": 4 / 5,
|
||
"4:3": 4 / 3,
|
||
"3:2": 3 / 2
|
||
};
|
||
|
||
const targetRatio = ratios[aspect];
|
||
if (!targetRatio) return;
|
||
|
||
let newW = toolState.crop.w || Math.round(img.clientWidth * 0.85);
|
||
let newH = Math.round(newW / targetRatio);
|
||
|
||
if (newH > img.clientHeight) {
|
||
newH = img.clientHeight;
|
||
newW = Math.round(newH * targetRatio);
|
||
}
|
||
if (newW > img.clientWidth) {
|
||
newW = img.clientWidth;
|
||
newH = Math.round(newW / targetRatio);
|
||
}
|
||
|
||
toolState.crop.w = newW;
|
||
toolState.crop.h = newH;
|
||
toolState.crop.x = Math.max(0, Math.min(img.clientWidth - newW, toolState.crop.x));
|
||
toolState.crop.y = Math.max(0, Math.min(img.clientHeight - newH, toolState.crop.y));
|
||
}
|
||
|
||
function updateCropVisuals() {
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img || !img.clientWidth) return;
|
||
|
||
const box = document.getElementById("crop-box");
|
||
const st = document.getElementById("crop-scrim-t");
|
||
const sb = document.getElementById("crop-scrim-b");
|
||
const sl = document.getElementById("crop-scrim-l");
|
||
const sr = document.getElementById("crop-scrim-r");
|
||
const dim = document.getElementById("crop-dim-badge");
|
||
|
||
const { x, y, w, h } = toolState.crop;
|
||
const imgW = img.clientWidth;
|
||
const imgH = img.clientHeight;
|
||
|
||
if (box) {
|
||
box.style.left = `${x}px`;
|
||
box.style.top = `${y}px`;
|
||
box.style.width = `${w}px`;
|
||
box.style.height = `${h}px`;
|
||
}
|
||
|
||
if (st) { st.style.top = "0px"; st.style.left = "0px"; st.style.width = `${imgW}px`; st.style.height = `${y}px`; }
|
||
if (sb) { sb.style.top = `${y + h}px`; sb.style.left = "0px"; sb.style.width = `${imgW}px`; sb.style.height = `${imgH - (y + h)}px`; }
|
||
if (sl) { sl.style.top = `${y}px`; sl.style.left = "0px"; sl.style.width = `${x}px`; sl.style.height = `${h}px`; }
|
||
if (sr) { sr.style.top = `${y}px`; sr.style.left = `${x + w}px`; sr.style.width = `${imgW - (x + w)}px`; sr.style.height = `${h}px`; }
|
||
|
||
const cur = filesList[activeIndex];
|
||
const natW = cur ? cur.naturalW : imgW;
|
||
const natH = cur ? cur.naturalH : imgH;
|
||
const scaleX = natW / imgW;
|
||
const scaleY = natH / imgH;
|
||
|
||
const realW = Math.round(w * scaleX);
|
||
const realH = Math.round(h * scaleY);
|
||
|
||
if (dim) {
|
||
dim.textContent = `${realW} × ${realH} px (${toolState.crop.aspect})`;
|
||
}
|
||
|
||
const optBadge = document.getElementById("opt-crop-size");
|
||
if (optBadge) {
|
||
optBadge.textContent = `${realW} × ${realH} px`;
|
||
}
|
||
}
|
||
|
||
function setupCropDragEvents() {
|
||
document.addEventListener("mousedown", (e) => {
|
||
if (currentTool !== "crop") return;
|
||
const handleEl = e.target.closest(".crop-handle");
|
||
const boxEl = e.target.closest("#crop-box");
|
||
|
||
if (handleEl) {
|
||
e.preventDefault();
|
||
cropInteraction = {
|
||
mode: "handle",
|
||
handle: handleEl.getAttribute("data-handle"),
|
||
startX: e.clientX,
|
||
startY: e.clientY,
|
||
origCrop: { ...toolState.crop }
|
||
};
|
||
} else if (boxEl) {
|
||
e.preventDefault();
|
||
cropInteraction = {
|
||
mode: "move",
|
||
startX: e.clientX,
|
||
startY: e.clientY,
|
||
origCrop: { ...toolState.crop }
|
||
};
|
||
}
|
||
});
|
||
|
||
document.addEventListener("mousemove", (e) => {
|
||
if (!cropInteraction || currentTool !== "crop") return;
|
||
e.preventDefault();
|
||
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img) return;
|
||
|
||
const dx = e.clientX - cropInteraction.startX;
|
||
const dy = e.clientY - cropInteraction.startY;
|
||
const orig = cropInteraction.origCrop;
|
||
const imgW = img.clientWidth;
|
||
const imgH = img.clientHeight;
|
||
|
||
if (cropInteraction.mode === "move") {
|
||
let newX = orig.x + dx;
|
||
let newY = orig.y + dy;
|
||
newX = Math.max(0, Math.min(imgW - orig.w, newX));
|
||
newY = Math.max(0, Math.min(imgH - orig.h, newY));
|
||
|
||
toolState.crop.x = Math.round(newX);
|
||
toolState.crop.y = Math.round(newY);
|
||
updateCropVisuals();
|
||
} else if (cropInteraction.mode === "handle") {
|
||
const h = cropInteraction.handle;
|
||
let newX = orig.x;
|
||
let newY = orig.y;
|
||
let newW = orig.w;
|
||
let newH = orig.h;
|
||
|
||
if (h.includes("e")) newW = orig.w + dx;
|
||
if (h.includes("s")) newH = orig.h + dy;
|
||
if (h.includes("w")) { newW = orig.w - dx; newX = orig.x + dx; }
|
||
if (h.includes("n")) { newH = orig.h - dy; newY = orig.y + dy; }
|
||
|
||
if (toolState.crop.aspect !== "free") {
|
||
const ratios = { "1:1": 1.0, "16:9": 16 / 9, "9:16": 9 / 16, "4:5": 4 / 5, "4:3": 4 / 3, "3:2": 3 / 2 };
|
||
const r = ratios[toolState.crop.aspect];
|
||
if (r) {
|
||
if (h === "e" || h === "w") newH = Math.round(newW / r);
|
||
else if (h === "n" || h === "s") newW = Math.round(newH * r);
|
||
else {
|
||
newH = Math.round(newW / r);
|
||
}
|
||
}
|
||
}
|
||
|
||
if (newW >= 30 && newH >= 30) {
|
||
if (newX >= 0 && newX + newW <= imgW && newY >= 0 && newY + newH <= imgH) {
|
||
toolState.crop.x = Math.round(newX);
|
||
toolState.crop.y = Math.round(newY);
|
||
toolState.crop.w = Math.round(newW);
|
||
toolState.crop.h = Math.round(newH);
|
||
updateCropVisuals();
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
document.addEventListener("mouseup", () => {
|
||
cropInteraction = null;
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// INPAINT MASK BRUSH ENGINE (Enterprise Pixel-Perfect Canvas Overlay)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let maskRedoStack = [];
|
||
|
||
function getMaskCanvasPoint(e) {
|
||
const canvas = document.getElementById("ps-mask-canvas");
|
||
if (!canvas) return { x: 0, y: 0 };
|
||
const rect = canvas.getBoundingClientRect();
|
||
if (!rect.width || !rect.height) return { x: 0, y: 0 };
|
||
|
||
// EXACT transformation: screen viewport pixels -> native canvas buffer pixels
|
||
const scaleX = canvas.width / rect.width;
|
||
const scaleY = canvas.height / rect.height;
|
||
|
||
const rawX = (e.clientX - rect.left) * scaleX;
|
||
const rawY = (e.clientY - rect.top) * scaleY;
|
||
|
||
return {
|
||
x: Math.max(0, Math.min(canvas.width, rawX)),
|
||
y: Math.max(0, Math.min(canvas.height, rawY))
|
||
};
|
||
}
|
||
|
||
function initMaskCanvas() {
|
||
const img = document.getElementById("ps-active-img");
|
||
const canvas = document.getElementById("ps-mask-canvas");
|
||
if (!img || !canvas) return;
|
||
|
||
const cur = filesList[activeIndex];
|
||
if (!cur) return;
|
||
|
||
// Set internal resolution to image native dimensions
|
||
const natW = cur.naturalW || img.naturalWidth || img.clientWidth || 800;
|
||
const natH = cur.naturalH || img.naturalHeight || img.clientHeight || 600;
|
||
|
||
if (canvas.width !== natW || canvas.height !== natH) {
|
||
canvas.width = natW;
|
||
canvas.height = natH;
|
||
}
|
||
|
||
maskCanvas = canvas;
|
||
maskCtx = canvas.getContext("2d");
|
||
|
||
redrawMaskStrokes();
|
||
setupMaskPointerEvents();
|
||
}
|
||
|
||
function setupMaskPointerEvents() {
|
||
const canvas = document.getElementById("ps-mask-canvas");
|
||
if (!canvas || canvas.dataset.pointerBound) return;
|
||
canvas.dataset.pointerBound = "true";
|
||
|
||
canvas.addEventListener("pointerdown", (e) => {
|
||
if (currentTool !== "masker") return;
|
||
e.preventDefault();
|
||
canvas.setPointerCapture(e.pointerId);
|
||
isDrawing = true;
|
||
maskRedoStack = []; // clear redo on new action
|
||
|
||
const pt = getMaskCanvasPoint(e);
|
||
const stroke = {
|
||
mode: toolState.masker.mode || "brush",
|
||
size: toolState.masker.brush_size,
|
||
points: [pt]
|
||
};
|
||
maskStrokes.push(stroke);
|
||
|
||
if (stroke.mode === "rect") {
|
||
stroke.startPt = pt;
|
||
} else {
|
||
renderSingleStrokeStep(stroke, pt, pt);
|
||
}
|
||
});
|
||
|
||
canvas.addEventListener("pointermove", (e) => {
|
||
updateBrushRing(e);
|
||
if (!isDrawing) return;
|
||
|
||
const pt = getMaskCanvasPoint(e);
|
||
const curStroke = maskStrokes[maskStrokes.length - 1];
|
||
if (curStroke) {
|
||
if (curStroke.mode === "rect") {
|
||
curStroke.endPt = pt;
|
||
redrawMaskStrokes();
|
||
if (maskCtx && curStroke.startPt) {
|
||
maskCtx.save();
|
||
maskCtx.fillStyle = "rgba(244, 63, 94, 0.55)";
|
||
maskCtx.strokeStyle = "#ffffff";
|
||
maskCtx.lineWidth = 2;
|
||
const rx = Math.min(curStroke.startPt.x, pt.x);
|
||
const ry = Math.min(curStroke.startPt.y, pt.y);
|
||
const rw = Math.abs(pt.x - curStroke.startPt.x);
|
||
const rh = Math.abs(pt.y - curStroke.startPt.y);
|
||
maskCtx.fillRect(rx, ry, rw, rh);
|
||
maskCtx.strokeRect(rx, ry, rw, rh);
|
||
maskCtx.restore();
|
||
}
|
||
} else if (curStroke.points.length > 0) {
|
||
const lastPt = curStroke.points[curStroke.points.length - 1];
|
||
curStroke.points.push(pt);
|
||
renderSingleStrokeStep(curStroke, lastPt, pt);
|
||
}
|
||
}
|
||
});
|
||
|
||
const stopDrawing = (e) => {
|
||
if (isDrawing) {
|
||
isDrawing = false;
|
||
try { canvas.releasePointerCapture(e.pointerId); } catch (_) {}
|
||
redrawMaskStrokes();
|
||
}
|
||
};
|
||
|
||
canvas.addEventListener("pointerup", stopDrawing);
|
||
canvas.addEventListener("pointercancel", stopDrawing);
|
||
canvas.addEventListener("pointerleave", (e) => {
|
||
if (!isDrawing) {
|
||
const ring = document.getElementById("brush-cursor-ring");
|
||
if (ring) ring.style.display = "none";
|
||
}
|
||
});
|
||
}
|
||
|
||
function renderSingleStrokeStep(stroke, p1, p2) {
|
||
if (!maskCtx) return;
|
||
|
||
maskCtx.save();
|
||
if (stroke.mode === "eraser") {
|
||
maskCtx.globalCompositeOperation = "destination-out";
|
||
maskCtx.lineWidth = stroke.size;
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.beginPath();
|
||
maskCtx.moveTo(p1.x, p1.y);
|
||
maskCtx.lineTo(p2.x, p2.y);
|
||
maskCtx.stroke();
|
||
} else {
|
||
maskCtx.globalCompositeOperation = "source-over";
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.lineWidth = stroke.size;
|
||
maskCtx.strokeStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)";
|
||
maskCtx.beginPath();
|
||
maskCtx.moveTo(p1.x, p1.y);
|
||
maskCtx.lineTo(p2.x, p2.y);
|
||
maskCtx.stroke();
|
||
}
|
||
maskCtx.restore();
|
||
}
|
||
|
||
function updateBrushRing(e) {
|
||
const ring = document.getElementById("brush-cursor-ring");
|
||
const canvas = document.getElementById("ps-mask-canvas");
|
||
if (!ring || !canvas) return;
|
||
|
||
if (currentTool !== "masker" || filesList.length === 0) {
|
||
ring.style.display = "none";
|
||
return;
|
||
}
|
||
|
||
const rect = canvas.getBoundingClientRect();
|
||
if (!rect.width || !rect.height) return;
|
||
|
||
const screenScale = rect.width / (canvas.width || 1);
|
||
const visualSize = Math.max(6, toolState.masker.brush_size * screenScale);
|
||
|
||
ring.style.width = `${visualSize}px`;
|
||
ring.style.height = `${visualSize}px`;
|
||
ring.style.left = `${e.clientX}px`;
|
||
ring.style.top = `${e.clientY}px`;
|
||
ring.style.display = "block";
|
||
}
|
||
|
||
function setBrushSize(size) {
|
||
toolState.masker.brush_size = parseInt(size, 10);
|
||
const optVal = document.getElementById("opt-brush-val");
|
||
const inspVal = document.getElementById("val-brush-sz");
|
||
if (optVal) optVal.innerText = `${size}px`;
|
||
if (inspVal) inspVal.innerText = `${size}px`;
|
||
}
|
||
window.setBrushSize = setBrushSize;
|
||
|
||
function setMaskMode(mode) {
|
||
toolState.masker.mode = mode;
|
||
renderToolOptions();
|
||
renderToolControls();
|
||
}
|
||
window.setMaskMode = setMaskMode;
|
||
|
||
function clearMaskStrokes() {
|
||
if (maskStrokes.length > 0) {
|
||
maskRedoStack.push([...maskStrokes]);
|
||
}
|
||
maskStrokes = [];
|
||
if (maskCtx && maskCanvas) {
|
||
maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
}
|
||
}
|
||
window.clearMaskStrokes = clearMaskStrokes;
|
||
|
||
function undoMaskStroke() {
|
||
if (maskStrokes.length > 0) {
|
||
const popped = maskStrokes.pop();
|
||
maskRedoStack.push(popped);
|
||
redrawMaskStrokes();
|
||
}
|
||
}
|
||
window.undoMaskStroke = undoMaskStroke;
|
||
|
||
function redoMaskStroke() {
|
||
if (maskRedoStack.length > 0) {
|
||
const item = maskRedoStack.pop();
|
||
if (Array.isArray(item)) {
|
||
maskStrokes = item;
|
||
} else {
|
||
maskStrokes.push(item);
|
||
}
|
||
redrawMaskStrokes();
|
||
}
|
||
}
|
||
window.redoMaskStroke = redoMaskStroke;
|
||
|
||
function fillMask() {
|
||
if (!maskCanvas) return;
|
||
maskStrokes.push({
|
||
mode: "fill",
|
||
size: 0,
|
||
points: []
|
||
});
|
||
redrawMaskStrokes();
|
||
}
|
||
window.fillMask = fillMask;
|
||
|
||
function invertMask() {
|
||
if (!maskCanvas) return;
|
||
maskStrokes.push({
|
||
mode: "invert",
|
||
size: 0,
|
||
points: []
|
||
});
|
||
redrawMaskStrokes();
|
||
}
|
||
window.invertMask = invertMask;
|
||
|
||
function redrawMaskStrokes() {
|
||
if (!maskCtx || !maskCanvas) return;
|
||
maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
|
||
maskStrokes.forEach(s => {
|
||
maskCtx.save();
|
||
if (s.mode === "fill") {
|
||
maskCtx.fillStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)";
|
||
maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
} else if (s.mode === "invert") {
|
||
maskCtx.globalCompositeOperation = "difference";
|
||
maskCtx.fillStyle = "#ffffff";
|
||
maskCtx.fillRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
} else if (s.mode === "rect" && s.startPt && s.endPt) {
|
||
maskCtx.fillStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)";
|
||
const rx = Math.min(s.startPt.x, s.endPt.x);
|
||
const ry = Math.min(s.startPt.y, s.endPt.y);
|
||
const rw = Math.abs(s.endPt.x - s.startPt.x);
|
||
const rh = Math.abs(s.endPt.y - s.startPt.y);
|
||
maskCtx.fillRect(rx, ry, rw, rh);
|
||
} else if (s.mode === "eraser") {
|
||
maskCtx.globalCompositeOperation = "destination-out";
|
||
maskCtx.lineWidth = s.size;
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.beginPath();
|
||
if (s.points.length > 0) {
|
||
maskCtx.moveTo(s.points[0].x, s.points[0].y);
|
||
s.points.forEach(p => maskCtx.lineTo(p.x, p.y));
|
||
}
|
||
maskCtx.stroke();
|
||
} else {
|
||
maskCtx.globalCompositeOperation = "source-over";
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.lineWidth = s.size;
|
||
maskCtx.strokeStyle = toolState.masker.color || "rgba(244, 63, 94, 0.70)";
|
||
maskCtx.beginPath();
|
||
if (s.points.length > 0) {
|
||
maskCtx.moveTo(s.points[0].x, s.points[0].y);
|
||
s.points.forEach(p => maskCtx.lineTo(p.x, p.y));
|
||
}
|
||
maskCtx.stroke();
|
||
}
|
||
maskCtx.restore();
|
||
});
|
||
}
|
||
|
||
function generateMaskDataUrl(targetW, targetH) {
|
||
if (!maskCanvas) return "";
|
||
const outCanvas = document.createElement("canvas");
|
||
outCanvas.width = targetW || maskCanvas.width;
|
||
outCanvas.height = targetH || maskCanvas.height;
|
||
const ctx = outCanvas.getContext("2d");
|
||
|
||
// Pure black background
|
||
ctx.fillStyle = "#000000";
|
||
ctx.fillRect(0, 0, outCanvas.width, outCanvas.height);
|
||
|
||
const scaleX = outCanvas.width / maskCanvas.width;
|
||
const scaleY = outCanvas.height / maskCanvas.height;
|
||
|
||
maskStrokes.forEach(s => {
|
||
ctx.save();
|
||
if (s.mode === "fill") {
|
||
ctx.fillStyle = "#ffffff";
|
||
ctx.fillRect(0, 0, outCanvas.width, outCanvas.height);
|
||
} else if (s.mode === "invert") {
|
||
ctx.globalCompositeOperation = "difference";
|
||
ctx.fillStyle = "#ffffff";
|
||
ctx.fillRect(0, 0, outCanvas.width, outCanvas.height);
|
||
} else if (s.mode === "rect" && s.startPt && s.endPt) {
|
||
ctx.fillStyle = "#ffffff";
|
||
const rx = Math.min(s.startPt.x * scaleX, s.endPt.x * scaleX);
|
||
const ry = Math.min(s.startPt.y * scaleY, s.endPt.y * scaleY);
|
||
const rw = Math.abs(s.endPt.x - s.startPt.x) * scaleX;
|
||
const rh = Math.abs(s.endPt.y - s.startPt.y) * scaleY;
|
||
ctx.fillRect(rx, ry, rw, rh);
|
||
} else if (s.mode === "eraser") {
|
||
ctx.globalCompositeOperation = "source-over";
|
||
ctx.strokeStyle = "#000000"; // Eraser turns mask black
|
||
ctx.lineWidth = s.size * scaleX;
|
||
ctx.lineCap = "round";
|
||
ctx.lineJoin = "round";
|
||
ctx.beginPath();
|
||
if (s.points.length > 0) {
|
||
ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY);
|
||
s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY));
|
||
}
|
||
ctx.stroke();
|
||
} else {
|
||
ctx.globalCompositeOperation = "source-over";
|
||
ctx.strokeStyle = "#ffffff"; // Mask is solid white
|
||
ctx.lineWidth = s.size * scaleX;
|
||
ctx.lineCap = "round";
|
||
ctx.lineJoin = "round";
|
||
ctx.beginPath();
|
||
if (s.points.length > 0) {
|
||
ctx.moveTo(s.points[0].x * scaleX, s.points[0].y * scaleY);
|
||
s.points.forEach(p => ctx.lineTo(p.x * scaleX, p.y * scaleY));
|
||
}
|
||
ctx.stroke();
|
||
}
|
||
ctx.restore();
|
||
});
|
||
|
||
return outCanvas.toDataURL("image/png");
|
||
}
|
||
|
||
function exportMaskOnly() {
|
||
const cur = filesList[activeIndex];
|
||
if (!cur) return;
|
||
const dataUrl = generateMaskDataUrl(cur.naturalW, cur.naturalH);
|
||
if (!dataUrl) return;
|
||
|
||
const a = document.createElement("a");
|
||
a.href = dataUrl;
|
||
a.download = (cur.name ? cur.name.replace(/\.[^/.]+$/, "") : "image") + "_mask.png";
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
a.remove();
|
||
showToast("Inpainting mask PNG downloaded", "success");
|
||
}
|
||
window.exportMaskOnly = exportMaskOnly;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// DYNAMIC CONTEXTUAL OPTIONS & INSPECTOR CONTROLS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function renderToolOptions() {
|
||
const strip = document.getElementById("ps-tool-options");
|
||
if (!strip) return;
|
||
|
||
const configs = {
|
||
crop: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Aspect:</span>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === 'free' ? 'active' : ''}" data-aspect="free" onclick="setCropAspect('free')">Freeform</button>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === '1:1' ? 'active' : ''}" data-aspect="1:1" onclick="setCropAspect('1:1')">1:1</button>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === '16:9' ? 'active' : ''}" data-aspect="16:9" onclick="setCropAspect('16:9')">16:9</button>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === '9:16' ? 'active' : ''}" data-aspect="9:16" onclick="setCropAspect('9:16')">9:16</button>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === '4:5' ? 'active' : ''}" data-aspect="4:5" onclick="setCropAspect('4:5')">4:5</button>
|
||
<button class="seg-pill crop-aspect-btn ${toolState.crop.aspect === '4:3' ? 'active' : ''}" data-aspect="4:3" onclick="setCropAspect('4:3')">4:3</button>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<button class="btn btn-secondary btn-sm" onclick="resetCropToFull()"><i class="fa-solid fa-expand"></i> Full Size</button>
|
||
<span class="label-val" id="opt-crop-size" style="margin-left: 6px;">--</span>
|
||
</div>
|
||
`,
|
||
resize: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Scale:</span>
|
||
<button class="seg-pill" onclick="scaleActiveImage(0.25)">25%</button>
|
||
<button class="seg-pill" onclick="scaleActiveImage(0.5)">50%</button>
|
||
<button class="seg-pill" onclick="scaleActiveImage(0.75)">75%</button>
|
||
<button class="seg-pill" onclick="scaleActiveImage(1.0)">100%</button>
|
||
<button class="seg-pill" onclick="scaleActiveImage(1.5)">150%</button>
|
||
<button class="seg-pill" onclick="scaleActiveImage(2.0)">200%</button>
|
||
</div>
|
||
`,
|
||
adjust: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Presets:</span>
|
||
<button class="seg-pill" onclick="applyColorPreset(0,0,0,1.0)">Reset</button>
|
||
<button class="seg-pill" onclick="applyColorPreset(5, 20, 25, 1.0)">Vivid</button>
|
||
<button class="seg-pill" onclick="applyColorPreset(-10, 25, -15, 0.9)">Cinematic</button>
|
||
<button class="seg-pill" onclick="applyColorPreset(0, 30, -100, 1.05)">B&W</button>
|
||
</div>
|
||
`,
|
||
filter: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Filter:</span>
|
||
<button class="seg-pill ${toolState.filter.filter==='BLUR'?'active':''}" onclick="setFilterQuick('BLUR')">Blur</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='SHARPEN'?'active':''}" onclick="setFilterQuick('SHARPEN')">Sharpen</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='GRAYSCALE'?'active':''}" onclick="setFilterQuick('GRAYSCALE')">Grayscale</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='SEPIA'?'active':''}" onclick="setFilterQuick('SEPIA')">Sepia</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='INVERT'?'active':''}" onclick="setFilterQuick('INVERT')">Invert</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='WARM'?'active':''}" onclick="setFilterQuick('WARM')">Warm</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='COOL'?'active':''}" onclick="setFilterQuick('COOL')">Cool</button>
|
||
<button class="seg-pill ${toolState.filter.filter==='VINTAGE'?'active':''}" onclick="setFilterQuick('VINTAGE')">Vintage</button>
|
||
</div>
|
||
`,
|
||
rotate: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Transform:</span>
|
||
<button class="seg-pill" onclick="setRotateQuick('90')"><i class="fa-solid fa-rotate-right"></i> 90° CW</button>
|
||
<button class="seg-pill" onclick="setRotateQuick('270')"><i class="fa-solid fa-rotate-left"></i> 90° CCW</button>
|
||
<button class="seg-pill" onclick="setRotateQuick('180')"><i class="fa-solid fa-arrows-rotate"></i> 180°</button>
|
||
<button class="seg-pill" onclick="setRotateQuick('FLIP_H')"><i class="fa-solid fa-arrows-left-right"></i> Flip H</button>
|
||
<button class="seg-pill" onclick="setRotateQuick('FLIP_V')"><i class="fa-solid fa-arrows-up-down"></i> Flip V</button>
|
||
</div>
|
||
`,
|
||
round_corners: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Radius:</span>
|
||
<input type="range" min="0" max="300" value="${toolState.round_corners.radius}" style="width: 120px;" oninput="updateRoundRadius(this.value)">
|
||
<span class="label-val" id="opt-round-val">${toolState.round_corners.radius}px</span>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<label style="display: flex; align-items: center; gap: 6px; cursor: pointer;">
|
||
<input type="checkbox" id="opt-circle-check" ${toolState.round_corners.is_circle ? 'checked' : ''} onchange="updateCircleAvatar(this.checked)">
|
||
<span>Circular Avatar</span>
|
||
</label>
|
||
</div>
|
||
`,
|
||
border: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Aspect Pad:</span>
|
||
<button class="seg-pill ${toolState.border.pad_aspect==='none'?'active':''}" onclick="setAspectPad('none')">None</button>
|
||
<button class="seg-pill ${toolState.border.pad_aspect==='1:1'?'active':''}" onclick="setAspectPad('1:1')">1:1 Square</button>
|
||
<button class="seg-pill ${toolState.border.pad_aspect==='4:5'?'active':''}" onclick="setAspectPad('4:5')">4:5 Portrait</button>
|
||
<button class="seg-pill ${toolState.border.pad_aspect==='16:9'?'active':''}" onclick="setAspectPad('16:9')">16:9</button>
|
||
<button class="seg-pill ${toolState.border.pad_aspect==='9:16'?'active':''}" onclick="setAspectPad('9:16')">9:16</button>
|
||
</div>
|
||
`,
|
||
watermark: `
|
||
<div class="ps-options-group">
|
||
<button class="btn btn-secondary btn-sm" onclick="triggerWatermarkPicker()"><i class="fa-solid fa-upload"></i> ${toolState.watermark.fileName || 'Choose Logo'}</button>
|
||
<span class="ps-options-label">Anchor:</span>
|
||
<button class="seg-pill ${toolState.watermark.position==='top_left'?'active':''}" onclick="setWmPos('top_left')">Top-Left</button>
|
||
<button class="seg-pill ${toolState.watermark.position==='top_right'?'active':''}" onclick="setWmPos('top_right')">Top-Right</button>
|
||
<button class="seg-pill ${toolState.watermark.position==='center'?'active':''}" onclick="setWmPos('center')">Center</button>
|
||
<button class="seg-pill ${toolState.watermark.position==='bottom_left'?'active':''}" onclick="setWmPos('bottom_left')">Bottom-Left</button>
|
||
<button class="seg-pill ${toolState.watermark.position==='bottom_right'?'active':''}" onclick="setWmPos('bottom_right')">Bottom-Right</button>
|
||
</div>
|
||
`,
|
||
masker: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Tool:</span>
|
||
<button class="seg-pill ${toolState.masker.mode === 'brush' ? 'active' : ''}" onclick="setMaskMode('brush')"><i class="fa-solid fa-paintbrush"></i> Brush</button>
|
||
<button class="seg-pill ${toolState.masker.mode === 'eraser' ? 'active' : ''}" onclick="setMaskMode('eraser')"><i class="fa-solid fa-eraser"></i> Eraser</button>
|
||
<button class="seg-pill ${toolState.masker.mode === 'rect' ? 'active' : ''}" onclick="setMaskMode('rect')"><i class="fa-regular fa-square"></i> Box</button>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Size:</span>
|
||
<input type="range" min="4" max="250" value="${toolState.masker.brush_size}" style="width: 100px;" oninput="setBrushSize(this.value)">
|
||
<span class="label-val" id="opt-brush-val">${toolState.masker.brush_size}px</span>
|
||
<button class="seg-pill" onclick="setBrushSize(15)">15px</button>
|
||
<button class="seg-pill" onclick="setBrushSize(40)">40px</button>
|
||
<button class="seg-pill" onclick="setBrushSize(90)">90px</button>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<button class="btn btn-secondary btn-sm" onclick="undoMaskStroke()" title="Undo Stroke"><i class="fa-solid fa-rotate-left"></i> Undo</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="redoMaskStroke()" title="Redo Stroke"><i class="fa-solid fa-rotate-right"></i> Redo</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="invertMask()" title="Invert Mask"><i class="fa-solid fa-circle-half-stroke"></i> Invert</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="fillMask()" title="Fill Whole Mask"><i class="fa-solid fa-fill-drip"></i> Fill</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="clearMaskStrokes()" title="Clear Mask"><i class="fa-solid fa-trash"></i> Clear</button>
|
||
</div>
|
||
`,
|
||
convert: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Format:</span>
|
||
<button class="seg-pill ${toolState.convert.format==='png'?'active':''}" onclick="setConvertFormat('png')">PNG</button>
|
||
<button class="seg-pill ${toolState.convert.format==='jpg'?'active':''}" onclick="setConvertFormat('jpg')">JPG</button>
|
||
<button class="seg-pill ${toolState.convert.format==='webp'?'active':''}" onclick="setConvertFormat('webp')">WEBP</button>
|
||
<button class="seg-pill ${toolState.convert.format==='avif'?'active':''}" onclick="setConvertFormat('avif')">AVIF</button>
|
||
<button class="seg-pill ${toolState.convert.format==='bmp'?'active':''}" onclick="setConvertFormat('bmp')">BMP</button>
|
||
<button class="seg-pill ${toolState.convert.format==='tiff'?'active':''}" onclick="setConvertFormat('tiff')">TIFF</button>
|
||
</div>
|
||
<div class="ps-options-group" id="opt-convert-q-group" style="${(toolState.convert.format==='webp'||toolState.convert.format==='jpg'||toolState.convert.format==='avif')?'display:flex;align-items:center;':'display:none;'}">
|
||
<span class="ps-options-label">Quality:</span>
|
||
<input type="range" min="50" max="100" value="${toolState.convert.quality}" style="width: 110px;" oninput="updateConvertQuality(this.value)">
|
||
<span class="label-val" id="opt-conv-val">${toolState.convert.quality}%</span>
|
||
<span style="font-size: 10px; color: var(--accent-cyan); font-family: var(--font-mono); margin-left: 4px;">${toolState.convert.quality>=95?'(High Res)':toolState.convert.quality>=85?'(Balanced)':'' }</span>
|
||
</div>
|
||
`,
|
||
compress: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Quality:</span>
|
||
<input type="range" min="10" max="95" value="${toolState.compress.quality}" style="width: 120px;" oninput="updateCompressQuality(this.value)">
|
||
<span class="label-val" id="opt-comp-val">${toolState.compress.quality}%</span>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<span id="opt-comp-sim" style="font-family: var(--font-mono); font-size: 11px; color: var(--accent-cyan);">Ready</span>
|
||
</div>
|
||
`,
|
||
strip_metadata: `
|
||
<div class="ps-options-group">
|
||
<span style="font-size: 11.5px; color: var(--accent-emerald); font-weight: 600;"><i class="fa-solid fa-shield-check"></i> Privacy Cleaner: EXIF, GPS, Serial Numbers Removed</span>
|
||
</div>
|
||
`
|
||
};
|
||
|
||
strip.innerHTML = configs[currentTool] || "";
|
||
}
|
||
|
||
function renderToolControls() {
|
||
const container = document.getElementById("inspector-tab-controls");
|
||
if (!container) return;
|
||
|
||
const cur = filesList[activeIndex];
|
||
const natW = cur ? cur.naturalW : 1920;
|
||
const natH = cur ? cur.naturalH : 1080;
|
||
|
||
const panels = {
|
||
crop: `
|
||
<div class="ps-section-title">Visual Crop Coordinates</div>
|
||
<div class="input-group">
|
||
<label>Aspect Ratio Constraint</label>
|
||
<select id="param-crop-aspect" onchange="setCropAspect(this.value)">
|
||
<option value="free" ${toolState.crop.aspect === "free" ? "selected" : ""}>Freeform</option>
|
||
<option value="1:1" ${toolState.crop.aspect === "1:1" ? "selected" : ""}>1:1 Square</option>
|
||
<option value="16:9" ${toolState.crop.aspect === "16:9" ? "selected" : ""}>16:9 Landscape</option>
|
||
<option value="9:16" ${toolState.crop.aspect === "9:16" ? "selected" : ""}>9:16 Vertical Story</option>
|
||
<option value="4:5" ${toolState.crop.aspect === "4:5" ? "selected" : ""}>4:5 Portrait</option>
|
||
<option value="4:3" ${toolState.crop.aspect === "4:3" ? "selected" : ""}>4:3 Standard</option>
|
||
<option value="3:2" ${toolState.crop.aspect === "3:2" ? "selected" : ""}>3:2 35mm</option>
|
||
</select>
|
||
</div>
|
||
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 12px; margin-top: 10px; font-size: 11.5px;">
|
||
<div style="color: var(--accent-cyan); font-weight: 600; margin-bottom: 4px;"><i class="fa-solid fa-hand-pointer"></i> Drag to Frame</div>
|
||
<p style="color: var(--text-3); margin: 0;">Drag directly on the image viewport or resize using the 8 boundary handles. When batch processing, the crop box is applied proportionally across all files.</p>
|
||
</div>
|
||
`,
|
||
resize: `
|
||
<div class="ps-section-title">Dimensions & Resampling</div>
|
||
<div class="grid-2" style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
|
||
<div class="input-group">
|
||
<label>Width (px)</label>
|
||
<input type="number" id="param-width" value="${toolState.resize.width || natW}" oninput="updateResizeWidth(this.value)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Height (px)</label>
|
||
<input type="number" id="param-height" value="${toolState.resize.height || natH}" oninput="updateResizeHeight(this.value)">
|
||
</div>
|
||
</div>
|
||
<div class="input-group">
|
||
<label style="cursor: pointer; display: flex; align-items: center; gap: 8px;">
|
||
<input type="checkbox" id="param-maintain" ${toolState.resize.maintain_aspect ? 'checked' : ''} onchange="toolState.resize.maintain_aspect=this.checked">
|
||
<span>Maintain Aspect Ratio</span>
|
||
</label>
|
||
</div>
|
||
`,
|
||
adjust: `
|
||
<div class="ps-section-title">Color Grading Sliders</div>
|
||
<div class="input-group">
|
||
<label>Brightness <span class="label-val" id="val-bri">${toolState.adjust.brightness}</span></label>
|
||
<input type="range" id="param-brightness" min="-100" max="100" value="${toolState.adjust.brightness}" oninput="updateAdjustParam('brightness', this.value, 'val-bri')">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Contrast <span class="label-val" id="val-con">${toolState.adjust.contrast}</span></label>
|
||
<input type="range" id="param-contrast" min="-100" max="100" value="${toolState.adjust.contrast}" oninput="updateAdjustParam('contrast', this.value, 'val-con')">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Saturation <span class="label-val" id="val-sat">${toolState.adjust.saturation}</span></label>
|
||
<input type="range" id="param-saturation" min="-100" max="100" value="${toolState.adjust.saturation}" oninput="updateAdjustParam('saturation', this.value, 'val-sat')">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Gamma Curve <span class="label-val" id="val-gam">${toolState.adjust.gamma}</span></label>
|
||
<input type="range" id="param-gamma" min="0.2" max="2.5" step="0.05" value="${toolState.adjust.gamma}" oninput="updateAdjustParam('gamma', this.value, 'val-gam')">
|
||
</div>
|
||
`,
|
||
filter: `
|
||
<div class="ps-section-title">Select Artistic Filter</div>
|
||
<div class="input-group">
|
||
<label>Filter Profile</label>
|
||
<select id="param-filter" onchange="toolState.filter.filter=this.value">
|
||
<option value="BLUR" ${toolState.filter.filter==='BLUR'?'selected':''}>Blur (Smooth 2.5px)</option>
|
||
<option value="SHARPEN" ${toolState.filter.filter==='SHARPEN'?'selected':''}>Sharpen (Crisp 2.0x)</option>
|
||
<option value="GRAYSCALE" ${toolState.filter.filter==='GRAYSCALE'?'selected':''}>Monochrome Grayscale</option>
|
||
<option value="SEPIA" ${toolState.filter.filter==='SEPIA'?'selected':''}>Classic Sepia</option>
|
||
<option value="INVERT" ${toolState.filter.filter==='INVERT'?'selected':''}>Invert Colors (Negative)</option>
|
||
<option value="EMBOSS" ${toolState.filter.filter==='EMBOSS'?'selected':''}>Emboss Relief</option>
|
||
<option value="CONTOUR" ${toolState.filter.filter==='CONTOUR'?'selected':''}>Edge Contour</option>
|
||
<option value="WARM" ${toolState.filter.filter==='WARM'?'selected':''}>Warm Golden Glow</option>
|
||
<option value="COOL" ${toolState.filter.filter==='COOL'?'selected':''}>Cool Cyan Chill</option>
|
||
<option value="VINTAGE" ${toolState.filter.filter==='VINTAGE'?'selected':''}>Vintage Analog Film</option>
|
||
</select>
|
||
</div>
|
||
`,
|
||
rotate: `
|
||
<div class="ps-section-title">Orientation & Angle</div>
|
||
<div class="input-group">
|
||
<label>Standard Transform</label>
|
||
<select id="param-operation" onchange="toolState.rotate.operation=this.value">
|
||
<option value="90" ${toolState.rotate.operation==='90'?'selected':''}>Rotate 90° CW</option>
|
||
<option value="180" ${toolState.rotate.operation==='180'?'selected':''}>Rotate 180°</option>
|
||
<option value="270" ${toolState.rotate.operation==='270'?'selected':''}>Rotate 270° CW (90° CCW)</option>
|
||
<option value="FLIP_H" ${toolState.rotate.operation==='FLIP_H'?'selected':''}>Flip Horizontal</option>
|
||
<option value="FLIP_V" ${toolState.rotate.operation==='FLIP_V'?'selected':''}>Flip Vertical</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group" style="margin-top: 10px;">
|
||
<label>Custom Angle Slider <span class="label-val" id="val-angle">${toolState.rotate.angle}°</span></label>
|
||
<input type="range" id="param-angle" min="-180" max="180" value="${toolState.rotate.angle}" oninput="updateRotateAngle(this.value)">
|
||
</div>
|
||
`,
|
||
round_corners: `
|
||
<div class="ps-section-title">Corner Geometry</div>
|
||
<div class="input-group">
|
||
<label>Corner Radius (px) <span class="label-val" id="val-radius">${toolState.round_corners.radius}px</span></label>
|
||
<input type="range" id="param-radius" min="0" max="400" value="${toolState.round_corners.radius}" oninput="updateRoundRadius(this.value)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label style="cursor: pointer; display: flex; align-items: center; gap: 8px;">
|
||
<input type="checkbox" id="param-circle" ${toolState.round_corners.is_circle ? 'checked' : ''} onchange="updateCircleAvatar(this.checked)">
|
||
<span>Circular Avatar Crop (Clipped to Circle)</span>
|
||
</label>
|
||
</div>
|
||
`,
|
||
border: `
|
||
<div class="ps-section-title">Border & Canvas Framing</div>
|
||
<div class="input-group">
|
||
<label>Border Thickness (px) <span class="label-val" id="val-bwidth">${toolState.border.border_width}px</span></label>
|
||
<input type="range" id="param-border-width" min="1" max="200" value="${toolState.border.border_width}" oninput="updateBorderWidth(this.value)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Border Color</label>
|
||
<div style="display: flex; gap: 8px; align-items: center;">
|
||
<input type="color" id="param-border-color" value="${toolState.border.border_color}" onchange="setCustomBorderColor(this.value)" style="width: 44px; height: 36px; padding: 2px;">
|
||
<input type="text" id="param-border-color-hex" value="${toolState.border.border_color}" oninput="setCustomBorderColor(this.value)" style="flex: 1;">
|
||
</div>
|
||
<div class="color-swatches-row">
|
||
<div class="color-swatch" style="background:#ffffff;" onclick="setCustomBorderColor('#ffffff')"></div>
|
||
<div class="color-swatch" style="background:#000000;" onclick="setCustomBorderColor('#000000')"></div>
|
||
<div class="color-swatch" style="background:#8b5cf6;" onclick="setCustomBorderColor('#8b5cf6')"></div>
|
||
<div class="color-swatch" style="background:#38bdf8;" onclick="setCustomBorderColor('#38bdf8')"></div>
|
||
<div class="color-swatch" style="background:#a855f7;" onclick="setCustomBorderColor('#a855f7')"></div>
|
||
<div class="color-swatch" style="background:#10b981;" onclick="setCustomBorderColor('#10b981')"></div>
|
||
</div>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Canvas Pad Aspect Ratio</label>
|
||
<select id="param-pad-aspect" onchange="toolState.border.pad_aspect=this.value">
|
||
<option value="none" ${toolState.border.pad_aspect==='none'?'selected':''}>None (Uniform Border)</option>
|
||
<option value="1:1" ${toolState.border.pad_aspect==='1:1'?'selected':''}>1:1 Square Canvas</option>
|
||
<option value="4:5" ${toolState.border.pad_aspect==='4:5'?'selected':''}>4:5 Instagram Portrait</option>
|
||
<option value="16:9" ${toolState.border.pad_aspect==='16:9'?'selected':''}>16:9 Video Canvas</option>
|
||
<option value="9:16" ${toolState.border.pad_aspect==='9:16'?'selected':''}>9:16 Story / Reels Canvas</option>
|
||
<option value="4:3" ${toolState.border.pad_aspect==='4:3'?'selected':''}>4:3 Standard Canvas</option>
|
||
</select>
|
||
</div>
|
||
`,
|
||
watermark: `
|
||
<div class="ps-section-title">Watermark Stamp</div>
|
||
<div class="input-group">
|
||
<label>Choose Logo / Watermark Image</label>
|
||
<input type="file" id="param-watermark-file" accept="image/*" onchange="cacheWatermarkFile(this)">
|
||
<span style="font-size: 11px; color: var(--accent-cyan); margin-top: 4px;" id="val-wm-file">${toolState.watermark.fileName || 'No file selected yet'}</span>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Position</label>
|
||
<select id="param-position" onchange="toolState.watermark.position=this.value">
|
||
<option value="bottom_right" ${toolState.watermark.position==='bottom_right'?'selected':''}>Bottom Right</option>
|
||
<option value="bottom_left" ${toolState.watermark.position==='bottom_left'?'selected':''}>Bottom Left</option>
|
||
<option value="top_right" ${toolState.watermark.position==='top_right'?'selected':''}>Top Right</option>
|
||
<option value="top_left" ${toolState.watermark.position==='top_left'?'selected':''}>Top Left</option>
|
||
<option value="center" ${toolState.watermark.position==='center'?'selected':''}>Center</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Opacity (%) <span class="label-val" id="val-wm-op">${toolState.watermark.opacity}%</span></label>
|
||
<input type="range" id="param-opacity" min="5" max="100" value="${toolState.watermark.opacity}" oninput="updateWatermarkOpacity(this.value)">
|
||
</div>
|
||
`,
|
||
masker: `
|
||
<div class="ps-section-title">Inpainting Mask & Pro Brush</div>
|
||
<div class="input-group">
|
||
<label>Brush Mode</label>
|
||
<div class="seg-pills-row">
|
||
<button class="seg-pill ${toolState.masker.mode === 'brush' ? 'active' : ''}" onclick="setMaskMode('brush')"><i class="fa-solid fa-paintbrush"></i> Brush</button>
|
||
<button class="seg-pill ${toolState.masker.mode === 'eraser' ? 'active' : ''}" onclick="setMaskMode('eraser')"><i class="fa-solid fa-eraser"></i> Eraser</button>
|
||
<button class="seg-pill ${toolState.masker.mode === 'rect' ? 'active' : ''}" onclick="setMaskMode('rect')"><i class="fa-regular fa-square"></i> Box Marquee</button>
|
||
</div>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Brush Diameter <span class="label-val" id="val-brush-sz">${toolState.masker.brush_size}px</span></label>
|
||
<input type="range" min="4" max="250" value="${toolState.masker.brush_size}" oninput="setBrushSize(this.value)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Mask Overlay Tint</label>
|
||
<div class="seg-pills-row">
|
||
<button class="seg-pill" style="border-color: rgba(244, 63, 94, 0.6); color: #f43f5e;" onclick="setMaskColor('rgba(244, 63, 94, 0.70)')">Ruby Red</button>
|
||
<button class="seg-pill" style="border-color: rgba(56, 189, 248, 0.6); color: #38bdf8;" onclick="setMaskColor('rgba(56, 189, 248, 0.70)')">Ice Cyan</button>
|
||
<button class="seg-pill" style="border-color: rgba(16, 185, 129, 0.6); color: #10b981;" onclick="setMaskColor('rgba(16, 185, 129, 0.70)')">Emerald</button>
|
||
</div>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Quick Actions</label>
|
||
<div style="display: grid; grid-template-columns: 1fr 1fr; gap: 6px; margin-top: 4px;">
|
||
<button class="btn btn-secondary btn-sm" onclick="invertMask()"><i class="fa-solid fa-circle-half-stroke"></i> Invert</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="fillMask()"><i class="fa-solid fa-fill-drip"></i> Fill Image</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="undoMaskStroke()"><i class="fa-solid fa-rotate-left"></i> Undo</button>
|
||
<button class="btn btn-secondary btn-sm" onclick="redoMaskStroke()"><i class="fa-solid fa-rotate-right"></i> Redo</button>
|
||
</div>
|
||
</div>
|
||
<div style="margin-top: 10px;">
|
||
<button class="btn btn-secondary btn-sm" style="width: 100%;" onclick="exportMaskOnly()">
|
||
<i class="fa-solid fa-download"></i> Download Binary Mask PNG
|
||
</button>
|
||
</div>
|
||
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 12px; margin-top: 10px; font-size: 11px;">
|
||
<p style="color: var(--text-3); margin: 0;"><i class="fa-solid fa-circle-info" style="color: var(--accent-cyan);"></i> Inpaint Masker paints a pixel-perfect rubylith mask directly over your image. Drawing generates a solid-white binary mask on a pitch-black canvas.</p>
|
||
</div>
|
||
`,
|
||
convert: `
|
||
<div class="ps-section-title">Transcode Format</div>
|
||
<div class="input-group">
|
||
<label>Target Extension</label>
|
||
<select id="param-format" onchange="toolState.convert.format=this.value; renderToolOptions();">
|
||
<option value="png" ${toolState.convert.format==='png'?'selected':''}>PNG (Lossless)</option>
|
||
<option value="jpg" ${toolState.convert.format==='jpg'?'selected':''}>JPG (Standard Web)</option>
|
||
<option value="webp" ${toolState.convert.format==='webp'?'selected':''}>WEBP (High Efficiency & Crisp)</option>
|
||
<option value="avif" ${toolState.convert.format==='avif'?'selected':''}>AVIF (Modern Ultra-Compressed)</option>
|
||
<option value="bmp" ${toolState.convert.format==='bmp'?'selected':''}>BMP (Windows Bitmap)</option>
|
||
<option value="tiff" ${toolState.convert.format==='tiff'?'selected':''}>TIFF (Print Master)</option>
|
||
<option value="ico" ${toolState.convert.format==='ico'?'selected':''}>ICO (Windows Icon)</option>
|
||
<option value="heic" ${toolState.convert.format==='heic'?'selected':''}>HEIC (Apple High Efficiency)</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Quality Profile (1-100) <span class="label-val" id="val-conv-q">${toolState.convert.quality}%</span></label>
|
||
<input type="range" id="param-quality" min="1" max="100" value="${toolState.convert.quality}" oninput="updateConvertQuality(this.value)">
|
||
</div>
|
||
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 10px; font-size: 11px; color: var(--text-3); line-height: 1.4;">
|
||
<i class="fa-solid fa-circle-check" style="color: var(--accent-emerald);"></i> <b>Crisp WebP Transcoding:</b> Powered by Google's native <code>cwebp</code> engine with Sharp-YUV color preservation. Retains full resolution and fine texture without blur (quality 92–98 recommended, 100 for lossless).
|
||
</div>
|
||
`,
|
||
compress: `
|
||
<div class="ps-section-title">Compression Engine</div>
|
||
<div class="input-group">
|
||
<label>Output Format</label>
|
||
<select id="param-format" onchange="updateCompressFormat(this.value)">
|
||
<option value="original" ${toolState.compress.format==='original'?'selected':''}>Preserve Original Format</option>
|
||
<option value="webp" ${toolState.compress.format==='webp'?'selected':''}>WEBP (High Efficiency & Crisp)</option>
|
||
<option value="jpg" ${toolState.compress.format==='jpg'?'selected':''}>JPG (Web Optimized)</option>
|
||
<option value="png" ${toolState.compress.format==='png'?'selected':''}>PNG (Lossless Graphics)</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Quality Threshold <span class="label-val" id="val-comp-q">${toolState.compress.quality}%</span></label>
|
||
<input type="range" id="param-quality" min="5" max="95" value="${toolState.compress.quality}" oninput="updateCompressQuality(this.value)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Target Size Per File (MB) <small style="color:var(--text-muted);">(Optional)</small></label>
|
||
<input type="number" id="param-target-size-mb" placeholder="e.g. 1.5" step="0.1" min="0.1" value="${toolState.compress.target_size_mb || ''}" oninput="toolState.compress.target_size_mb=parseFloat(this.value)||0">
|
||
</div>
|
||
<div id="inspector-comp-box" style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 12px; margin-top: 10px; font-size: 11.5px;">
|
||
<div style="display:flex; justify-content:space-between; margin-bottom:6px;">
|
||
<span style="color:var(--text-3);">Original Size:</span>
|
||
<span id="stat-orig-sz" style="color:#fff; font-family:var(--font-mono);">--</span>
|
||
</div>
|
||
<div style="display:flex; justify-content:space-between; margin-bottom:6px;">
|
||
<span style="color:var(--text-3);">Estimated Output:</span>
|
||
<span id="stat-new-sz" style="color:var(--accent-cyan); font-weight:700; font-family:var(--font-mono);">--</span>
|
||
</div>
|
||
<div style="text-align:right; color:var(--accent-emerald); font-weight:700;" id="stat-red-pct">
|
||
Reduction: --
|
||
</div>
|
||
</div>
|
||
`,
|
||
strip_metadata: `
|
||
<div class="ps-section-title">EXIF Privacy Cleaner</div>
|
||
<div class="input-group">
|
||
<label>Target Format</label>
|
||
<select id="param-format" onchange="toolState.strip_metadata.format=this.value">
|
||
<option value="original" ${toolState.strip_metadata.format==='original'?'selected':''}>Preserve Original Extension</option>
|
||
<option value="jpg" ${toolState.strip_metadata.format==='jpg'?'selected':''}>Convert to Clean JPG</option>
|
||
<option value="png" ${toolState.strip_metadata.format==='png'?'selected':''}>Convert to Clean PNG</option>
|
||
<option value="webp" ${toolState.strip_metadata.format==='webp'?'selected':''}>Convert to Clean WEBP</option>
|
||
</select>
|
||
</div>
|
||
<div style="background: var(--bg-input); border: 1px solid var(--border-1); border-radius: var(--r-md); padding: 14px; margin-top: 10px; font-size: 11.5px; display:flex; flex-direction:column; gap:6px;">
|
||
<div style="color:var(--accent-emerald); font-weight:700;"><i class="fa-solid fa-check-double"></i> Cleans All Hidden Metadata:</div>
|
||
<div style="color:var(--text-3);">• GPS Geolocation Coordinates</div>
|
||
<div style="color:var(--text-3);">• Camera Model, Serial Number & Lens</div>
|
||
<div style="color:var(--text-3);">• Creation Date, Exposure & Shutter Speeds</div>
|
||
<div style="color:var(--text-3);">• Embedded Thumbnails & Author Tags</div>
|
||
</div>
|
||
`
|
||
};
|
||
|
||
container.innerHTML = panels[currentTool] || "";
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// STATE MUTATORS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function updateResizeWidth(val) {
|
||
const w = parseInt(val, 10) || 0;
|
||
toolState.resize.width = w;
|
||
if (toolState.resize.maintain_aspect && filesList[activeIndex]) {
|
||
const cur = filesList[activeIndex];
|
||
const h = Math.round(w * (cur.naturalH / cur.naturalW));
|
||
toolState.resize.height = h;
|
||
const hIn = document.getElementById("param-height");
|
||
if (hIn) hIn.value = h;
|
||
}
|
||
}
|
||
window.updateResizeWidth = updateResizeWidth;
|
||
|
||
function updateResizeHeight(val) {
|
||
const h = parseInt(val, 10) || 0;
|
||
toolState.resize.height = h;
|
||
if (toolState.resize.maintain_aspect && filesList[activeIndex]) {
|
||
const cur = filesList[activeIndex];
|
||
const w = Math.round(h * (cur.naturalW / cur.naturalH));
|
||
toolState.resize.width = w;
|
||
const wIn = document.getElementById("param-width");
|
||
if (wIn) wIn.value = w;
|
||
}
|
||
}
|
||
window.updateResizeHeight = updateResizeHeight;
|
||
|
||
function scaleActiveImage(factor) {
|
||
const cur = filesList[activeIndex];
|
||
if (!cur) return;
|
||
const w = Math.round(cur.naturalW * factor);
|
||
const h = Math.round(cur.naturalH * factor);
|
||
toolState.resize.width = w;
|
||
toolState.resize.height = h;
|
||
const wIn = document.getElementById("param-width");
|
||
const hIn = document.getElementById("param-height");
|
||
if (wIn) wIn.value = w;
|
||
if (hIn) hIn.value = h;
|
||
showToast(`Scaled to ${Math.round(factor * 100)}% (${w}×${h} px)`, "info");
|
||
}
|
||
window.scaleActiveImage = scaleActiveImage;
|
||
|
||
function updateAdjustParam(key, val, labelId) {
|
||
toolState.adjust[key] = parseFloat(val);
|
||
const l = document.getElementById(labelId);
|
||
if (l) l.innerText = val;
|
||
}
|
||
window.updateAdjustParam = updateAdjustParam;
|
||
|
||
function applyColorPreset(bri, con, sat, gam) {
|
||
toolState.adjust.brightness = bri;
|
||
toolState.adjust.contrast = con;
|
||
toolState.adjust.saturation = sat;
|
||
toolState.adjust.gamma = gam;
|
||
|
||
const bIn = document.getElementById("param-brightness");
|
||
const cIn = document.getElementById("param-contrast");
|
||
const sIn = document.getElementById("param-saturation");
|
||
const gIn = document.getElementById("param-gamma");
|
||
|
||
if (bIn) { bIn.value = bri; document.getElementById("val-bri").innerText = bri; }
|
||
if (cIn) { cIn.value = con; document.getElementById("val-con").innerText = con; }
|
||
if (sIn) { sIn.value = sat; document.getElementById("val-sat").innerText = sat; }
|
||
if (gIn) { gIn.value = gam; document.getElementById("val-gam").innerText = gam; }
|
||
showToast("Preset applied", "info");
|
||
}
|
||
window.applyColorPreset = applyColorPreset;
|
||
|
||
function setFilterQuick(name) {
|
||
toolState.filter.filter = name;
|
||
const fSelect = document.getElementById("param-filter");
|
||
if (fSelect) fSelect.value = name;
|
||
renderToolOptions();
|
||
executeActiveImage();
|
||
}
|
||
window.setFilterQuick = setFilterQuick;
|
||
|
||
function setRotateQuick(op) {
|
||
toolState.rotate.operation = op;
|
||
const opSelect = document.getElementById("param-operation");
|
||
if (opSelect) opSelect.value = op;
|
||
executeActiveImage();
|
||
}
|
||
window.setRotateQuick = setRotateQuick;
|
||
|
||
function updateRotateAngle(val) {
|
||
toolState.rotate.angle = parseInt(val, 10);
|
||
toolState.rotate.operation = val;
|
||
const l = document.getElementById("val-angle");
|
||
if (l) l.innerText = `${val}°`;
|
||
const op = document.getElementById("param-operation");
|
||
if (op && val !== "0") op.value = val;
|
||
}
|
||
window.updateRotateAngle = updateRotateAngle;
|
||
|
||
function updateRoundRadius(val) {
|
||
const r = parseInt(val, 10);
|
||
toolState.round_corners.radius = r;
|
||
const l1 = document.getElementById("val-radius");
|
||
const l2 = document.getElementById("opt-round-val");
|
||
if (l1) l1.innerText = `${r}px`;
|
||
if (l2) l2.innerText = `${r}px`;
|
||
}
|
||
window.updateRoundRadius = updateRoundRadius;
|
||
|
||
function updateCircleAvatar(checked) {
|
||
toolState.round_corners.is_circle = checked;
|
||
const chk1 = document.getElementById("param-circle");
|
||
const chk2 = document.getElementById("opt-circle-check");
|
||
if (chk1) chk1.checked = checked;
|
||
if (chk2) chk2.checked = checked;
|
||
}
|
||
window.updateCircleAvatar = updateCircleAvatar;
|
||
|
||
function updateBorderWidth(val) {
|
||
const bw = parseInt(val, 10);
|
||
toolState.border.border_width = bw;
|
||
const l = document.getElementById("val-bwidth");
|
||
if (l) l.innerText = `${bw}px`;
|
||
}
|
||
window.updateBorderWidth = updateBorderWidth;
|
||
|
||
function setCustomBorderColor(hex) {
|
||
toolState.border.border_color = hex;
|
||
const cPicker = document.getElementById("param-border-color");
|
||
const cHex = document.getElementById("param-border-color-hex");
|
||
if (cPicker) cPicker.value = hex;
|
||
if (cHex) cHex.value = hex;
|
||
}
|
||
window.setCustomBorderColor = setCustomBorderColor;
|
||
|
||
function setAspectPad(pad) {
|
||
toolState.border.pad_aspect = pad;
|
||
const pSelect = document.getElementById("param-pad-aspect");
|
||
if (pSelect) pSelect.value = pad;
|
||
renderToolOptions();
|
||
}
|
||
window.setAspectPad = setAspectPad;
|
||
|
||
function triggerWatermarkPicker() {
|
||
const fileInput = document.getElementById("param-watermark-file");
|
||
if (fileInput) fileInput.click();
|
||
}
|
||
window.triggerWatermarkPicker = triggerWatermarkPicker;
|
||
|
||
function cacheWatermarkFile(input) {
|
||
if (input.files && input.files[0]) {
|
||
const file = input.files[0];
|
||
toolState.watermark.fileName = file.name;
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
toolState.watermark.base64 = e.target.result;
|
||
const fLabel = document.getElementById("val-wm-file");
|
||
if (fLabel) fLabel.innerText = file.name;
|
||
renderToolOptions();
|
||
showToast(`Watermark selected: ${file.name}`, "success");
|
||
};
|
||
reader.readAsDataURL(file);
|
||
}
|
||
}
|
||
window.cacheWatermarkFile = cacheWatermarkFile;
|
||
|
||
function setWmPos(pos) {
|
||
toolState.watermark.position = pos;
|
||
const pSelect = document.getElementById("param-position");
|
||
if (pSelect) pSelect.value = pos;
|
||
renderToolOptions();
|
||
}
|
||
window.setWmPos = setWmPos;
|
||
|
||
function updateWatermarkOpacity(val) {
|
||
const op = parseInt(val, 10);
|
||
toolState.watermark.opacity = op;
|
||
const l = document.getElementById("val-wm-op");
|
||
if (l) l.innerText = `${op}%`;
|
||
}
|
||
window.updateWatermarkOpacity = updateWatermarkOpacity;
|
||
|
||
function setConvertFormat(fmt) {
|
||
toolState.convert.format = fmt;
|
||
const fSelect = document.getElementById("param-format");
|
||
if (fSelect) fSelect.value = fmt;
|
||
renderToolOptions();
|
||
}
|
||
window.setConvertFormat = setConvertFormat;
|
||
|
||
function updateConvertQuality(val) {
|
||
const q = parseInt(val, 10);
|
||
toolState.convert.quality = q;
|
||
const l = document.getElementById("val-conv-q");
|
||
if (l) l.innerText = `${q}%`;
|
||
const lOpt = document.getElementById("opt-conv-val");
|
||
if (lOpt) lOpt.innerText = `${q}%`;
|
||
const pQ = document.getElementById("param-quality");
|
||
if (pQ && pQ.value != q) pQ.value = q;
|
||
}
|
||
window.updateConvertQuality = updateConvertQuality;
|
||
|
||
function updateCompressFormat(fmt) {
|
||
toolState.compress.format = fmt;
|
||
simulateCompressionDebounced();
|
||
}
|
||
window.updateCompressFormat = updateCompressFormat;
|
||
|
||
function updateCompressQuality(val) {
|
||
const q = parseInt(val, 10);
|
||
toolState.compress.quality = q;
|
||
const l1 = document.getElementById("val-comp-q");
|
||
const l2 = document.getElementById("opt-comp-val");
|
||
if (l1) l1.innerText = `${q}%`;
|
||
if (l2) l2.innerText = `${q}%`;
|
||
simulateCompressionDebounced();
|
||
}
|
||
window.updateCompressQuality = updateCompressQuality;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// COMPRESSION SIMULATION
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let simDebounceTimer;
|
||
function simulateCompressionDebounced() {
|
||
clearTimeout(simDebounceTimer);
|
||
simDebounceTimer = setTimeout(simulateCompression, 350);
|
||
}
|
||
|
||
async function simulateCompression() {
|
||
if (currentTool !== "compress" || filesList.length === 0) return;
|
||
const current = filesList[activeIndex];
|
||
if (!current) return;
|
||
|
||
const quality = toolState.compress.quality.toString();
|
||
const format = toolState.compress.format;
|
||
|
||
const statOrig = document.getElementById("stat-orig-sz");
|
||
const statNew = document.getElementById("stat-new-sz");
|
||
const statRed = document.getElementById("stat-red-pct");
|
||
const optSim = document.getElementById("opt-comp-sim");
|
||
|
||
if (statNew) statNew.textContent = "Calculating...";
|
||
if (optSim) optSim.textContent = "Calculating...";
|
||
|
||
try {
|
||
const formData = new FormData();
|
||
formData.append("image", current.file);
|
||
formData.append("quality", quality);
|
||
formData.append("format", format);
|
||
|
||
const res = await fetch(getApiUrl("/simulate-compression"), {
|
||
method: "POST",
|
||
body: formData
|
||
});
|
||
const data = await res.json();
|
||
|
||
if (data.original_size) {
|
||
const toMb = (b) => (b / (1024 * 1024)).toFixed(2) + " MB";
|
||
const toKb = (b) => (b / 1024).toFixed(0) + " KB";
|
||
const fmtSz = (s) => (s > 1024 * 1024 ? toMb(s) : toKb(s));
|
||
|
||
const origStr = fmtSz(data.original_size);
|
||
const newStr = fmtSz(data.new_size);
|
||
const redStr = `-${data.reduction.toFixed(1)}%`;
|
||
|
||
if (statOrig) statOrig.textContent = origStr;
|
||
if (statNew) statNew.textContent = newStr;
|
||
if (statRed) statRed.textContent = `Reduction: ${redStr}`;
|
||
if (optSim) optSim.textContent = `${origStr} → ${newStr} (${redStr})`;
|
||
}
|
||
} catch (err) {
|
||
if (statNew) statNew.textContent = "Error";
|
||
if (optSim) optSim.textContent = "Error";
|
||
}
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// EXECUTE ACTIVE IMAGE (Single Operation)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
async function executeActiveImage() {
|
||
if (!filesList || filesList.length === 0) {
|
||
showToast("Please open an image first", "error");
|
||
return;
|
||
}
|
||
|
||
const current = filesList[activeIndex];
|
||
if (!current) return;
|
||
|
||
// Masker Special Case
|
||
if (currentTool === "masker") {
|
||
const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH);
|
||
if (!maskDataUrl) {
|
||
showToast("Please paint a mask over the object first", "error");
|
||
return;
|
||
}
|
||
|
||
const maskBlob = await (await fetch(maskDataUrl)).blob();
|
||
const fData = new FormData();
|
||
fData.append("images", maskBlob, "mask.png");
|
||
await executeEndpointRequest("/mask", fData);
|
||
return;
|
||
}
|
||
|
||
const formData = new FormData();
|
||
formData.append("images", current.file);
|
||
|
||
if (currentTool === "crop") {
|
||
const img = document.getElementById("ps-active-img");
|
||
const imgW = img ? img.clientWidth : current.naturalW;
|
||
const imgH = img ? img.clientHeight : current.naturalH;
|
||
|
||
let { x, y, w, h } = toolState.crop;
|
||
if (!w || !h || w <= 0 || h <= 0) {
|
||
x = 0; y = 0; w = imgW; h = imgH;
|
||
}
|
||
|
||
const scaleX = current.naturalW / imgW;
|
||
const scaleY = current.naturalH / imgH;
|
||
|
||
const l = Math.max(0, Math.round(x * scaleX));
|
||
const t = Math.max(0, Math.round(y * scaleY));
|
||
const r = Math.min(current.naturalW, Math.round((x + w) * scaleX));
|
||
const b = Math.min(current.naturalH, Math.round((y + h) * scaleY));
|
||
|
||
const lPct = (x / imgW) * 100;
|
||
const tPct = (y / imgH) * 100;
|
||
const rPct = ((x + w) / imgW) * 100;
|
||
const bPct = ((y + h) / imgH) * 100;
|
||
|
||
formData.append("left", l.toString());
|
||
formData.append("top", t.toString());
|
||
formData.append("right", r.toString());
|
||
formData.append("bottom", b.toString());
|
||
formData.append("left_pct", lPct.toString());
|
||
formData.append("top_pct", tPct.toString());
|
||
formData.append("right_pct", rPct.toString());
|
||
formData.append("bottom_pct", bPct.toString());
|
||
} else if (currentTool === "resize") {
|
||
const w = toolState.resize.width || current.naturalW;
|
||
const h = toolState.resize.height || current.naturalH;
|
||
formData.append("width", w.toString());
|
||
formData.append("height", h.toString());
|
||
formData.append("maintain_aspect", toolState.resize.maintain_aspect ? "true" : "false");
|
||
} else if (currentTool === "adjust") {
|
||
formData.append("brightness", toolState.adjust.brightness.toString());
|
||
formData.append("contrast", toolState.adjust.contrast.toString());
|
||
formData.append("saturation", toolState.adjust.saturation.toString());
|
||
formData.append("gamma", toolState.adjust.gamma.toString());
|
||
} else if (currentTool === "filter") {
|
||
formData.append("filter", toolState.filter.filter);
|
||
} else if (currentTool === "rotate") {
|
||
formData.append("operation", toolState.rotate.operation);
|
||
} else if (currentTool === "round_corners") {
|
||
formData.append("radius", toolState.round_corners.radius.toString());
|
||
formData.append("is_circle", toolState.round_corners.is_circle ? "true" : "false");
|
||
} else if (currentTool === "border") {
|
||
formData.append("border_width", toolState.border.border_width.toString());
|
||
formData.append("border_color", toolState.border.border_color);
|
||
formData.append("pad_aspect", toolState.border.pad_aspect);
|
||
} else if (currentTool === "watermark") {
|
||
const wmFile = document.getElementById("param-watermark-file")?.files[0];
|
||
if (wmFile) {
|
||
formData.append("watermark", wmFile);
|
||
} else if (toolState.watermark.base64) {
|
||
formData.append("watermark_base64", toolState.watermark.base64);
|
||
} else {
|
||
showToast("Please choose a watermark image first", "error");
|
||
return;
|
||
}
|
||
formData.append("position", toolState.watermark.position);
|
||
formData.append("opacity", toolState.watermark.opacity.toString());
|
||
} else if (currentTool === "convert") {
|
||
formData.append("format", toolState.convert.format);
|
||
formData.append("quality", toolState.convert.quality.toString());
|
||
} else if (currentTool === "compress") {
|
||
formData.append("format", toolState.compress.format);
|
||
formData.append("quality", toolState.compress.quality.toString());
|
||
if (toolState.compress.target_size_mb > 0) {
|
||
formData.append("target_size_mb", toolState.compress.target_size_mb.toString());
|
||
}
|
||
} else if (currentTool === "strip_metadata") {
|
||
formData.append("format", toolState.strip_metadata.format);
|
||
formData.append("quality", "95");
|
||
}
|
||
|
||
const endpoint = currentTool === "round_corners" ? "/round-corners" :
|
||
currentTool === "strip_metadata" ? "/strip-metadata" :
|
||
`/${currentTool}`;
|
||
|
||
await executeEndpointRequest(endpoint, formData);
|
||
}
|
||
window.executeActiveImage = executeActiveImage;
|
||
|
||
async function executeEndpointRequest(endpoint, formData) {
|
||
showToast("Processing image...", "info");
|
||
try {
|
||
const res = await fetch(getApiUrl(endpoint), {
|
||
method: "POST",
|
||
body: formData
|
||
});
|
||
const data = await res.json();
|
||
|
||
if (res.ok && data.results && data.results.length > 0) {
|
||
const resItem = data.results[0];
|
||
const cur = filesList[activeIndex];
|
||
|
||
// Update current active image in place
|
||
cur.dataUrl = resItem.image;
|
||
if (resItem.info) {
|
||
cur.naturalW = resItem.info.width;
|
||
cur.naturalH = resItem.info.height;
|
||
}
|
||
|
||
// Re-convert data URI to Blob to update File reference
|
||
const blob = await (await fetch(resItem.image)).blob();
|
||
cur.file = new File([blob], resItem.filename || cur.name, { type: blob.type });
|
||
cur.size = blob.size;
|
||
|
||
pushHistorySnapshot(currentTool.toUpperCase() + " applied", resItem.image, cur.naturalW, cur.naturalH);
|
||
renderActiveImage();
|
||
updateSplitImages();
|
||
showToast("Transformation applied successfully!", "success");
|
||
} else {
|
||
showToast(data.error || "Transformation failed", "error");
|
||
}
|
||
} catch (err) {
|
||
showToast(`Network error: ${err.message}`, "error");
|
||
}
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// EXECUTE BATCH ALL (Universal Batch Across All Tools)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
async function executeBatchAll() {
|
||
if (!filesList || filesList.length === 0) {
|
||
showToast("No images to process", "error");
|
||
return;
|
||
}
|
||
|
||
// Open modal
|
||
openBatchModal();
|
||
logBatchConsole(`Starting batch execution for tool: [${currentTool.toUpperCase()}] across ${filesList.length} files...`);
|
||
|
||
// Build parameters object for batch
|
||
const params = {};
|
||
const current = filesList[activeIndex] || filesList[0];
|
||
|
||
if (currentTool === "crop") {
|
||
const img = document.getElementById("ps-active-img");
|
||
const imgW = img ? img.clientWidth : current.naturalW;
|
||
const imgH = img ? img.clientHeight : current.naturalH;
|
||
|
||
let { x, y, w, h } = toolState.crop;
|
||
if (!w || !h || w <= 0 || h <= 0) {
|
||
x = 0; y = 0; w = imgW; h = imgH;
|
||
}
|
||
|
||
params.left_pct = (x / imgW) * 100;
|
||
params.top_pct = (y / imgH) * 100;
|
||
params.right_pct = ((x + w) / imgW) * 100;
|
||
params.bottom_pct = ((y + h) / imgH) * 100;
|
||
} else if (currentTool === "resize") {
|
||
params.width = toolState.resize.width || current.naturalW;
|
||
params.height = toolState.resize.height || current.naturalH;
|
||
params.maintain_aspect = toolState.resize.maintain_aspect;
|
||
} else if (currentTool === "adjust") {
|
||
params.brightness = toolState.adjust.brightness;
|
||
params.contrast = toolState.adjust.contrast;
|
||
params.saturation = toolState.adjust.saturation;
|
||
params.gamma = toolState.adjust.gamma;
|
||
} else if (currentTool === "filter") {
|
||
params.filter = toolState.filter.filter;
|
||
} else if (currentTool === "rotate") {
|
||
params.operation = toolState.rotate.operation;
|
||
} else if (currentTool === "round_corners") {
|
||
params.radius = toolState.round_corners.radius;
|
||
params.is_circle = toolState.round_corners.is_circle;
|
||
} else if (currentTool === "border") {
|
||
params.border_width = toolState.border.border_width;
|
||
params.border_color = toolState.border.border_color;
|
||
params.pad_aspect = toolState.border.pad_aspect;
|
||
} else if (currentTool === "watermark") {
|
||
if (toolState.watermark.base64) {
|
||
params.watermark_base64 = toolState.watermark.base64;
|
||
}
|
||
params.position = toolState.watermark.position;
|
||
params.opacity = toolState.watermark.opacity;
|
||
} else if (currentTool === "masker") {
|
||
const maskDataUrl = generateMaskDataUrl(current.naturalW, current.naturalH);
|
||
if (maskDataUrl) {
|
||
params.mask_base64 = maskDataUrl;
|
||
}
|
||
} else if (currentTool === "convert") {
|
||
params.format = toolState.convert.format;
|
||
params.quality = toolState.convert.quality;
|
||
} else if (currentTool === "compress") {
|
||
params.format = toolState.compress.format;
|
||
params.quality = toolState.compress.quality;
|
||
if (toolState.compress.target_size_mb > 0) {
|
||
params.target_size_mb = toolState.compress.target_size_mb;
|
||
}
|
||
} else if (currentTool === "strip_metadata") {
|
||
params.format = toolState.strip_metadata.format;
|
||
params.quality = 95;
|
||
}
|
||
|
||
// Calculate total MB
|
||
const totalBytes = filesList.reduce((acc, f) => acc + f.size, 0);
|
||
const totalMb = totalBytes / (1024 * 1024);
|
||
params.current_size_mb = totalMb;
|
||
|
||
try {
|
||
// 1. Chunked Upload (Max 15 files or 8MB per chunk for proxy resilience)
|
||
const MAX_FILES = 15;
|
||
const MAX_BYTES = 8 * 1024 * 1024;
|
||
const chunks = [];
|
||
let curChunk = [];
|
||
let curChunkBytes = 0;
|
||
|
||
for (const item of filesList) {
|
||
if (curChunk.length >= MAX_FILES || (curChunkBytes + item.size > MAX_BYTES && curChunk.length > 0)) {
|
||
chunks.push(curChunk);
|
||
curChunk = [];
|
||
curChunkBytes = 0;
|
||
}
|
||
curChunk.push(item);
|
||
curChunkBytes += item.size;
|
||
}
|
||
if (curChunk.length > 0) chunks.push(curChunk);
|
||
|
||
logBatchConsole(`Packaging ${filesList.length} files into ${chunks.length} proxy-safe chunk(s)...`);
|
||
|
||
const uploadStartTime = performance.now();
|
||
let uploadedBytes = 0;
|
||
|
||
for (let i = 0; i < chunks.length; i++) {
|
||
const chunk = chunks[i];
|
||
const pct = Math.round((i / chunks.length) * 50);
|
||
updateBatchModalProgress(pct, `Uploading chunk ${i + 1} of ${chunks.length}...`);
|
||
|
||
const fData = new FormData();
|
||
fData.append("chunk_index", i.toString());
|
||
fData.append("total_chunks", chunks.length.toString());
|
||
fData.append("reset", (i === 0).toString());
|
||
if (activeSessionId) fData.append("session_id", activeSessionId);
|
||
|
||
chunk.forEach(item => {
|
||
fData.append("files", item.file);
|
||
fData.append("relative_paths", item.name);
|
||
});
|
||
|
||
// 3-Attempt Exponential Backoff
|
||
let chunkSuccess = false;
|
||
let lastErr = null;
|
||
for (let attempt = 1; attempt <= 3; attempt++) {
|
||
try {
|
||
const upRes = await fetch(getApiUrl("/upload-batch"), {
|
||
method: "POST",
|
||
headers: activeSessionId ? { "X-Session-ID": activeSessionId } : {},
|
||
body: fData
|
||
});
|
||
if (!upRes.ok) throw new Error(`HTTP ${upRes.status}`);
|
||
const upData = await upRes.json();
|
||
if (upData.session_id) activeSessionId = upData.session_id;
|
||
chunkSuccess = true;
|
||
break;
|
||
} catch (err) {
|
||
lastErr = err;
|
||
logBatchConsole(`⚠️ Chunk ${i + 1} attempt ${attempt} failed: ${err.message}. Retrying...`);
|
||
await new Promise(r => setTimeout(r, 1000 * attempt));
|
||
}
|
||
}
|
||
|
||
if (!chunkSuccess) {
|
||
throw new Error(`Upload failed on chunk ${i + 1}: ${lastErr?.message || "network error"}`);
|
||
}
|
||
|
||
uploadedBytes += chunk.reduce((acc, it) => acc + it.size, 0);
|
||
const elapsedSec = (performance.now() - uploadStartTime) / 1000;
|
||
const speedMb = (uploadedBytes / (1024 * 1024)) / (elapsedSec || 1);
|
||
const speedEl = document.getElementById("batch-modal-speed");
|
||
if (speedEl) speedEl.textContent = `${speedMb.toFixed(1)} MB/s`;
|
||
}
|
||
|
||
updateBatchModalProgress(50, "Files uploaded! Starting server transformations...");
|
||
logBatchConsole(`✓ All chunks uploaded successfully. Starting stream processing...`, "success");
|
||
|
||
// 2. Check if user selected Enterprise Background Execution
|
||
const isBackground = document.getElementById("batch-run-background")?.checked;
|
||
if (isBackground) {
|
||
const timeLimitSec = parseInt(document.getElementById("batch-time-limit-sel")?.value || "120", 10);
|
||
logBatchConsole(`Dispatching to enterprise background job with ${timeLimitSec}s governance time limit...`);
|
||
updateBatchModalProgress(70, `Dispatching to background worker (${timeLimitSec}s limit)...`);
|
||
|
||
const jobRes = await fetch(getApiUrl("/api/jobs/start"), {
|
||
method: "POST",
|
||
headers: { "Content-Type": "application/json" },
|
||
body: JSON.stringify({
|
||
session_id: activeSessionId,
|
||
operation: currentTool,
|
||
time_limit_sec: timeLimitSec,
|
||
params: params
|
||
})
|
||
});
|
||
const jobData = await jobRes.json();
|
||
if (!jobRes.ok) throw new Error(jobData.error || "Failed to start background job");
|
||
|
||
logBatchConsole(`✓ Job [${jobData.job_id}] running in server background!`, "success");
|
||
logBatchConsole(`✓ Governance: Auto-terminates if execution exceeds ${timeLimitSec} seconds.`);
|
||
updateBatchModalProgress(100, `Background job started: ${jobData.job_id}`);
|
||
document.getElementById("btn-modal-close").style.display = "inline-flex";
|
||
|
||
trackBackgroundJob(jobData.job_id);
|
||
switchInspectorTab("jobs");
|
||
showToast(`Background job ${jobData.job_id} dispatched (${timeLimitSec}s limit)`, "success");
|
||
return;
|
||
}
|
||
|
||
// 2. SSE Server-Side Batch Processing
|
||
const procRes = await fetch(getApiUrl("/batch-process-session"), {
|
||
method: "POST",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
...(activeSessionId ? { "X-Session-ID": activeSessionId } : {})
|
||
},
|
||
body: JSON.stringify({
|
||
operation: currentTool,
|
||
params: params,
|
||
session_id: activeSessionId
|
||
})
|
||
});
|
||
|
||
if (!procRes.ok) {
|
||
const errTxt = await procRes.text();
|
||
throw new Error(`Processing failed (${procRes.status}): ${errTxt}`);
|
||
}
|
||
|
||
const reader = procRes.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
let buffer = "";
|
||
let lastResult = null;
|
||
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
|
||
buffer += decoder.decode(value, { stream: true });
|
||
const lines = buffer.split("\n");
|
||
buffer = lines.pop();
|
||
|
||
for (const line of lines) {
|
||
if (line.startsWith(":")) continue;
|
||
if (line.startsWith("data: ")) {
|
||
try {
|
||
const ev = JSON.parse(line.substring(6));
|
||
if (ev.type === "progress") {
|
||
const streamPct = 50 + Math.round((ev.current / ev.total) * 50);
|
||
updateBatchModalProgress(streamPct, `Processing image ${ev.current} of ${ev.total}: ${ev.filename}`);
|
||
logBatchConsole(`[${ev.current}/${ev.total}] ✓ ${ev.filename}`);
|
||
} else if (ev.type === "complete") {
|
||
lastResult = ev;
|
||
}
|
||
} catch (pe) {}
|
||
}
|
||
}
|
||
}
|
||
|
||
if (lastResult) {
|
||
updateBatchModalProgress(100, `Completed! Processed ${lastResult.processed_count} files`);
|
||
logBatchConsole(`✓ Batch complete: ${lastResult.processed_count} files processed successfully!`, "success");
|
||
|
||
// Auto Download ZIP
|
||
const dlSession = lastResult.session_id || activeSessionId;
|
||
const dlZip = lastResult.zip_name || "processed_images.zip";
|
||
const dlUrl = getApiUrl(`/download-batch?session_id=${encodeURIComponent(dlSession)}&zip_name=${encodeURIComponent(dlZip)}`);
|
||
|
||
logBatchConsole("Downloading processed ZIP archive...");
|
||
const dlRes = await fetch(dlUrl);
|
||
if (dlRes.ok) {
|
||
const blob = await dlRes.blob();
|
||
const a = document.createElement("a");
|
||
a.href = window.URL.createObjectURL(blob);
|
||
a.download = dlZip;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
a.remove();
|
||
showToast("Batch complete! ZIP downloaded", "success");
|
||
}
|
||
|
||
document.getElementById("btn-modal-close").style.display = "inline-flex";
|
||
} else {
|
||
throw new Error("No completion event received from server");
|
||
}
|
||
} catch (error) {
|
||
logBatchConsole(`❌ Error: ${error.message}`, "error");
|
||
updateBatchModalProgress(100, `Failed: ${error.message}`);
|
||
const fill = document.getElementById("batch-modal-fill");
|
||
if (fill) fill.style.background = "#ef4444";
|
||
document.getElementById("btn-modal-close").style.display = "inline-flex";
|
||
showToast(error.message, "error");
|
||
}
|
||
}
|
||
window.executeBatchAll = executeBatchAll;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// MODAL & CONSOLE HELPERS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function openBatchModal() {
|
||
const modal = document.getElementById("batch-modal");
|
||
const fill = document.getElementById("batch-modal-fill");
|
||
const closeBtn = document.getElementById("btn-modal-close");
|
||
const consoleBox = document.getElementById("batch-modal-console");
|
||
|
||
if (modal) modal.style.display = "flex";
|
||
if (fill) { fill.style.width = "0%"; fill.style.background = "linear-gradient(90deg, var(--primary) 0%, var(--accent-cyan) 100%)"; }
|
||
if (closeBtn) closeBtn.style.display = "none";
|
||
if (consoleBox) consoleBox.innerHTML = "";
|
||
updateBatchModalProgress(0, "Initializing...");
|
||
}
|
||
|
||
function closeBatchModal() {
|
||
const modal = document.getElementById("batch-modal");
|
||
if (modal) modal.style.display = "none";
|
||
}
|
||
window.closeBatchModal = closeBatchModal;
|
||
|
||
function updateBatchModalProgress(pct, statusText) {
|
||
const pctEl = document.getElementById("batch-modal-pct");
|
||
const fillEl = document.getElementById("batch-modal-fill");
|
||
const statEl = document.getElementById("batch-modal-status");
|
||
|
||
if (pctEl) pctEl.textContent = `${pct}%`;
|
||
if (fillEl) fillEl.style.width = `${pct}%`;
|
||
if (statEl) statEl.textContent = statusText;
|
||
}
|
||
|
||
function logBatchConsole(text, type = "normal") {
|
||
const box = document.getElementById("batch-modal-console");
|
||
if (!box) return;
|
||
const line = document.createElement("div");
|
||
line.className = `ps-console-line ${type}`;
|
||
line.textContent = `> ${text}`;
|
||
box.appendChild(line);
|
||
box.scrollTop = box.scrollHeight;
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// INSPECTOR TAB SWITCHING
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function switchInspectorTab(tabName, el) {
|
||
document.querySelectorAll(".ps-inspector-tab").forEach(t => {
|
||
t.classList.toggle("active", t.getAttribute("data-tab") === tabName);
|
||
});
|
||
|
||
const tabControls = document.getElementById("inspector-tab-controls");
|
||
const tabInfo = document.getElementById("inspector-tab-info");
|
||
const tabHistory = document.getElementById("inspector-tab-history");
|
||
const tabBatch = document.getElementById("inspector-tab-batch");
|
||
const tabJobs = document.getElementById("inspector-tab-jobs");
|
||
|
||
if (tabControls) tabControls.style.display = (tabName === "controls") ? "block" : "none";
|
||
if (tabInfo) tabInfo.style.display = (tabName === "info") ? "block" : "none";
|
||
if (tabHistory) {
|
||
tabHistory.style.display = (tabName === "history") ? "block" : "none";
|
||
if (tabName === "history") renderHistoryTab();
|
||
}
|
||
if (tabBatch) tabBatch.style.display = (tabName === "batch") ? "block" : "none";
|
||
if (tabJobs) {
|
||
tabJobs.style.display = (tabName === "jobs") ? "block" : "none";
|
||
if (tabName === "jobs") refreshBackgroundJobs();
|
||
}
|
||
}
|
||
window.switchInspectorTab = switchInspectorTab;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// VIEWPORT ZOOM & HUD CONTROLS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function zoomViewport(delta) {
|
||
zoomFactor = Math.max(0.25, Math.min(3.5, zoomFactor + delta));
|
||
applyZoom();
|
||
}
|
||
window.zoomViewport = zoomViewport;
|
||
|
||
function resetZoom() {
|
||
zoomFactor = 1.0;
|
||
applyZoom();
|
||
}
|
||
window.resetZoom = resetZoom;
|
||
|
||
function actualSizeZoom() {
|
||
zoomFactor = 1.0;
|
||
applyZoom();
|
||
}
|
||
window.actualSizeZoom = actualSizeZoom;
|
||
|
||
function applyZoom() {
|
||
const stage = document.getElementById("ps-stage-container");
|
||
const val = document.getElementById("ps-zoom-val");
|
||
if (stage) stage.style.transform = `scale(${zoomFactor})`;
|
||
if (val) val.textContent = `${Math.round(zoomFactor * 100)}%`;
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// KEYBOARD SHORTCUTS (Photoshop Standard Ergonomics)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function setupKeyboardShortcuts() {
|
||
document.addEventListener("keydown", (e) => {
|
||
if (["INPUT", "SELECT", "TEXTAREA"].includes(e.target.tagName)) {
|
||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||
e.preventDefault();
|
||
executeActiveImage();
|
||
}
|
||
return;
|
||
}
|
||
|
||
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "o") {
|
||
e.preventDefault();
|
||
document.getElementById("file-input-multi")?.click();
|
||
return;
|
||
}
|
||
|
||
if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
|
||
e.preventDefault();
|
||
executeActiveImage();
|
||
return;
|
||
}
|
||
|
||
if (e.key === "Escape") {
|
||
closeBatchModal();
|
||
return;
|
||
}
|
||
|
||
const key = e.key.toLowerCase();
|
||
const toolMap = {
|
||
"c": "crop",
|
||
"m": "resize",
|
||
"r": "rotate",
|
||
"a": "adjust",
|
||
"f": "filter",
|
||
"o": "round_corners",
|
||
"d": "border",
|
||
"t": "watermark",
|
||
"b": "masker",
|
||
"e": "convert",
|
||
"z": "compress",
|
||
"s": "strip_metadata"
|
||
};
|
||
|
||
if (toolMap[key]) {
|
||
e.preventDefault();
|
||
selectTool(toolMap[key]);
|
||
}
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// TOAST NOTIFICATIONS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function showToast(msg, type = "info") {
|
||
const container = document.getElementById("toast-container");
|
||
if (!container) return;
|
||
const toast = document.createElement("div");
|
||
toast.className = `toast ${type}`;
|
||
const icon = type === "success" ? "fa-circle-check" :
|
||
type === "error" ? "fa-circle-exclamation" :
|
||
"fa-circle-info";
|
||
toast.innerHTML = `<i class="fa-solid ${icon}"></i> <span>${msg}</span>`;
|
||
container.appendChild(toast);
|
||
setTimeout(() => toast.remove(), 4000);
|
||
}
|
||
window.showToast = showToast;
|
||
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// HISTORY SNAPSHOTS TIMELINE
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let historySnapshots = [];
|
||
|
||
function pushHistorySnapshot(label, dataUrl, w, h) {
|
||
const time = new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' });
|
||
const snapshot = {
|
||
id: Date.now() + Math.random().toString(36).substring(2, 7),
|
||
label: label || "Edit",
|
||
time: time,
|
||
dataUrl: dataUrl,
|
||
w: w,
|
||
h: h
|
||
};
|
||
historySnapshots.push(snapshot);
|
||
renderHistoryTab();
|
||
}
|
||
window.pushHistorySnapshot = pushHistorySnapshot;
|
||
|
||
function renderHistoryTab() {
|
||
const container = document.getElementById("ps-history-list");
|
||
if (!container) return;
|
||
|
||
if (historySnapshots.length === 0) {
|
||
container.innerHTML = `
|
||
<div style="text-align: center; color: var(--text-muted); font-size: 11.5px; padding: 24px 10px;">
|
||
<i class="fa-solid fa-clock-rotate-left" style="font-size: 24px; opacity: 0.4; margin-bottom: 8px; display: block;"></i>
|
||
No edit history recorded yet.<br>Apply operations to build snapshot timeline.
|
||
</div>`;
|
||
return;
|
||
}
|
||
|
||
let html = "";
|
||
historySnapshots.forEach((snap, idx) => {
|
||
const isLatest = idx === historySnapshots.length - 1;
|
||
html += `
|
||
<div class="ps-history-item ${isLatest ? 'active' : ''}" onclick="restoreHistoryState(${idx})" title="Click to restore this state">
|
||
<div class="ps-history-name">
|
||
<i class="fa-solid ${idx === 0 ? 'fa-image' : 'fa-wand-magic-sparkles'}" style="margin-right: 6px; color: ${isLatest ? 'var(--primary)' : 'var(--text-muted)'};"></i>
|
||
<span>${snap.label}</span>
|
||
</div>
|
||
<span class="ps-history-time">${snap.time}</span>
|
||
</div>`;
|
||
});
|
||
container.innerHTML = html;
|
||
}
|
||
window.renderHistoryTab = renderHistoryTab;
|
||
|
||
async function restoreHistoryState(index) {
|
||
if (index < 0 || index >= historySnapshots.length) return;
|
||
const snap = historySnapshots[index];
|
||
const cur = filesList[activeIndex];
|
||
if (!cur) return;
|
||
|
||
cur.dataUrl = snap.dataUrl;
|
||
cur.naturalW = snap.w;
|
||
cur.naturalH = snap.h;
|
||
|
||
try {
|
||
const blob = await (await fetch(snap.dataUrl)).blob();
|
||
cur.file = new File([blob], cur.name, { type: blob.type });
|
||
cur.size = blob.size;
|
||
} catch (_) {}
|
||
|
||
renderActiveImage();
|
||
updateSplitImages();
|
||
renderHistoryTab();
|
||
showToast(`Restored snapshot: ${snap.label}`, "info");
|
||
}
|
||
window.restoreHistoryState = restoreHistoryState;
|
||
|
||
function revertToOriginal() {
|
||
if (historySnapshots.length === 0) {
|
||
showToast("No original snapshot available", "info");
|
||
return;
|
||
}
|
||
restoreHistoryState(0);
|
||
}
|
||
window.revertToOriginal = revertToOriginal;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// BEFORE / AFTER SPLIT VIEW COMPARISON
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let splitActive = false;
|
||
let isSplitDragging = false;
|
||
|
||
function toggleSplitView() {
|
||
const splitContainer = document.getElementById("ps-split-container");
|
||
const btn = document.getElementById("btn-toggle-split") || document.getElementById("btn-split-view");
|
||
if (!splitContainer) return;
|
||
|
||
splitActive = !splitActive;
|
||
if (splitActive) {
|
||
splitContainer.style.display = "block";
|
||
if (btn) btn.classList.add("active");
|
||
updateSplitImages();
|
||
setupSplitDrag();
|
||
showToast("Split View enabled (Drag divider to compare)", "info");
|
||
} else {
|
||
splitContainer.style.display = "none";
|
||
if (btn) btn.classList.remove("active");
|
||
}
|
||
}
|
||
window.toggleSplitView = toggleSplitView;
|
||
|
||
function updateSplitImages() {
|
||
const beforeImg = document.getElementById("ps-split-before-img");
|
||
const activeImg = document.getElementById("ps-active-img");
|
||
if (!beforeImg || !activeImg) return;
|
||
|
||
const originalUrl = (historySnapshots.length > 0) ? historySnapshots[0].dataUrl : activeImg.src;
|
||
beforeImg.src = originalUrl;
|
||
}
|
||
window.updateSplitImages = updateSplitImages;
|
||
|
||
function setupSplitDrag() {
|
||
const container = document.getElementById("ps-split-container");
|
||
const bar = document.getElementById("ps-split-bar");
|
||
const clipWrap = document.getElementById("ps-split-clip-wrap");
|
||
if (!container || !bar || !clipWrap || container.dataset.dragBound) return;
|
||
container.dataset.dragBound = "true";
|
||
|
||
function setDividerPos(clientX) {
|
||
const rect = container.getBoundingClientRect();
|
||
if (!rect.width) return;
|
||
let pct = ((clientX - rect.left) / rect.width) * 100;
|
||
pct = Math.max(0, Math.min(100, pct));
|
||
bar.style.left = pct + "%";
|
||
clipWrap.style.width = pct + "%";
|
||
}
|
||
|
||
bar.addEventListener("pointerdown", (e) => {
|
||
isSplitDragging = true;
|
||
bar.setPointerCapture(e.pointerId);
|
||
e.preventDefault();
|
||
});
|
||
|
||
window.addEventListener("pointermove", (e) => {
|
||
if (!isSplitDragging) return;
|
||
setDividerPos(e.clientX);
|
||
});
|
||
|
||
window.addEventListener("pointerup", (e) => {
|
||
if (isSplitDragging) {
|
||
isSplitDragging = false;
|
||
try { bar.releasePointerCapture(e.pointerId); } catch (_) {}
|
||
}
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// ENTERPRISE PRESETS MODAL
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function openPresetsModal() {
|
||
const modal = document.getElementById("presets-modal");
|
||
if (modal) modal.style.display = "flex";
|
||
}
|
||
window.openPresetsModal = openPresetsModal;
|
||
|
||
function closePresetsModal() {
|
||
const modal = document.getElementById("presets-modal");
|
||
if (modal) modal.style.display = "none";
|
||
}
|
||
window.closePresetsModal = closePresetsModal;
|
||
|
||
function applyEnterprisePreset(name, targetW, targetH, aspect) {
|
||
selectTool("resize");
|
||
toolState.resize.width = targetW;
|
||
toolState.resize.height = targetH;
|
||
toolState.resize.maintain_aspect = false;
|
||
|
||
const wInput = document.getElementById("param-resize-w");
|
||
const hInput = document.getElementById("param-resize-h");
|
||
if (wInput) wInput.value = targetW;
|
||
if (hInput) hInput.value = targetH;
|
||
|
||
closePresetsModal();
|
||
showToast(`Applied preset: ${name} (${targetW}×${targetH})`, "success");
|
||
}
|
||
window.applyEnterprisePreset = applyEnterprisePreset;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// ENTERPRISE BACKGROUND JOBS & ASYNC WORKERS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let jobPollInterval = null;
|
||
|
||
function toggleBackgroundGovOptions(checked) {
|
||
const box = document.getElementById("batch-gov-timeout-box");
|
||
if (box) {
|
||
box.style.opacity = checked ? "1" : "0.5";
|
||
}
|
||
}
|
||
window.toggleBackgroundGovOptions = toggleBackgroundGovOptions;
|
||
|
||
function trackBackgroundJob(jobId) {
|
||
startJobPolling();
|
||
refreshBackgroundJobs();
|
||
}
|
||
window.trackBackgroundJob = trackBackgroundJob;
|
||
|
||
function startJobPolling() {
|
||
if (jobPollInterval) return;
|
||
jobPollInterval = setInterval(refreshBackgroundJobs, 2500);
|
||
}
|
||
window.startJobPolling = startJobPolling;
|
||
|
||
async function refreshBackgroundJobs() {
|
||
const listContainer = document.getElementById("ps-jobs-list");
|
||
const badgePill = document.getElementById("jobs-badge-pill");
|
||
if (!listContainer) return;
|
||
|
||
try {
|
||
const res = await fetch(getApiUrl("/api/jobs/list"));
|
||
if (!res.ok) return;
|
||
const data = await res.json();
|
||
const jobs = data.jobs || [];
|
||
|
||
if (badgePill) {
|
||
const activeCount = jobs.filter(j => j.status === "QUEUED" || j.status === "PROCESSING").length;
|
||
badgePill.textContent = activeCount.toString();
|
||
badgePill.style.display = activeCount > 0 ? "inline-block" : "none";
|
||
}
|
||
|
||
renderJobsList(jobs);
|
||
} catch (err) {
|
||
console.error("Failed to refresh background jobs:", err);
|
||
}
|
||
}
|
||
window.refreshBackgroundJobs = refreshBackgroundJobs;
|
||
|
||
function renderJobsList(jobs) {
|
||
const container = document.getElementById("ps-jobs-list");
|
||
if (!container) return;
|
||
|
||
if (!jobs || jobs.length === 0) {
|
||
container.innerHTML = `
|
||
<div style="text-align: center; color: var(--text-muted); font-size: 11.5px; padding: 24px 10px;">
|
||
<i class="fa-solid fa-server" style="font-size: 24px; opacity: 0.4; margin-bottom: 8px; display: block;"></i>
|
||
No background jobs found.<br>Dispatch heavy tasks using the "Run in Background" toggle.
|
||
</div>`;
|
||
return;
|
||
}
|
||
|
||
let html = "";
|
||
jobs.forEach(job => {
|
||
const jId = job.job_id || job.id;
|
||
const badgeClass =
|
||
job.status === "COMPLETED" ? "badge-success" :
|
||
job.status === "PROCESSING" ? "badge-running" :
|
||
job.status === "TIMED_OUT" ? "badge-timeout" :
|
||
job.status === "CANCELLED" ? "badge-cancelled" :
|
||
"badge-queued";
|
||
|
||
const elapsed = `${Math.round(job.elapsed_sec || 0)}s`;
|
||
const limit = job.time_limit_sec ? `${job.time_limit_sec}s` : "none";
|
||
const doneFiles = job.completed_files !== undefined ? job.completed_files : (job.processed_count || 0);
|
||
const dlUrl = (job.status === "COMPLETED" || job.status === "TIMED_OUT") ? getApiUrl("/api/jobs/download?job_id=" + encodeURIComponent(jId)) : null;
|
||
|
||
html += `
|
||
<div class="ps-job-card" id="job-card-${jId}">
|
||
<div class="ps-job-header">
|
||
<div style="display: flex; flex-direction: column; gap: 2px;">
|
||
<div style="font-weight: 700; font-size: 12px; color: #fff;">
|
||
<i class="fa-solid fa-gear" style="color: var(--primary); margin-right: 5px;"></i>
|
||
${(job.operation || "Batch").toUpperCase()} Task
|
||
</div>
|
||
<div style="font-size: 10px; font-family: var(--font-mono); color: var(--text-muted);">${jId}</div>
|
||
</div>
|
||
<span class="ps-job-badge ${badgeClass}">${job.status}</span>
|
||
</div>
|
||
|
||
<div class="ps-job-meta">
|
||
<div class="ps-job-stat">
|
||
<span class="ps-job-stat-label">Files</span>
|
||
<span class="ps-job-stat-val">${doneFiles} / ${job.total_files || 1}</span>
|
||
</div>
|
||
<div class="ps-job-stat">
|
||
<span class="ps-job-stat-label">Elapsed / Limit</span>
|
||
<span class="ps-job-stat-val">${elapsed} / ${limit}</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div class="ps-progress-bar-bg" style="height: 5px; margin: 8px 0; background: rgba(255,255,255,0.06); border-radius: 3px; overflow: hidden;">
|
||
<div style="height: 100%; width: ${job.progress_pct || 0}%; background: var(--primary); transition: width 0.3s ease;"></div>
|
||
</div>
|
||
|
||
<div class="ps-job-actions">
|
||
${(job.status === "PROCESSING" || job.status === "QUEUED") ? `
|
||
<button class="btn btn-secondary btn-sm" onclick="cancelJob('${jId}')" style="height: 24px; font-size: 10.5px; color: var(--accent-rose); border-color: rgba(244,63,94,0.3);">
|
||
<i class="fa-solid fa-stop"></i> Terminate
|
||
</button>
|
||
` : ''}
|
||
${dlUrl ? `
|
||
<a href="${dlUrl}" download class="btn btn-primary btn-sm" style="height: 24px; font-size: 10.5px; text-decoration: none; display: inline-flex; align-items: center; gap: 4px;">
|
||
<i class="fa-solid fa-download"></i> Download ZIP
|
||
</a>
|
||
` : ''}
|
||
</div>
|
||
</div>
|
||
`;
|
||
});
|
||
|
||
container.innerHTML = html;
|
||
}
|
||
|
||
async function cancelJob(jobId) {
|
||
try {
|
||
const res = await fetch(getApiUrl(`/api/jobs/cancel?job_id=${encodeURIComponent(jobId)}`), { method: "POST" });
|
||
const data = await res.json();
|
||
if (res.ok) {
|
||
showToast("Job canceled successfully", "info");
|
||
refreshBackgroundJobs();
|
||
} else {
|
||
showToast(data.error || "Failed to cancel job", "error");
|
||
}
|
||
} catch (err) {
|
||
showToast(`Error cancelling job: ${err.message}`, "error");
|
||
}
|
||
}
|
||
window.cancelJob = cancelJob;
|
||
|
||
function setMaskColor(colorHex) {
|
||
toolState.masker.color = colorHex;
|
||
redrawMaskStrokes();
|
||
}
|
||
window.setMaskColor = setMaskColor;
|