1833 lines
76 KiB
JavaScript
1833 lines
76 KiB
JavaScript
/**
|
||
* Photoshop Lite · Obsidian Liquid Studio
|
||
* Advanced Image Manipulation Suite & 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 = "";
|
||
|
||
// Crop State
|
||
let cropAspectRatio = "free"; // "free", "1:1", "16:9", "9:16", "4:5", "4:3", "3:2"
|
||
let cropCoords = { x: 0, y: 0, w: 0, h: 0 }; // in CSS pixels relative to image element
|
||
let cropInteraction = null; // { mode: 'move' | 'handle', handle: string, startX, startY, origCrop }
|
||
|
||
// Masker State
|
||
let maskCanvas = null;
|
||
let maskCtx = null;
|
||
let isDrawing = false;
|
||
let maskStrokes = [];
|
||
let brushSize = 35;
|
||
|
||
// Watermark Base64 Cache for Batch Processing
|
||
let watermarkBase64 = "";
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// 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();
|
||
renderToolControls();
|
||
renderToolOptions();
|
||
updateQueueUI();
|
||
});
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// 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 = ""; // Reset file input
|
||
}
|
||
}
|
||
|
||
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;
|
||
renderActiveImage();
|
||
}
|
||
|
||
updateQueueUI();
|
||
showToast(`Loaded ${filesList.length} image(s) into workspace`, "success");
|
||
}
|
||
|
||
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;
|
||
|
||
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;
|
||
renderActiveImage();
|
||
}
|
||
}
|
||
|
||
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();
|
||
}
|
||
|
||
function resetWorkspace() {
|
||
filesList = [];
|
||
activeIndex = 0;
|
||
cropCoords = { x: 0, y: 0, w: 0, h: 0 };
|
||
maskStrokes = [];
|
||
renderActiveImage();
|
||
updateQueueUI();
|
||
showToast("Workspace cleared", "info");
|
||
}
|
||
|
||
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];
|
||
const wIn = document.getElementById("param-width");
|
||
const hIn = document.getElementById("param-height");
|
||
if (wIn && hIn && cur) {
|
||
wIn.value = cur.naturalW;
|
||
hIn.value = cur.naturalH;
|
||
}
|
||
}
|
||
|
||
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: 80% 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);
|
||
|
||
cropCoords = { x, y, w, h };
|
||
applyAspectRatioConstraint(cropAspectRatio);
|
||
updateCropVisuals();
|
||
}
|
||
|
||
function setCropAspect(aspect) {
|
||
cropAspectRatio = aspect;
|
||
document.querySelectorAll(".crop-aspect-btn").forEach(b => {
|
||
b.classList.toggle("active", b.getAttribute("data-aspect") === aspect);
|
||
});
|
||
applyAspectRatioConstraint(aspect);
|
||
updateCropVisuals();
|
||
}
|
||
window.setCropAspect = setCropAspect;
|
||
|
||
function resetCropToFull() {
|
||
const img = document.getElementById("ps-active-img");
|
||
if (!img) return;
|
||
cropCoords = { x: 0, y: 0, w: img.clientWidth, h: img.clientHeight };
|
||
applyAspectRatioConstraint(cropAspectRatio);
|
||
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 = cropCoords.w;
|
||
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);
|
||
}
|
||
|
||
cropCoords.w = newW;
|
||
cropCoords.h = newH;
|
||
cropCoords.x = Math.max(0, Math.min(img.clientWidth - newW, cropCoords.x));
|
||
cropCoords.y = Math.max(0, Math.min(img.clientHeight - newH, cropCoords.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 } = cropCoords;
|
||
const imgW = img.clientWidth;
|
||
const imgH = img.clientHeight;
|
||
|
||
// Box position
|
||
if (box) {
|
||
box.style.left = `${x}px`;
|
||
box.style.top = `${y}px`;
|
||
box.style.width = `${w}px`;
|
||
box.style.height = `${h}px`;
|
||
}
|
||
|
||
// Scrims
|
||
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`; }
|
||
|
||
// Actual pixel dimensions
|
||
const scaleX = (filesList[activeIndex]?.naturalW || imgW) / imgW;
|
||
const scaleY = (filesList[activeIndex]?.naturalH || imgH) / imgH;
|
||
|
||
const realW = Math.round(w * scaleX);
|
||
const realH = Math.round(h * scaleY);
|
||
|
||
if (dim) {
|
||
dim.textContent = `${realW} × ${realH} px (${cropAspectRatio})`;
|
||
}
|
||
|
||
// Sync to header options badge if exists
|
||
const optBadge = document.getElementById("opt-crop-size");
|
||
if (optBadge) {
|
||
optBadge.textContent = `${realW} × ${realH} px`;
|
||
}
|
||
}
|
||
|
||
function setupCropDragEvents() {
|
||
const box = document.getElementById("crop-box");
|
||
|
||
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: { ...cropCoords }
|
||
};
|
||
} else if (boxEl) {
|
||
e.preventDefault();
|
||
cropInteraction = {
|
||
mode: "move",
|
||
startX: e.clientX,
|
||
startY: e.clientY,
|
||
origCrop: { ...cropCoords }
|
||
};
|
||
}
|
||
});
|
||
|
||
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));
|
||
|
||
cropCoords.x = Math.round(newX);
|
||
cropCoords.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;
|
||
|
||
// Handle directions
|
||
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; }
|
||
|
||
// Aspect constraint handling
|
||
if (cropAspectRatio !== "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[cropAspectRatio];
|
||
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);
|
||
}
|
||
}
|
||
}
|
||
|
||
// Minimum constraint
|
||
if (newW >= 30 && newH >= 30) {
|
||
if (newX >= 0 && newX + newW <= imgW && newY >= 0 && newY + newH <= imgH) {
|
||
cropCoords = { x: Math.round(newX), y: Math.round(newY), w: Math.round(newW), h: Math.round(newH) };
|
||
updateCropVisuals();
|
||
}
|
||
}
|
||
}
|
||
});
|
||
|
||
document.addEventListener("mouseup", () => {
|
||
cropInteraction = null;
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// INPAINT MASK BRUSH ENGINE (Interactive Canvas Overlay)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function initMaskCanvas() {
|
||
const img = document.getElementById("ps-active-img");
|
||
const canvas = document.getElementById("ps-mask-canvas");
|
||
if (!img || !canvas || !img.clientWidth) return;
|
||
|
||
canvas.width = img.clientWidth;
|
||
canvas.height = img.clientHeight;
|
||
maskCanvas = canvas;
|
||
maskCtx = canvas.getContext("2d");
|
||
|
||
// Re-render strokes if any
|
||
redrawMaskStrokes();
|
||
|
||
canvas.onmousedown = (e) => {
|
||
isDrawing = true;
|
||
const rect = canvas.getBoundingClientRect();
|
||
const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top };
|
||
const stroke = { size: brushSize, points: [pt] };
|
||
maskStrokes.push(stroke);
|
||
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.strokeStyle = "#ff0000";
|
||
maskCtx.lineWidth = brushSize;
|
||
maskCtx.beginPath();
|
||
maskCtx.moveTo(pt.x, pt.y);
|
||
maskCtx.lineTo(pt.x, pt.y);
|
||
maskCtx.stroke();
|
||
};
|
||
|
||
canvas.onmousemove = (e) => {
|
||
updateBrushRing(e.clientX, e.clientY);
|
||
if (!isDrawing) return;
|
||
const rect = canvas.getBoundingClientRect();
|
||
const pt = { x: e.clientX - rect.left, y: e.clientY - rect.top };
|
||
const curStroke = maskStrokes[maskStrokes.length - 1];
|
||
if (curStroke) {
|
||
const lastPt = curStroke.points[curStroke.points.length - 1];
|
||
curStroke.points.push(pt);
|
||
|
||
maskCtx.beginPath();
|
||
maskCtx.moveTo(lastPt.x, lastPt.y);
|
||
maskCtx.lineTo(pt.x, pt.y);
|
||
maskCtx.stroke();
|
||
}
|
||
};
|
||
|
||
canvas.onmouseup = () => { isDrawing = false; };
|
||
canvas.onmouseleave = () => { isDrawing = false; };
|
||
}
|
||
|
||
function updateBrushRing(x, y) {
|
||
const ring = document.getElementById("brush-cursor-ring");
|
||
if (!ring) return;
|
||
ring.style.left = `${x}px`;
|
||
ring.style.top = `${y}px`;
|
||
ring.style.width = `${brushSize}px`;
|
||
ring.style.height = `${brushSize}px`;
|
||
}
|
||
|
||
function setBrushSize(size) {
|
||
brushSize = parseInt(size, 10);
|
||
const ring = document.getElementById("brush-cursor-ring");
|
||
if (ring) {
|
||
ring.style.width = `${brushSize}px`;
|
||
ring.style.height = `${brushSize}px`;
|
||
}
|
||
}
|
||
window.setBrushSize = setBrushSize;
|
||
|
||
function clearMaskStrokes() {
|
||
maskStrokes = [];
|
||
if (maskCtx && maskCanvas) {
|
||
maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
}
|
||
}
|
||
window.clearMaskStrokes = clearMaskStrokes;
|
||
|
||
function undoMaskStroke() {
|
||
maskStrokes.pop();
|
||
redrawMaskStrokes();
|
||
}
|
||
window.undoMaskStroke = undoMaskStroke;
|
||
|
||
function redrawMaskStrokes() {
|
||
if (!maskCtx || !maskCanvas) return;
|
||
maskCtx.clearRect(0, 0, maskCanvas.width, maskCanvas.height);
|
||
maskCtx.lineCap = "round";
|
||
maskCtx.lineJoin = "round";
|
||
maskCtx.strokeStyle = "#ff0000";
|
||
|
||
maskStrokes.forEach(s => {
|
||
maskCtx.lineWidth = s.size;
|
||
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();
|
||
});
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// 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 active" data-aspect="free" onclick="setCropAspect('free')">Freeform</button>
|
||
<button class="seg-pill crop-aspect-btn" data-aspect="1:1" onclick="setCropAspect('1:1')">1:1 Square</button>
|
||
<button class="seg-pill crop-aspect-btn" data-aspect="16:9" onclick="setCropAspect('16:9')">16:9</button>
|
||
<button class="seg-pill crop-aspect-btn" data-aspect="9:16" onclick="setCropAspect('9:16')">9:16 Story</button>
|
||
<button class="seg-pill crop-aspect-btn" data-aspect="4:5" onclick="setCropAspect('4:5')">4:5</button>
|
||
<button class="seg-pill crop-aspect-btn" 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> Reset Crop</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 Presets:</span>
|
||
<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)">Neutral</button>
|
||
<button class="seg-pill" onclick="applyColorPreset(5, 20, 25, 1.0)">Vivid Pop</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)">High Contrast B&W</button>
|
||
</div>
|
||
`,
|
||
filter: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Quick Filter:</span>
|
||
<button class="seg-pill" onclick="setFilterQuick('BLUR')">Blur</button>
|
||
<button class="seg-pill" onclick="setFilterQuick('SHARPEN')">Sharpen</button>
|
||
<button class="seg-pill" onclick="setFilterQuick('GRAYSCALE')">Grayscale</button>
|
||
<button class="seg-pill" onclick="setFilterQuick('WARM')">Warm</button>
|
||
<button class="seg-pill" onclick="setFilterQuick('COOL')">Cool</button>
|
||
<button class="seg-pill" 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="250" value="35" style="width: 120px;" oninput="document.getElementById('param-radius').value=this.value; document.getElementById('opt-round-val').innerText=this.value+'px'">
|
||
<span class="label-val" id="opt-round-val">35px</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" onchange="document.getElementById('param-circle').checked=this.checked">
|
||
<span>Perfect Circular Avatar</span>
|
||
</label>
|
||
</div>
|
||
`,
|
||
border: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Canvas Aspect Pad:</span>
|
||
<button class="seg-pill" onclick="setAspectPad('none')">None</button>
|
||
<button class="seg-pill" onclick="setAspectPad('1:1')">1:1 Square</button>
|
||
<button class="seg-pill" onclick="setAspectPad('4:5')">4:5 Portrait</button>
|
||
<button class="seg-pill" onclick="setAspectPad('16:9')">16:9 Landscape</button>
|
||
</div>
|
||
`,
|
||
watermark: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Position:</span>
|
||
<button class="seg-pill" onclick="setWmPos('top_left')">TL</button>
|
||
<button class="seg-pill" onclick="setWmPos('top_right')">TR</button>
|
||
<button class="seg-pill" onclick="setWmPos('center')">Center</button>
|
||
<button class="seg-pill" onclick="setWmPos('bottom_left')">BL</button>
|
||
<button class="seg-pill active" onclick="setWmPos('bottom_right')">BR</button>
|
||
</div>
|
||
`,
|
||
masker: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Brush Size:</span>
|
||
<input type="range" min="5" max="150" value="35" style="width: 120px;" oninput="setBrushSize(this.value); document.getElementById('opt-brush-val').innerText=this.value+'px'">
|
||
<span class="label-val" id="opt-brush-val">35px</span>
|
||
</div>
|
||
<div class="ps-options-group">
|
||
<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="clearMaskStrokes()"><i class="fa-solid fa-trash"></i> Clear</button>
|
||
</div>
|
||
`,
|
||
convert: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Target Format:</span>
|
||
<button class="seg-pill active" onclick="setConvertFormat('png')">PNG</button>
|
||
<button class="seg-pill" onclick="setConvertFormat('jpg')">JPG</button>
|
||
<button class="seg-pill" onclick="setConvertFormat('webp')">WEBP</button>
|
||
<button class="seg-pill" onclick="setConvertFormat('avif')">AVIF</button>
|
||
<button class="seg-pill" onclick="setConvertFormat('bmp')">BMP</button>
|
||
<button class="seg-pill" onclick="setConvertFormat('tiff')">TIFF</button>
|
||
</div>
|
||
`,
|
||
compress: `
|
||
<div class="ps-options-group">
|
||
<span class="ps-options-label">Quality:</span>
|
||
<input type="range" id="opt-comp-quality" min="10" max="95" value="80" style="width: 120px;" oninput="document.getElementById('param-quality').value=this.value; document.getElementById('opt-comp-val').innerText=this.value+'%'; simulateCompressionDebounced()">
|
||
<span class="label-val" id="opt-comp-val">80%</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);">Simulating...</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 Guard Active: Strips EXIF, GPS, Camera Model, Timestamps</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" ${cropAspectRatio === "free" ? "selected" : ""}>Freeform</option>
|
||
<option value="1:1" ${cropAspectRatio === "1:1" ? "selected" : ""}>1:1 Square</option>
|
||
<option value="16:9" ${cropAspectRatio === "16:9" ? "selected" : ""}>16:9 Landscape</option>
|
||
<option value="9:16" ${cropAspectRatio === "9:16" ? "selected" : ""}>9:16 Vertical Story</option>
|
||
<option value="4:5" ${cropAspectRatio === "4:5" ? "selected" : ""}>4:5 Portrait</option>
|
||
<option value="4:3" ${cropAspectRatio === "4:3" ? "selected" : ""}>4:3 Standard</option>
|
||
<option value="3:2" ${cropAspectRatio === "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="${natW}" oninput="syncAspectHeight()">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Height (px)</label>
|
||
<input type="number" id="param-height" value="${natH}" oninput="syncAspectWidth()">
|
||
</div>
|
||
</div>
|
||
<div class="input-group">
|
||
<label style="cursor: pointer; display: flex; align-items: center; gap: 8px;">
|
||
<input type="checkbox" id="param-maintain" 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">0</span></label>
|
||
<input type="range" id="param-brightness" min="-100" max="100" value="0" oninput="document.getElementById('val-bri').innerText=this.value">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Contrast <span class="label-val" id="val-con">0</span></label>
|
||
<input type="range" id="param-contrast" min="-100" max="100" value="0" oninput="document.getElementById('val-con').innerText=this.value">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Saturation <span class="label-val" id="val-sat">0</span></label>
|
||
<input type="range" id="param-saturation" min="-100" max="100" value="0" oninput="document.getElementById('val-sat').innerText=this.value">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Gamma Curve <span class="label-val" id="val-gam">1.0</span></label>
|
||
<input type="range" id="param-gamma" min="0.2" max="2.5" step="0.05" value="1.0" oninput="document.getElementById('val-gam').innerText=this.value">
|
||
</div>
|
||
`,
|
||
filter: `
|
||
<div class="ps-section-title">Select Artistic Filter</div>
|
||
<div class="input-group">
|
||
<label>Filter Profile</label>
|
||
<select id="param-filter">
|
||
<option value="BLUR">Blur (Smooth 2.5px)</option>
|
||
<option value="SHARPEN">Sharpen (Crisp 2.0x)</option>
|
||
<option value="GRAYSCALE">Monochrome Grayscale</option>
|
||
<option value="SEPIA">Classic Sepia</option>
|
||
<option value="INVERT">Invert Colors (Negative)</option>
|
||
<option value="EMBOSS">Emboss Relief</option>
|
||
<option value="CONTOUR">Edge Contour</option>
|
||
<option value="WARM">Warm Golden Glow</option>
|
||
<option value="COOL">Cool Cyan Chill</option>
|
||
<option value="VINTAGE">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">
|
||
<option value="90">Rotate 90° CW</option>
|
||
<option value="180">Rotate 180°</option>
|
||
<option value="270">Rotate 270° CW (90° CCW)</option>
|
||
<option value="FLIP_H">Flip Horizontal</option>
|
||
<option value="FLIP_V">Flip Vertical</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group" style="margin-top: 10px;">
|
||
<label>Custom Angle Slider <span class="label-val" id="val-angle">0°</span></label>
|
||
<input type="range" id="param-angle" min="-180" max="180" value="0" oninput="document.getElementById('val-angle').innerText=this.value+'°'; if(this.value != '0') document.getElementById('param-operation').value=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">35px</span></label>
|
||
<input type="range" id="param-radius" min="0" max="400" value="35" oninput="document.getElementById('val-radius').innerText=this.value+'px'">
|
||
</div>
|
||
<div class="input-group">
|
||
<label style="cursor: pointer; display: flex; align-items: center; gap: 8px;">
|
||
<input type="checkbox" id="param-circle">
|
||
<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">20px</span></label>
|
||
<input type="range" id="param-border-width" min="1" max="200" value="20" oninput="document.getElementById('val-bwidth').innerText=this.value+'px'">
|
||
</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="#ffffff" style="width: 44px; height: 36px; padding: 2px;">
|
||
<input type="text" id="param-border-color-hex" value="#ffffff" oninput="document.getElementById('param-border-color').value=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:#ff6c37;" onclick="setCustomBorderColor('#ff6c37')"></div>
|
||
<div class="color-swatch" style="background:#00f2fe;" onclick="setCustomBorderColor('#00f2fe')"></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">
|
||
<option value="none">None (Uniform Border)</option>
|
||
<option value="1:1">1:1 Square Canvas</option>
|
||
<option value="4:5">4:5 Instagram Portrait</option>
|
||
<option value="16:9">16:9 Video Canvas</option>
|
||
<option value="9:16">9:16 Story / Reels Canvas</option>
|
||
<option value="4:3">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="cacheWatermarkBase64(this)">
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Position</label>
|
||
<select id="param-position">
|
||
<option value="bottom_right" selected>Bottom Right</option>
|
||
<option value="bottom_left">Bottom Left</option>
|
||
<option value="top_right">Top Right</option>
|
||
<option value="top_left">Top Left</option>
|
||
<option value="center">Center</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Opacity (%) <span class="label-val" id="val-wm-op">60%</span></label>
|
||
<input type="range" id="param-opacity" min="5" max="100" value="60" oninput="document.getElementById('val-wm-op').innerText=this.value+'%'">
|
||
</div>
|
||
`,
|
||
masker: `
|
||
<div class="ps-section-title">Mask Generator & Brush</div>
|
||
<div class="input-group">
|
||
<label>Brush Diameter <span class="label-val" id="val-brush-sz">35px</span></label>
|
||
<input type="range" min="5" max="150" value="35" oninput="setBrushSize(this.value); document.getElementById('val-brush-sz').innerText=this.value+'px'">
|
||
</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;">
|
||
<p style="color: var(--text-3); margin: 0;">Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a 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">
|
||
<option value="png" selected>PNG (Lossless)</option>
|
||
<option value="jpg">JPG (Standard Web)</option>
|
||
<option value="webp">WEBP (Next-Gen High Efficiency)</option>
|
||
<option value="avif">AVIF (Modern Ultra-Compressed)</option>
|
||
<option value="bmp">BMP (Windows Bitmap)</option>
|
||
<option value="tiff">TIFF (Print Master)</option>
|
||
<option value="ico">ICO (Windows Icon)</option>
|
||
<option value="heic">HEIC (Apple High Efficiency)</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Quality Profile (1-100) <span class="label-val" id="val-conv-q">95%</span></label>
|
||
<input type="range" id="param-quality" min="1" max="100" value="95" oninput="document.getElementById('val-conv-q').innerText=this.value+'%'">
|
||
</div>
|
||
`,
|
||
compress: `
|
||
<div class="ps-section-title">Compression Engine</div>
|
||
<div class="input-group">
|
||
<label>Output Format</label>
|
||
<select id="param-format" onchange="simulateCompressionDebounced()">
|
||
<option value="original">Preserve Original Format</option>
|
||
<option value="webp">WEBP (Maximum Reduction)</option>
|
||
<option value="jpg">JPG (Web Optimized)</option>
|
||
<option value="png">PNG (Lossless Graphics)</option>
|
||
</select>
|
||
</div>
|
||
<div class="input-group">
|
||
<label>Quality Threshold <span class="label-val" id="val-comp-q">80%</span></label>
|
||
<input type="range" id="param-quality" min="5" max="95" value="80" oninput="document.getElementById('val-comp-q').innerText=this.value+'%'; simulateCompressionDebounced()">
|
||
</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">
|
||
</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">
|
||
<option value="original">Preserve Original Extension</option>
|
||
<option value="jpg">Convert to Clean JPG</option>
|
||
<option value="png">Convert to Clean PNG</option>
|
||
<option value="webp">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] || "";
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// QUICK CONTROLS & RESIZE ASPECT HELPERS
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
function scaleActiveImage(factor) {
|
||
const cur = filesList[activeIndex];
|
||
if (!cur) return;
|
||
const wIn = document.getElementById("param-width");
|
||
const hIn = document.getElementById("param-height");
|
||
if (wIn && hIn) {
|
||
wIn.value = Math.round(cur.naturalW * factor);
|
||
hIn.value = Math.round(cur.naturalH * factor);
|
||
}
|
||
}
|
||
window.scaleActiveImage = scaleActiveImage;
|
||
|
||
function syncAspectHeight() {
|
||
const maintain = document.getElementById("param-maintain")?.checked;
|
||
const cur = filesList[activeIndex];
|
||
if (!maintain || !cur) return;
|
||
const w = parseFloat(document.getElementById("param-width").value);
|
||
if (w && cur.naturalW) {
|
||
document.getElementById("param-height").value = Math.round(w * (cur.naturalH / cur.naturalW));
|
||
}
|
||
}
|
||
window.syncAspectHeight = syncAspectHeight;
|
||
|
||
function syncAspectWidth() {
|
||
const maintain = document.getElementById("param-maintain")?.checked;
|
||
const cur = filesList[activeIndex];
|
||
if (!maintain || !cur) return;
|
||
const h = parseFloat(document.getElementById("param-height").value);
|
||
if (h && cur.naturalH) {
|
||
document.getElementById("param-width").value = Math.round(h * (cur.naturalW / cur.naturalH));
|
||
}
|
||
}
|
||
window.syncAspectWidth = syncAspectWidth;
|
||
|
||
function applyColorPreset(bri, con, sat, 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; }
|
||
}
|
||
window.applyColorPreset = applyColorPreset;
|
||
|
||
function setFilterQuick(name) {
|
||
const fSelect = document.getElementById("param-filter");
|
||
if (fSelect) fSelect.value = name;
|
||
executeActiveImage();
|
||
}
|
||
window.setFilterQuick = setFilterQuick;
|
||
|
||
function setRotateQuick(op) {
|
||
const opSelect = document.getElementById("param-operation");
|
||
if (opSelect) opSelect.value = op;
|
||
executeActiveImage();
|
||
}
|
||
window.setRotateQuick = setRotateQuick;
|
||
|
||
function setCustomBorderColor(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) {
|
||
const pSelect = document.getElementById("param-pad-aspect");
|
||
if (pSelect) pSelect.value = pad;
|
||
}
|
||
window.setAspectPad = setAspectPad;
|
||
|
||
function setWmPos(pos) {
|
||
const pSelect = document.getElementById("param-position");
|
||
if (pSelect) pSelect.value = pos;
|
||
}
|
||
window.setWmPos = setWmPos;
|
||
|
||
function setConvertFormat(fmt) {
|
||
const fSelect = document.getElementById("param-format");
|
||
if (fSelect) fSelect.value = fmt;
|
||
}
|
||
window.setConvertFormat = setConvertFormat;
|
||
|
||
function cacheWatermarkBase64(input) {
|
||
if (input.files && input.files[0]) {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
watermarkBase64 = e.target.result;
|
||
};
|
||
reader.readAsDataURL(input.files[0]);
|
||
}
|
||
}
|
||
window.cacheWatermarkBase64 = cacheWatermarkBase64;
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// COMPRESSION SIMULATION
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
let simDebounceTimer;
|
||
function simulateCompressionDebounced() {
|
||
clearTimeout(simDebounceTimer);
|
||
simDebounceTimer = setTimeout(simulateCompression, 400);
|
||
}
|
||
|
||
async function simulateCompression() {
|
||
if (currentTool !== "compress" || filesList.length === 0) return;
|
||
const current = filesList[activeIndex];
|
||
if (!current) return;
|
||
|
||
const quality = document.getElementById("param-quality")?.value || "80";
|
||
const format = document.getElementById("param-format")?.value || "original";
|
||
|
||
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 = "Simulating...";
|
||
|
||
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 = "Simulation 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;
|
||
|
||
const formData = new FormData();
|
||
|
||
// Masker Special Case
|
||
if (currentTool === "masker") {
|
||
if (!maskCanvas) {
|
||
showToast("No mask canvas active", "error");
|
||
return;
|
||
}
|
||
|
||
const outCanvas = document.createElement("canvas");
|
||
outCanvas.width = current.naturalW;
|
||
outCanvas.height = current.naturalH;
|
||
const ctx = outCanvas.getContext("2d");
|
||
|
||
// Black background
|
||
ctx.fillStyle = "#000000";
|
||
ctx.fillRect(0, 0, outCanvas.width, outCanvas.height);
|
||
|
||
// Replay in white
|
||
const scaleX = current.naturalW / maskCanvas.width;
|
||
const scaleY = current.naturalH / maskCanvas.height;
|
||
|
||
ctx.lineCap = "round";
|
||
ctx.lineJoin = "round";
|
||
ctx.strokeStyle = "#ffffff";
|
||
|
||
maskStrokes.forEach(s => {
|
||
ctx.lineWidth = s.size * scaleX;
|
||
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();
|
||
});
|
||
|
||
outCanvas.toBlob(async (blob) => {
|
||
const fData = new FormData();
|
||
fData.append("images", blob, "mask.png");
|
||
await executeEndpointRequest("/mask", fData);
|
||
}, "image/png");
|
||
return;
|
||
}
|
||
|
||
// Normal Tools
|
||
formData.append("images", current.file);
|
||
|
||
if (currentTool === "crop") {
|
||
const img = document.getElementById("ps-active-img");
|
||
const scaleX = current.naturalW / img.clientWidth;
|
||
const scaleY = current.naturalH / img.clientHeight;
|
||
|
||
const l = Math.round(cropCoords.x * scaleX);
|
||
const t = Math.round(cropCoords.y * scaleY);
|
||
const r = Math.round((cropCoords.x + cropCoords.w) * scaleX);
|
||
const b = Math.round((cropCoords.y + cropCoords.h) * scaleY);
|
||
|
||
const lPct = (cropCoords.x / img.clientWidth) * 100;
|
||
const tPct = (cropCoords.y / img.clientHeight) * 100;
|
||
const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100;
|
||
const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 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") {
|
||
formData.append("width", document.getElementById("param-width")?.value || current.naturalW);
|
||
formData.append("height", document.getElementById("param-height")?.value || current.naturalH);
|
||
formData.append("maintain_aspect", document.getElementById("param-maintain")?.checked ? "true" : "false");
|
||
} else if (currentTool === "adjust") {
|
||
formData.append("brightness", document.getElementById("param-brightness")?.value || "0");
|
||
formData.append("contrast", document.getElementById("param-contrast")?.value || "0");
|
||
formData.append("saturation", document.getElementById("param-saturation")?.value || "0");
|
||
formData.append("gamma", document.getElementById("param-gamma")?.value || "1.0");
|
||
} else if (currentTool === "filter") {
|
||
formData.append("filter", document.getElementById("param-filter")?.value || "BLUR");
|
||
} else if (currentTool === "rotate") {
|
||
formData.append("operation", document.getElementById("param-operation")?.value || "90");
|
||
} else if (currentTool === "round_corners") {
|
||
formData.append("radius", document.getElementById("param-radius")?.value || "35");
|
||
formData.append("is_circle", document.getElementById("param-circle")?.checked ? "true" : "false");
|
||
} else if (currentTool === "border") {
|
||
formData.append("border_width", document.getElementById("param-border-width")?.value || "20");
|
||
formData.append("border_color", document.getElementById("param-border-color")?.value || "#ffffff");
|
||
formData.append("pad_aspect", document.getElementById("param-pad-aspect")?.value || "none");
|
||
} else if (currentTool === "watermark") {
|
||
const wmFile = document.getElementById("param-watermark-file")?.files[0];
|
||
if (!wmFile) {
|
||
showToast("Please choose a watermark image first", "error");
|
||
return;
|
||
}
|
||
formData.append("watermark", wmFile);
|
||
formData.append("position", document.getElementById("param-position")?.value || "bottom_right");
|
||
formData.append("opacity", document.getElementById("param-opacity")?.value || "60");
|
||
} else if (currentTool === "convert") {
|
||
formData.append("format", document.getElementById("param-format")?.value || "png");
|
||
formData.append("quality", document.getElementById("param-quality")?.value || "95");
|
||
} else if (currentTool === "compress") {
|
||
formData.append("quality", document.getElementById("param-quality")?.value || "80");
|
||
formData.append("format", document.getElementById("param-format")?.value || "original");
|
||
} else if (currentTool === "strip_metadata") {
|
||
formData.append("format", document.getElementById("param-format")?.value || "original");
|
||
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 the 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;
|
||
|
||
renderActiveImage();
|
||
showToast("Transformation applied successfully!", "success");
|
||
} else {
|
||
showToast(data.error || "Transformation failed", "error");
|
||
}
|
||
} catch (err) {
|
||
showToast(`Network error: ${err.message}`, "error");
|
||
}
|
||
}
|
||
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
// EXECUTE BATCH ALL (Proxy-Safe Chunking & SSE Progress Dashboard)
|
||
// ═══════════════════════════════════════════════════════════════════
|
||
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 lPct = (cropCoords.x / img.clientWidth) * 100;
|
||
const tPct = (cropCoords.y / img.clientHeight) * 100;
|
||
const rPct = ((cropCoords.x + cropCoords.w) / img.clientWidth) * 100;
|
||
const bPct = ((cropCoords.y + cropCoords.h) / img.clientHeight) * 100;
|
||
|
||
params.left_pct = lPct;
|
||
params.top_pct = tPct;
|
||
params.right_pct = rPct;
|
||
params.bottom_pct = bPct;
|
||
} else if (currentTool === "resize") {
|
||
params.width = parseFloat(document.getElementById("param-width")?.value || current.naturalW);
|
||
params.height = parseFloat(document.getElementById("param-height")?.value || current.naturalH);
|
||
params.maintain_aspect = document.getElementById("param-maintain")?.checked;
|
||
} else if (currentTool === "adjust") {
|
||
params.brightness = parseFloat(document.getElementById("param-brightness")?.value || 0);
|
||
params.contrast = parseFloat(document.getElementById("param-contrast")?.value || 0);
|
||
params.saturation = parseFloat(document.getElementById("param-saturation")?.value || 0);
|
||
params.gamma = parseFloat(document.getElementById("param-gamma")?.value || 1.0);
|
||
} else if (currentTool === "filter") {
|
||
params.filter = document.getElementById("param-filter")?.value || "BLUR";
|
||
} else if (currentTool === "rotate") {
|
||
params.operation = document.getElementById("param-operation")?.value || "90";
|
||
} else if (currentTool === "round_corners") {
|
||
params.radius = parseFloat(document.getElementById("param-radius")?.value || 35);
|
||
params.is_circle = document.getElementById("param-circle")?.checked;
|
||
} else if (currentTool === "border") {
|
||
params.border_width = parseFloat(document.getElementById("param-border-width")?.value || 20);
|
||
params.border_color = document.getElementById("param-border-color")?.value || "#ffffff";
|
||
params.pad_aspect = document.getElementById("param-pad-aspect")?.value || "none";
|
||
} else if (currentTool === "watermark") {
|
||
if (watermarkBase64) {
|
||
params.watermark_base64 = watermarkBase64;
|
||
}
|
||
params.position = document.getElementById("param-position")?.value || "bottom_right";
|
||
params.opacity = parseFloat(document.getElementById("param-opacity")?.value || 60);
|
||
} else if (currentTool === "convert") {
|
||
params.format = document.getElementById("param-format")?.value || "png";
|
||
params.quality = parseFloat(document.getElementById("param-quality")?.value || 95);
|
||
} else if (currentTool === "compress") {
|
||
params.format = document.getElementById("param-format")?.value || "original";
|
||
params.quality = parseFloat(document.getElementById("param-quality")?.value || 80);
|
||
const targetMb = parseFloat(document.getElementById("param-target-size-mb")?.value || 0);
|
||
if (targetMb > 0) params.target_size_mb = targetMb;
|
||
} else if (currentTool === "strip_metadata") {
|
||
params.format = document.getElementById("param-format")?.value || "original";
|
||
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); // first 50% for upload
|
||
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-side transformations...");
|
||
logBatchConsole(`✓ All chunks uploaded successfully. Starting stream processing...`, "success");
|
||
|
||
// 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; // Keep-alive ping
|
||
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.remove("active"));
|
||
if (el) el.classList.add("active");
|
||
|
||
const tabControls = document.getElementById("inspector-tab-controls");
|
||
const tabInfo = document.getElementById("inspector-tab-info");
|
||
const tabBatch = document.getElementById("inspector-tab-batch");
|
||
|
||
if (tabControls) tabControls.style.display = (tabName === "controls") ? "block" : "none";
|
||
if (tabInfo) tabInfo.style.display = (tabName === "info") ? "block" : "none";
|
||
if (tabBatch) tabBatch.style.display = (tabName === "batch") ? "block" : "none";
|
||
}
|
||
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 typing in an input or select, skip tool shortcuts
|
||
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;
|