1464 lines
60 KiB
JavaScript
1464 lines
60 KiB
JavaScript
let currentTool = "resize";
|
|||
|
|
let currentFiles = [];
|
||
|
|
let batchFiles = []; // For batch processing
|
||
|
|
|
||
|
|
// Batch file upload handler
|
||
|
|
document.addEventListener("DOMContentLoaded", function () {
|
||
|
|
const batchInput = document.getElementById("batch-files");
|
||
|
|
const folderInput = document.getElementById("batch-folder");
|
||
|
|
const batchDropZone = document.getElementById("batchUploadZone");
|
||
|
|
|
||
|
|
function handleFileSelection(files) {
|
||
|
|
batchFiles = Array.from(files);
|
||
|
|
const fileInfo = document.getElementById("batchFileInfo");
|
||
|
|
if (batchFiles.length > 0) {
|
||
|
|
const totalSize = (
|
||
|
|
batchFiles.reduce((sum, f) => sum + f.size, 0) /
|
||
|
|
(1024 * 1024)
|
||
|
|
).toFixed(2);
|
||
|
|
fileInfo.textContent = `✓ ${batchFiles.length} files selected (${totalSize} MB)`;
|
||
|
|
fileInfo.style.color = "var(--primary)";
|
||
|
|
logToConsole(`Selected ${batchFiles.length} files (${totalSize} MB) for batch processing.`);
|
||
|
|
} else {
|
||
|
|
fileInfo.textContent = "";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (batchInput) {
|
||
|
|
batchInput.addEventListener("change", function (e) {
|
||
|
|
handleFileSelection(e.target.files);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
if (folderInput) {
|
||
|
|
folderInput.addEventListener("change", function (e) {
|
||
|
|
handleFileSelection(e.target.files);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
if (batchDropZone) {
|
||
|
|
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
|
||
|
|
batchDropZone.addEventListener(eventName, (e) => {
|
||
|
|
e.preventDefault();
|
||
|
|
e.stopPropagation();
|
||
|
|
}, false);
|
||
|
|
});
|
||
|
|
["dragenter", "dragover"].forEach((eventName) => {
|
||
|
|
batchDropZone.addEventListener(eventName, () => {
|
||
|
|
batchDropZone.style.borderColor = "var(--primary)";
|
||
|
|
batchDropZone.style.background = "rgba(255, 108, 55, 0.15)";
|
||
|
|
}, false);
|
||
|
|
});
|
||
|
|
["dragleave", "drop"].forEach((eventName) => {
|
||
|
|
batchDropZone.addEventListener(eventName, () => {
|
||
|
|
batchDropZone.style.borderColor = "var(--border)";
|
||
|
|
batchDropZone.style.background = "rgba(255, 255, 255, 0.03)";
|
||
|
|
}, false);
|
||
|
|
});
|
||
|
|
batchDropZone.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 subEntry of entries) {
|
||
|
|
await scanEntry(subEntry, path ? `${path}/${entry.name}` : entry.name);
|
||
|
|
}
|
||
|
|
await readEntries();
|
||
|
|
}
|
||
|
|
};
|
||
|
|
await readEntries();
|
||
|
|
}
|
||
|
|
};
|
||
|
|
|
||
|
|
for (let i = 0; i < items.length; i++) {
|
||
|
|
const item = items[i];
|
||
|
|
if (item.webkitGetAsEntry) {
|
||
|
|
const entry = item.webkitGetAsEntry();
|
||
|
|
if (entry) await scanEntry(entry);
|
||
|
|
} else if (item.kind === "file") {
|
||
|
|
scannedFiles.push(item.getAsFile());
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (scannedFiles.length > 0) {
|
||
|
|
handleFileSelection(scannedFiles);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
|
||
|
|
handleFileSelection(e.dataTransfer.files);
|
||
|
|
}
|
||
|
|
}, false);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
// Tool Configurations
|
||
|
|
const toolConfigs = {
|
||
|
|
resize: {
|
||
|
|
title: "Resize Images",
|
||
|
|
desc: "Change image dimensions while maintaining quality.",
|
||
|
|
controls: `
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Height (px)</label>
|
||
|
|
<input type="number" id="param-height" placeholder="Height">
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Width (px)</label>
|
||
|
|
<input type="number" id="param-width" placeholder="Width">
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<label>
|
||
|
|
<input type="checkbox" id="param-maintain" checked> Maintain Aspect Ratio
|
||
|
|
</label>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
convert: {
|
||
|
|
title: "Convert Formats",
|
||
|
|
desc: "Convert images between PNG, JPG, WEBP, HEIC, and more.",
|
||
|
|
controls: `
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Target Format</label>
|
||
|
|
<select id="param-format">
|
||
|
|
<option value="png">PNG</option>
|
||
|
|
<option value="jpg">JPG</option>
|
||
|
|
<option value="webp">WEBP</option>
|
||
|
|
<option value="bmp">BMP</option>
|
||
|
|
<option value="tiff">TIFF</option>
|
||
|
|
<option value="ico">ICO</option>
|
||
|
|
<option value="heic">HEIC</option>
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Quality (1-100)</label>
|
||
|
|
<input type="number" id="param-quality" value="95" min="1" max="100">
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
compress: {
|
||
|
|
title: "Compress Images",
|
||
|
|
desc: "Reduce file size optimized for web (Lossless-ish/High Efficiency).",
|
||
|
|
controls: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Output Format</label>
|
||
|
|
<select id="param-format" onchange="debounceSimulate()">
|
||
|
|
<option value="original">Original Format - Best for preserving exact type</option>
|
||
|
|
<option value="jpg">JPG - Best for photos, highly compressible</option>
|
||
|
|
<option value="png">PNG - Lossless, best for graphics/transparency</option>
|
||
|
|
<option value="webp">WEBP - Next-gen format, superior compression</option>
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Compression Level / Quality</label>
|
||
|
|
<input type="range" id="param-quality" min="1" max="100" value="80" oninput="this.nextElementSibling.innerText = this.value + '%'; debounceSimulate()">
|
||
|
|
<span style="float: right; font-weight: bold; color: var(--primary);">80%</span>
|
||
|
|
</div>
|
||
|
|
<div id="compression-stats" style="margin-top: 15px; padding: 15px; background: #0f172a; border: 1px solid var(--border); border-radius: 6px; font-size: 0.9rem;">
|
||
|
|
<div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
|
||
|
|
<span style="color: var(--text-secondary);">Original Est:</span>
|
||
|
|
<span id="stat-orig" style="color: #fff; font-family: monospace;">--</span>
|
||
|
|
</div>
|
||
|
|
<div style="display: flex; justify-content: space-between; margin-bottom: 8px;">
|
||
|
|
<span style="color: var(--text-secondary);">New Est:</span>
|
||
|
|
<span id="stat-new" style="color: var(--secondary); font-weight: bold; font-family: monospace;">--</span>
|
||
|
|
</div>
|
||
|
|
<div style="text-align: right; font-size: 0.85rem; color: #94a3b8; border-top: 1px solid #334155; padding-top: 8px;" id="stat-diff">
|
||
|
|
Select an image to see stats
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
crop: {
|
||
|
|
title: "Crop Images",
|
||
|
|
desc: "Trim images to specific coordinates.",
|
||
|
|
controls: `
|
||
|
|
<div class="grid-4">
|
||
|
|
<div class="input-group"><label>Left</label><input type="number" id="param-left" value="0"></div>
|
||
|
|
<div class="input-group"><label>Top</label><input type="number" id="param-top" value="0"></div>
|
||
|
|
<div class="input-group"><label>Right</label><input type="number" id="param-right" value="800"></div>
|
||
|
|
<div class="input-group"><label>Bottom</label><input type="number" id="param-bottom" value="600"></div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
filter: {
|
||
|
|
title: "Apply Filters",
|
||
|
|
desc: "Enhance images with artistic effects.",
|
||
|
|
controls: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Select Filter</label>
|
||
|
|
<select id="param-filter">
|
||
|
|
<option value="BLUR">Blur</option>
|
||
|
|
<option value="SHARPEN">Sharpen</option>
|
||
|
|
<option value="GRAYSCALE">Grayscale</option>
|
||
|
|
<option value="SEPIA">Sepia</option>
|
||
|
|
<option value="INVERT">Invert Colors</option>
|
||
|
|
<option value="EMBOSS">Emboss</option>
|
||
|
|
<option value="CONTOUR">Contour</option>
|
||
|
|
<option value="EDGE_ENHANCE">Edge Enhance</option>
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
rotate: {
|
||
|
|
title: "Rotate & Flip",
|
||
|
|
desc: "Change orientation of images.",
|
||
|
|
controls: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Operation</label>
|
||
|
|
<select id="param-operation">
|
||
|
|
<option value="90">Rotate 90° CW</option>
|
||
|
|
<option value="180">Rotate 180°</option>
|
||
|
|
<option value="270">Rotate 270° CW</option>
|
||
|
|
<option value="FLIP_H">Flip Horizontal</option>
|
||
|
|
<option value="FLIP_V">Flip Vertical</option>
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
watermark: {
|
||
|
|
title: "Add Watermark",
|
||
|
|
desc: "Overlay logo or text image.",
|
||
|
|
controls: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Watermark Image</label>
|
||
|
|
<input type="file" id="param-watermark-file" accept="image/*">
|
||
|
|
</div>
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Position</label>
|
||
|
|
<select id="param-position">
|
||
|
|
<option value="bottom_right">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 (%)</label>
|
||
|
|
<input type="number" id="param-opacity" value="50" min="0" max="100">
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
masker: {
|
||
|
|
title: "Mask Generator",
|
||
|
|
desc: "Draw over the object to create a binary mask.",
|
||
|
|
controls: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Brush Size</label>
|
||
|
|
<input type="range" id="param-brush-size" min="5" max="100" value="30" oninput="this.nextElementSibling.innerText = this.value + 'px'; updateBrushCursor(this.value)">
|
||
|
|
<span style="float: right; font-weight: bold; color: var(--primary);">30px</span>
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<p style="font-size: 0.9rem; color: #94a3b8;">Draw with the red brush over the area you want to mask. The output will be white on black background.</p>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
},
|
||
|
|
};
|
||
|
|
|
||
|
|
// Init
|
||
|
|
document.addEventListener("DOMContentLoaded", () => {
|
||
|
|
renderControls();
|
||
|
|
|
||
|
|
// Drag and Drop
|
||
|
|
const dropZone = document.getElementById("drop-zone");
|
||
|
|
|
||
|
|
["dragenter", "dragover", "dragleave", "drop"].forEach((eventName) => {
|
||
|
|
dropZone.addEventListener(eventName, preventDefaults, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
function preventDefaults(e) {
|
||
|
|
e.preventDefault();
|
||
|
|
e.stopPropagation();
|
||
|
|
}
|
||
|
|
|
||
|
|
["dragenter", "dragover"].forEach((eventName) => {
|
||
|
|
dropZone.addEventListener(eventName, highlight, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
["dragleave", "drop"].forEach((eventName) => {
|
||
|
|
dropZone.addEventListener(eventName, unhighlight, false);
|
||
|
|
});
|
||
|
|
|
||
|
|
function highlight(e) {
|
||
|
|
dropZone.classList.add("dragover");
|
||
|
|
}
|
||
|
|
function unhighlight(e) {
|
||
|
|
dropZone.classList.remove("dragover");
|
||
|
|
}
|
||
|
|
|
||
|
|
dropZone.addEventListener("drop", handleDrop, false);
|
||
|
|
|
||
|
|
function handleDrop(e) {
|
||
|
|
const dt = e.dataTransfer;
|
||
|
|
document.getElementById("file-input").files = dt.files;
|
||
|
|
handleFileSelect(document.getElementById("file-input"));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
function switchTool(tool, element) {
|
||
|
|
currentTool = tool;
|
||
|
|
|
||
|
|
// Update UI Sidebar
|
||
|
|
document
|
||
|
|
.querySelectorAll(".nav-item")
|
||
|
|
.forEach((el) => el.classList.remove("active"));
|
||
|
|
|
||
|
|
let targetEl = element || (typeof event !== "undefined" && event ? (event.currentTarget || event.target?.closest?.(".nav-item")) : null);
|
||
|
|
if (!targetEl) {
|
||
|
|
targetEl = document.querySelector(`.nav-item[data-tool="${tool}"]`);
|
||
|
|
}
|
||
|
|
if (targetEl) {
|
||
|
|
targetEl.classList.add("active");
|
||
|
|
}
|
||
|
|
|
||
|
|
if (tool === "batch") {
|
||
|
|
document.getElementById("single-tool-wrapper").style.display = "none";
|
||
|
|
document.getElementById("batch-view").style.display = "block";
|
||
|
|
document.getElementById("tool-title").innerText = "Batch Processing";
|
||
|
|
document.getElementById("tool-desc").innerText =
|
||
|
|
"Process entire folders locally via the server.";
|
||
|
|
updateBatchControls();
|
||
|
|
} else {
|
||
|
|
document.getElementById("single-tool-wrapper").style.display =
|
||
|
|
"block";
|
||
|
|
document.getElementById("batch-view").style.display = "none";
|
||
|
|
document.getElementById("results-area").innerHTML = "";
|
||
|
|
|
||
|
|
const config = toolConfigs[tool];
|
||
|
|
document.getElementById("tool-title").innerText = config.title;
|
||
|
|
document.getElementById("tool-desc").innerText = config.desc;
|
||
|
|
renderControls();
|
||
|
|
|
||
|
|
// Re-bind resize logic if we have an image loaded and swtiched back to resize
|
||
|
|
if (currentTool === "resize" && currentFiles.length > 0) {
|
||
|
|
setupResizeLogic(currentFiles[0]);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Trigger compression sim if switching to compress
|
||
|
|
if (currentTool === "compress" && currentFiles.length > 0) {
|
||
|
|
simulateCompression();
|
||
|
|
}
|
||
|
|
|
||
|
|
// Trigger masker setup if switching to masker
|
||
|
|
if (currentTool === "masker" && currentFiles.length > 0) {
|
||
|
|
const reader = new FileReader();
|
||
|
|
reader.onload = (e) =>
|
||
|
|
setupMaskerLogic(currentFiles[0], e.target.result);
|
||
|
|
reader.readAsDataURL(currentFiles[0]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
window.switchTool = switchTool;
|
||
|
|
|
||
|
|
function renderControls() {
|
||
|
|
document.getElementById("controls-area").innerHTML =
|
||
|
|
toolConfigs[currentTool].controls;
|
||
|
|
}
|
||
|
|
|
||
|
|
function triggerFileInput() {
|
||
|
|
document.getElementById("file-input").click();
|
||
|
|
}
|
||
|
|
|
||
|
|
// Debounce logic for compression simulation
|
||
|
|
let debounceTimer;
|
||
|
|
function debounceSimulate() {
|
||
|
|
clearTimeout(debounceTimer);
|
||
|
|
debounceTimer = setTimeout(simulateCompression, 500);
|
||
|
|
}
|
||
|
|
|
||
|
|
async function simulateCompression() {
|
||
|
|
// Only valid for single file compression tool
|
||
|
|
if (currentTool !== "compress" || currentFiles.length === 0) return;
|
||
|
|
|
||
|
|
const file = currentFiles[0]; // Simulate first file only
|
||
|
|
const quality = document.getElementById("param-quality").value;
|
||
|
|
const format = document.getElementById("param-format").value;
|
||
|
|
|
||
|
|
const formData = new FormData();
|
||
|
|
formData.append("image", file);
|
||
|
|
formData.append("quality", quality);
|
||
|
|
formData.append("format", format);
|
||
|
|
|
||
|
|
document.getElementById("stat-new").innerText = "Calculating...";
|
||
|
|
|
||
|
|
try {
|
||
|
|
const res = await fetch("/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 fmtSize = (s) => (s > 1024 * 1024 ? toMB(s) : toKB(s));
|
||
|
|
|
||
|
|
document.getElementById("stat-orig").innerText = fmtSize(
|
||
|
|
data.original_size,
|
||
|
|
);
|
||
|
|
document.getElementById("stat-new").innerText = fmtSize(
|
||
|
|
data.new_size,
|
||
|
|
);
|
||
|
|
document.getElementById("stat-diff").innerText =
|
||
|
|
`Reduction: ${data.reduction}%`;
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
console.error("Simulation failed", e);
|
||
|
|
document.getElementById("stat-new").innerText = "Error";
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function handleFileSelect(input) {
|
||
|
|
if (input.files.length > 0) {
|
||
|
|
currentFiles = input.files;
|
||
|
|
const file = input.files[0];
|
||
|
|
|
||
|
|
// 1. Show Preview in Drop Zone
|
||
|
|
const reader = new FileReader();
|
||
|
|
reader.onload = function (e) {
|
||
|
|
const dropZone = document.getElementById("drop-zone");
|
||
|
|
dropZone.innerHTML = `
|
||
|
|
<div style="height: 100%; display: flex; align-items: center; justify-content: center; overflow: hidden;">
|
||
|
|
<img src="${e.target.result}" style="max-width: 100%; max-height: 500px; object-fit: contain; border-radius: 8px;">
|
||
|
|
</div>
|
||
|
|
`;
|
||
|
|
dropZone.style.padding = "10px";
|
||
|
|
dropZone.style.minHeight = "300px";
|
||
|
|
dropZone.style.height = "auto";
|
||
|
|
|
||
|
|
// 2. Setup Resize Logic if relevant
|
||
|
|
if (currentTool === "resize") {
|
||
|
|
setupResizeLogic(file, e.target.result);
|
||
|
|
}
|
||
|
|
// 3. Trigger Compress Sim if relevant
|
||
|
|
if (currentTool === "compress") {
|
||
|
|
simulateCompression();
|
||
|
|
}
|
||
|
|
// 4. Setup Masker
|
||
|
|
if (currentTool === "masker") {
|
||
|
|
setupMaskerLogic(file, e.target.result);
|
||
|
|
}
|
||
|
|
};
|
||
|
|
reader.readAsDataURL(file);
|
||
|
|
|
||
|
|
showToast(`${input.files.length} file(s) selected`, "success");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Logic for auto-calculating aspect ratio
|
||
|
|
function setupResizeLogic(file, dataUrl) {
|
||
|
|
if (!dataUrl) {
|
||
|
|
const reader = new FileReader();
|
||
|
|
reader.onload = (e) => setupResizeLogic(file, e.target.result);
|
||
|
|
reader.readAsDataURL(file);
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const img = new Image();
|
||
|
|
img.onload = function () {
|
||
|
|
const wInput = document.getElementById("param-width");
|
||
|
|
const hInput = document.getElementById("param-height");
|
||
|
|
const maintainCheck = document.getElementById("param-maintain");
|
||
|
|
|
||
|
|
if (!wInput || !hInput) return; // switched tool already
|
||
|
|
|
||
|
|
// Set initial values
|
||
|
|
wInput.value = this.width;
|
||
|
|
hInput.value = this.height;
|
||
|
|
|
||
|
|
const aspectRatio = this.width / this.height;
|
||
|
|
|
||
|
|
// Listeners
|
||
|
|
hInput.addEventListener("input", () => {
|
||
|
|
if (maintainCheck.checked && hInput.value) {
|
||
|
|
wInput.value = Math.round(hInput.value * aspectRatio);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
wInput.addEventListener("input", () => {
|
||
|
|
if (maintainCheck.checked && wInput.value) {
|
||
|
|
hInput.value = Math.round(wInput.value / aspectRatio);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
};
|
||
|
|
img.src = dataUrl;
|
||
|
|
}
|
||
|
|
|
||
|
|
function showToast(msg, type = "info") {
|
||
|
|
const container = document.getElementById("toast-container");
|
||
|
|
const toast = document.createElement("div");
|
||
|
|
toast.className = `toast ${type}`;
|
||
|
|
toast.innerHTML =
|
||
|
|
type === "success"
|
||
|
|
? `<i class="fa-solid fa-check-circle"></i> ${msg}`
|
||
|
|
: `<i class="fa-solid fa-circle-exclamation"></i> ${msg}`;
|
||
|
|
container.appendChild(toast);
|
||
|
|
setTimeout(() => toast.remove(), 4000);
|
||
|
|
}
|
||
|
|
|
||
|
|
function showLoader(show) {
|
||
|
|
const loader = document.getElementById("loader");
|
||
|
|
if (show) loader.classList.add("active");
|
||
|
|
else loader.classList.remove("active");
|
||
|
|
}
|
||
|
|
|
||
|
|
async function executeProcess() {
|
||
|
|
if (!currentFiles || currentFiles.length === 0) {
|
||
|
|
showToast("Please select images first", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const formData = new FormData();
|
||
|
|
for (let file of currentFiles) {
|
||
|
|
formData.append("images", file);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Handle Masker special case (needs async processing of canvas)
|
||
|
|
if (currentTool === "masker") {
|
||
|
|
if (!maskCanvas) {
|
||
|
|
showToast("No mask canvas active", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Generate binary mask
|
||
|
|
const outCanvas = document.createElement("canvas");
|
||
|
|
outCanvas.width = maskCanvas.width;
|
||
|
|
outCanvas.height = maskCanvas.height;
|
||
|
|
const ctx = outCanvas.getContext("2d");
|
||
|
|
|
||
|
|
// Fill Black
|
||
|
|
ctx.fillStyle = "#000000";
|
||
|
|
ctx.fillRect(0, 0, outCanvas.width, outCanvas.height);
|
||
|
|
|
||
|
|
// Replay strokes in White
|
||
|
|
ctx.lineCap = "round";
|
||
|
|
ctx.lineJoin = "round";
|
||
|
|
ctx.strokeStyle = "#ffffff";
|
||
|
|
|
||
|
|
maskStrokes.forEach((stroke) => {
|
||
|
|
ctx.lineWidth = stroke.size;
|
||
|
|
ctx.beginPath();
|
||
|
|
if (stroke.points.length > 0) {
|
||
|
|
ctx.moveTo(stroke.points[0].x, stroke.points[0].y);
|
||
|
|
stroke.points.forEach((p) => ctx.lineTo(p.x, p.y));
|
||
|
|
}
|
||
|
|
ctx.stroke();
|
||
|
|
});
|
||
|
|
|
||
|
|
outCanvas.toBlob(async (blob) => {
|
||
|
|
const formData = new FormData();
|
||
|
|
formData.append("images", blob, "mask.png");
|
||
|
|
|
||
|
|
showLoader(true);
|
||
|
|
try {
|
||
|
|
const res = await fetch("/mask", {
|
||
|
|
method: "POST",
|
||
|
|
body: formData,
|
||
|
|
});
|
||
|
|
const data = await res.json();
|
||
|
|
if (res.ok) {
|
||
|
|
renderResults(data.results);
|
||
|
|
showToast("Mask generated!", "success");
|
||
|
|
} else {
|
||
|
|
showToast(data.error, "error");
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
showToast("Network error", "error");
|
||
|
|
} finally {
|
||
|
|
showLoader(false);
|
||
|
|
}
|
||
|
|
});
|
||
|
|
return; // Exit normal flow
|
||
|
|
}
|
||
|
|
|
||
|
|
// Append params specific to tool
|
||
|
|
if (currentTool === "resize") {
|
||
|
|
formData.append(
|
||
|
|
"width",
|
||
|
|
document.getElementById("param-width").value,
|
||
|
|
);
|
||
|
|
formData.append(
|
||
|
|
"height",
|
||
|
|
document.getElementById("param-height").value,
|
||
|
|
);
|
||
|
|
formData.append(
|
||
|
|
"maintain_aspect",
|
||
|
|
document.getElementById("param-maintain").checked,
|
||
|
|
);
|
||
|
|
} else if (currentTool === "convert") {
|
||
|
|
formData.append(
|
||
|
|
"format",
|
||
|
|
document.getElementById("param-format").value,
|
||
|
|
);
|
||
|
|
formData.append(
|
||
|
|
"quality",
|
||
|
|
document.getElementById("param-quality").value,
|
||
|
|
);
|
||
|
|
} else if (currentTool === "compress") {
|
||
|
|
formData.append(
|
||
|
|
"quality",
|
||
|
|
document.getElementById("param-quality").value,
|
||
|
|
);
|
||
|
|
// Added format support
|
||
|
|
const fmt = document.getElementById("param-format");
|
||
|
|
if (fmt) formData.append("format", fmt.value);
|
||
|
|
} else if (currentTool === "crop") {
|
||
|
|
formData.append("left", document.getElementById("param-left").value);
|
||
|
|
formData.append("top", document.getElementById("param-top").value);
|
||
|
|
formData.append(
|
||
|
|
"right",
|
||
|
|
document.getElementById("param-right").value,
|
||
|
|
);
|
||
|
|
formData.append(
|
||
|
|
"bottom",
|
||
|
|
document.getElementById("param-bottom").value,
|
||
|
|
);
|
||
|
|
} else if (currentTool === "filter") {
|
||
|
|
formData.append(
|
||
|
|
"filter",
|
||
|
|
document.getElementById("param-filter").value,
|
||
|
|
);
|
||
|
|
} else if (currentTool === "rotate") {
|
||
|
|
formData.append(
|
||
|
|
"operation",
|
||
|
|
document.getElementById("param-operation").value,
|
||
|
|
);
|
||
|
|
} else if (currentTool === "watermark") {
|
||
|
|
const wmFile = document.getElementById("param-watermark-file")
|
||
|
|
.files[0];
|
||
|
|
if (!wmFile) {
|
||
|
|
showToast("Select watermark image", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
formData.append("watermark", wmFile);
|
||
|
|
formData.append(
|
||
|
|
"position",
|
||
|
|
document.getElementById("param-position").value,
|
||
|
|
);
|
||
|
|
formData.append(
|
||
|
|
"opacity",
|
||
|
|
document.getElementById("param-opacity").value,
|
||
|
|
);
|
||
|
|
}
|
||
|
|
|
||
|
|
showLoader(true);
|
||
|
|
try {
|
||
|
|
const res = await fetch(`/${currentTool}`, {
|
||
|
|
method: "POST",
|
||
|
|
body: formData,
|
||
|
|
});
|
||
|
|
const data = await res.json();
|
||
|
|
|
||
|
|
if (res.ok) {
|
||
|
|
renderResults(data.results);
|
||
|
|
showToast("Processing complete!", "success");
|
||
|
|
} else {
|
||
|
|
showToast(data.error || "Processing failed", "error");
|
||
|
|
}
|
||
|
|
} catch (err) {
|
||
|
|
showToast("Network error", "error");
|
||
|
|
} finally {
|
||
|
|
showLoader(false);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function renderResults(results) {
|
||
|
|
const container = document.getElementById("results-area");
|
||
|
|
container.innerHTML = "";
|
||
|
|
|
||
|
|
// Add Download All button if multiple
|
||
|
|
if (results.length > 1) {
|
||
|
|
const btn = document.createElement("button");
|
||
|
|
btn.className = "btn btn-secondary";
|
||
|
|
btn.style.gridColumn = "1 / -1";
|
||
|
|
btn.style.marginBottom = "20px";
|
||
|
|
btn.innerHTML =
|
||
|
|
'<i class="fa-solid fa-file-zipper"></i> Download All as ZIP';
|
||
|
|
btn.onclick = () => downloadAll(results);
|
||
|
|
container.appendChild(btn);
|
||
|
|
}
|
||
|
|
|
||
|
|
results.forEach((res) => {
|
||
|
|
const card = document.createElement("div");
|
||
|
|
card.className = "result-card";
|
||
|
|
card.innerHTML = `
|
||
|
|
<div class="image-preview">
|
||
|
|
<img src="${res.image}" alt="Result">
|
||
|
|
</div>
|
||
|
|
<div class="card-body">
|
||
|
|
<div class="file-name" title="${res.filename}">${res.filename}</div>
|
||
|
|
<div class="file-meta">
|
||
|
|
<span>${res.info.width}x${res.info.height}</span>
|
||
|
|
<span>${res.info.format}</span>
|
||
|
|
</div>
|
||
|
|
<a href="${res.image}" download="${res.filename}" class="download-link">
|
||
|
|
<i class="fa-solid fa-download"></i> Download
|
||
|
|
</a>
|
||
|
|
</div>
|
||
|
|
`;
|
||
|
|
container.appendChild(card);
|
||
|
|
});
|
||
|
|
}
|
||
|
|
|
||
|
|
async function downloadAll(results) {
|
||
|
|
try {
|
||
|
|
const res = await fetch("/download-all", {
|
||
|
|
method: "POST",
|
||
|
|
headers: { "Content-Type": "application/json" },
|
||
|
|
body: JSON.stringify({ images: results }),
|
||
|
|
});
|
||
|
|
if (res.ok) {
|
||
|
|
const blob = await res.blob();
|
||
|
|
const url = window.URL.createObjectURL(blob);
|
||
|
|
const a = document.createElement("a");
|
||
|
|
a.href = url;
|
||
|
|
a.download = "processed_images.zip";
|
||
|
|
document.body.appendChild(a);
|
||
|
|
a.click();
|
||
|
|
a.remove();
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
showToast("Download failed", "error");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// --- Batch Functions ---
|
||
|
|
|
||
|
|
async function browseFolder() {
|
||
|
|
try {
|
||
|
|
const res = await fetch("/select-folder", { method: "POST" });
|
||
|
|
const data = await res.json();
|
||
|
|
if (res.ok && data.path) {
|
||
|
|
document.getElementById("batch-path").value = data.path;
|
||
|
|
showToast("Folder selected!", "success");
|
||
|
|
|
||
|
|
// Auto-calculate folder size if compress operation
|
||
|
|
const op = document.getElementById("batch-operation").value;
|
||
|
|
if (op === "compress") {
|
||
|
|
await calculateFolderSize(data.path);
|
||
|
|
}
|
||
|
|
} else if (!data.path) {
|
||
|
|
// Cancelled
|
||
|
|
} else {
|
||
|
|
showToast("Failed to select folder", "error");
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
showToast("Error opening dialog", "error");
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function calculateFolderSize() {
|
||
|
|
const currentSizeInput = document.getElementById("param-current-size");
|
||
|
|
const currentSizeMbInput = document.getElementById(
|
||
|
|
"param-current-size-mb",
|
||
|
|
);
|
||
|
|
|
||
|
|
if (!currentSizeInput) {
|
||
|
|
console.log("⚠️ Compress controls not rendered yet");
|
||
|
|
return; // Not in compress mode
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!batchFiles || batchFiles.length === 0) {
|
||
|
|
currentSizeInput.value = "0 MB (0 images)";
|
||
|
|
currentSizeMbInput.value = 0;
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
console.log("📊 Calculating folder size locally...");
|
||
|
|
|
||
|
|
let totalBytes = 0;
|
||
|
|
batchFiles.forEach(f => { totalBytes += f.size });
|
||
|
|
let totalMb = (totalBytes / (1024 * 1024)).toFixed(2);
|
||
|
|
|
||
|
|
currentSizeInput.value = `${totalMb} MB (${batchFiles.length} images)`;
|
||
|
|
currentSizeMbInput.value = totalMb;
|
||
|
|
logToConsole(`Folder size: ${totalMb} MB (${batchFiles.length} images)`);
|
||
|
|
console.log("✅ Folder size calculated successfully");
|
||
|
|
}
|
||
|
|
|
||
|
|
function updateBatchControls() {
|
||
|
|
const op = document.getElementById("batch-operation").value;
|
||
|
|
const container = document.getElementById("batch-params");
|
||
|
|
|
||
|
|
// Reuse the HTML from toolConfigs but adapt inputs to regular inputs (no file inputs except watermark path)
|
||
|
|
// Re-fetch since it's cleaner
|
||
|
|
const configs = {
|
||
|
|
resize: `
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group"><label>Height (px)</label><input type="number" id="param-height" placeholder="Auto"></div>
|
||
|
|
<div class="input-group"><label>Width (px)</label><input type="number" id="param-width" placeholder="Auto"></div>
|
||
|
|
</div>
|
||
|
|
<div class="input-group"><label><input type="checkbox" id="param-maintain" checked> Maintain Aspect Ratio (Leave one empty for proportional, or fill both for fit-box)</label></div>
|
||
|
|
`,
|
||
|
|
convert: toolConfigs.convert.controls,
|
||
|
|
compress: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Output Format</label>
|
||
|
|
<select id="param-format">
|
||
|
|
<option value="original">Original Format - Best for preserving exact type</option>
|
||
|
|
<option value="jpg">JPG - Best for photos, highly compressible</option>
|
||
|
|
<option value="png">PNG - Lossless, best for graphics/transparency</option>
|
||
|
|
<option value="webp">WEBP - Next-gen format, superior compression</option>
|
||
|
|
</select>
|
||
|
|
</div>
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Current Folder Size</label>
|
||
|
|
<input type="text" id="param-current-size" readonly placeholder="Calculating..." style="background: #1e293b; cursor: not-allowed;">
|
||
|
|
<input type="hidden" id="param-current-size-mb">
|
||
|
|
</div>
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Target Size (MB)</label>
|
||
|
|
<input type="number" id="param-target-size-mb" placeholder="Enter target size" step="0.1" min="0.1">
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
<div id="compression-info" style="margin-top: 15px; padding: 12px; background: #0f172a; border: 1px solid var(--border); border-radius: 6px; font-size: 0.9rem; display: none;">
|
||
|
|
<div style="color: #94a3b8; margin-bottom: 8px;">Compression Estimate:</div>
|
||
|
|
<div id="compression-estimate" style="color: var(--secondary); font-weight: bold;"></div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
crop: toolConfigs.crop.controls,
|
||
|
|
filter: toolConfigs.filter.controls,
|
||
|
|
rotate: toolConfigs.rotate.controls,
|
||
|
|
watermark: `
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Watermark Image Path (Local)</label>
|
||
|
|
<input type="text" id="param-watermark-path" placeholder="/home/user/logo.png">
|
||
|
|
</div>
|
||
|
|
<div class="grid-2">
|
||
|
|
<div class="input-group">
|
||
|
|
<label>Position</label>
|
||
|
|
<select id="param-position">
|
||
|
|
<option value="bottom_right">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 (%)</label>
|
||
|
|
<input type="number" id="param-opacity" value="50">
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
};
|
||
|
|
|
||
|
|
container.innerHTML = configs[op];
|
||
|
|
|
||
|
|
// Auto-calculate folder size if switching to compress and path already exists
|
||
|
|
if (op === "compress") {
|
||
|
|
setTimeout(() => calculateFolderSize(), 100);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
async function executeBatch() {
|
||
|
|
if (!batchFiles || batchFiles.length === 0) {
|
||
|
|
showToast("Please select images or a folder first", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
const op = document.getElementById("batch-operation").value;
|
||
|
|
|
||
|
|
// Calculate current folder size from selected files
|
||
|
|
const current_size_mb =
|
||
|
|
batchFiles.reduce((sum, f) => sum + f.size, 0) / (1024 * 1024);
|
||
|
|
|
||
|
|
logToConsole(`Starting batch: ${batchFiles.length} files (${current_size_mb.toFixed(2)} MB)...`);
|
||
|
|
|
||
|
|
// Show progress bar container immediately
|
||
|
|
const progressContainer = document.getElementById("batch-progress-container");
|
||
|
|
const progressBar = document.getElementById("batch-progress-bar");
|
||
|
|
const progressLabel = document.getElementById("batch-progress-label");
|
||
|
|
const progressPercent = document.getElementById("batch-progress-percent");
|
||
|
|
const progressDetail = document.getElementById("batch-progress-detail");
|
||
|
|
|
||
|
|
progressContainer.style.display = "block";
|
||
|
|
progressBar.style.width = "0%";
|
||
|
|
progressBar.style.background = "linear-gradient(90deg, var(--primary), var(--secondary))";
|
||
|
|
progressPercent.textContent = "0%";
|
||
|
|
progressLabel.textContent = `Preparing ${batchFiles.length} files for upload...`;
|
||
|
|
progressDetail.textContent = `Total size: ${current_size_mb.toFixed(2)} MB`;
|
||
|
|
showLoader(false);
|
||
|
|
|
||
|
|
// Helper to resolve correct tool URL across direct access, proxy prefixes and domains
|
||
|
|
function getApiUrl(endpoint) {
|
||
|
|
const p = endpoint.startsWith('/') ? endpoint : '/' + endpoint;
|
||
|
|
if (window.location.pathname.startsWith('/tool/image-manipulator')) {
|
||
|
|
return '/tool/image-manipulator' + p;
|
||
|
|
}
|
||
|
|
return p;
|
||
|
|
}
|
||
|
|
|
||
|
|
try {
|
||
|
|
// Optimized chunking tuned for Cloudflare / Nginx / remote proxies (max 15 files / 8MB per chunk)
|
||
|
|
const chunks = [];
|
||
|
|
let currentChunk = [];
|
||
|
|
let currentChunkBytes = 0;
|
||
|
|
const MAX_FILES_PER_CHUNK = 15;
|
||
|
|
const MAX_BYTES_PER_CHUNK = 8 * 1024 * 1024; // 8MB limit per chunk ensures Cloudflare 100MB limit is never approached
|
||
|
|
|
||
|
|
for (const file of batchFiles) {
|
||
|
|
if (currentChunk.length >= MAX_FILES_PER_CHUNK || (currentChunkBytes + file.size > MAX_BYTES_PER_CHUNK && currentChunk.length > 0)) {
|
||
|
|
chunks.push(currentChunk);
|
||
|
|
currentChunk = [];
|
||
|
|
currentChunkBytes = 0;
|
||
|
|
}
|
||
|
|
currentChunk.push(file);
|
||
|
|
currentChunkBytes += file.size;
|
||
|
|
}
|
||
|
|
if (currentChunk.length > 0) {
|
||
|
|
chunks.push(currentChunk);
|
||
|
|
}
|
||
|
|
|
||
|
|
logToConsole(`Uploading in ${chunks.length} proxy-safe batches (max ${MAX_FILES_PER_CHUNK} files / 8MB per chunk)...`);
|
||
|
|
|
||
|
|
let uploadedFilesCount = 0;
|
||
|
|
let activeSessionId = window._batchSessionId || "";
|
||
|
|
|
||
|
|
// Upload chunks sequentially with automatic retry
|
||
|
|
for (let i = 0; i < chunks.length; i++) {
|
||
|
|
const chunk = chunks[i];
|
||
|
|
const chunkPct = Math.round((i / chunks.length) * 100);
|
||
|
|
progressBar.style.width = `${chunkPct}%`;
|
||
|
|
progressPercent.textContent = `${chunkPct}%`;
|
||
|
|
progressLabel.textContent = `Uploading files: ${uploadedFilesCount} of ${batchFiles.length} (${chunkPct}%)...`;
|
||
|
|
progressDetail.textContent = `Batch ${i + 1} of ${chunks.length} (${chunk.length} files in this batch)`;
|
||
|
|
|
||
|
|
const formData = new FormData();
|
||
|
|
formData.append("chunk_index", i.toString());
|
||
|
|
formData.append("total_chunks", chunks.length.toString());
|
||
|
|
formData.append("reset", (i === 0).toString());
|
||
|
|
if (activeSessionId) {
|
||
|
|
formData.append("session_id", activeSessionId);
|
||
|
|
}
|
||
|
|
|
||
|
|
chunk.forEach((file) => {
|
||
|
|
formData.append("files", file);
|
||
|
|
formData.append(
|
||
|
|
"relative_paths",
|
||
|
|
file.webkitRelativePath || file.name,
|
||
|
|
);
|
||
|
|
});
|
||
|
|
|
||
|
|
// Resilient upload with 3 attempts
|
||
|
|
let uploadSuccess = false;
|
||
|
|
let lastErr = null;
|
||
|
|
for (let attempt = 1; attempt <= 3; attempt++) {
|
||
|
|
try {
|
||
|
|
const uploadRes = await fetch(getApiUrl("/upload-batch"), {
|
||
|
|
method: "POST",
|
||
|
|
headers: activeSessionId ? { "X-Session-ID": activeSessionId } : {},
|
||
|
|
body: formData,
|
||
|
|
});
|
||
|
|
if (!uploadRes.ok) {
|
||
|
|
const txt = await uploadRes.text();
|
||
|
|
throw new Error(`HTTP ${uploadRes.status}: ${txt}`);
|
||
|
|
}
|
||
|
|
const uploadData = await uploadRes.json();
|
||
|
|
if (uploadData.session_id) {
|
||
|
|
activeSessionId = uploadData.session_id;
|
||
|
|
window._batchSessionId = activeSessionId;
|
||
|
|
}
|
||
|
|
uploadSuccess = true;
|
||
|
|
break;
|
||
|
|
} catch (err) {
|
||
|
|
lastErr = err;
|
||
|
|
logToConsole(`⚠️ Batch ${i + 1} attempt ${attempt} failed: ${err.message}. Retrying...`, "warn");
|
||
|
|
await new Promise((r) => setTimeout(r, 1000 * attempt));
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (!uploadSuccess) {
|
||
|
|
throw new Error(`Upload failed on batch ${i + 1} of ${chunks.length}: ${lastErr ? lastErr.message : "network failure"}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
uploadedFilesCount += chunk.length;
|
||
|
|
}
|
||
|
|
|
||
|
|
progressBar.style.width = "100%";
|
||
|
|
progressPercent.textContent = "100%";
|
||
|
|
progressLabel.textContent = `✓ Uploaded all ${batchFiles.length} files (${current_size_mb.toFixed(2)} MB)`;
|
||
|
|
progressDetail.textContent = "Initializing image processing engine...";
|
||
|
|
logToConsole(`\u2713 All ${batchFiles.length} files uploaded successfully (${current_size_mb.toFixed(2)} MB)`);
|
||
|
|
|
||
|
|
// Collect params
|
||
|
|
const params = {};
|
||
|
|
const inputs = document
|
||
|
|
.getElementById("batch-params")
|
||
|
|
.querySelectorAll("input, select");
|
||
|
|
inputs.forEach((input) => {
|
||
|
|
const key = input.id.replace("param-", "").replace(/-/g, "_");
|
||
|
|
if (input.type === "checkbox") params[key] = input.checked;
|
||
|
|
else if (input.value) params[key] = input.value;
|
||
|
|
});
|
||
|
|
|
||
|
|
// Add current size for compression calculation
|
||
|
|
params["current_size_mb"] = current_size_mb;
|
||
|
|
|
||
|
|
// Reset progress bar for processing phase
|
||
|
|
progressBar.style.width = "0%";
|
||
|
|
progressPercent.textContent = "0%";
|
||
|
|
progressLabel.textContent = `Processing ${op}...`;
|
||
|
|
progressDetail.textContent = "Starting operations on images...";
|
||
|
|
|
||
|
|
// Process with SSE streaming
|
||
|
|
logToConsole(`Processing ${op}...`);
|
||
|
|
const processRes = await fetch(getApiUrl("/batch-process-session"), {
|
||
|
|
method: "POST",
|
||
|
|
headers: {
|
||
|
|
"Content-Type": "application/json",
|
||
|
|
...(activeSessionId ? { "X-Session-ID": activeSessionId } : {}),
|
||
|
|
},
|
||
|
|
body: JSON.stringify({
|
||
|
|
operation: op,
|
||
|
|
params: params,
|
||
|
|
session_id: activeSessionId,
|
||
|
|
}),
|
||
|
|
});
|
||
|
|
|
||
|
|
if (!processRes.ok) {
|
||
|
|
const errTxt = await processRes.text();
|
||
|
|
throw new Error(`Processing failed (${processRes.status}): ${errTxt}`);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Read SSE stream
|
||
|
|
const reader = processRes.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 });
|
||
|
|
|
||
|
|
// Parse SSE events from buffer
|
||
|
|
const lines = buffer.split("\n");
|
||
|
|
buffer = lines.pop(); // Keep incomplete line in buffer
|
||
|
|
|
||
|
|
for (const line of lines) {
|
||
|
|
if (line.startsWith(":")) {
|
||
|
|
// Keep-alive heartbeat from server, ignore
|
||
|
|
continue;
|
||
|
|
}
|
||
|
|
if (line.startsWith("data: ")) {
|
||
|
|
try {
|
||
|
|
const event = JSON.parse(line.substring(6));
|
||
|
|
|
||
|
|
if (event.type === "progress") {
|
||
|
|
const pct = Math.round((event.current / event.total) * 100);
|
||
|
|
progressBar.style.width = `${pct}%`;
|
||
|
|
progressPercent.textContent = `${pct}%`;
|
||
|
|
progressLabel.textContent = `Processing ${event.current} of ${event.total}`;
|
||
|
|
|
||
|
|
if (event.error) {
|
||
|
|
progressDetail.textContent = `\u26A0 ${event.filename}: Error`;
|
||
|
|
} else if (event.reduction !== undefined) {
|
||
|
|
progressDetail.textContent = `${event.filename}: ${event.original_kb.toFixed(1)}KB \u2192 ${event.compressed_kb.toFixed(1)}KB (-${event.reduction.toFixed(1)}%)`;
|
||
|
|
} else {
|
||
|
|
progressDetail.textContent = `\u2713 ${event.filename}`;
|
||
|
|
}
|
||
|
|
} else if (event.type === "complete") {
|
||
|
|
lastResult = event;
|
||
|
|
}
|
||
|
|
} catch (parseErr) {
|
||
|
|
// Ignore malformed SSE lines
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
if (lastResult) {
|
||
|
|
// Update progress bar to 100%
|
||
|
|
progressBar.style.width = "100%";
|
||
|
|
progressPercent.textContent = "100%";
|
||
|
|
progressBar.style.background = "linear-gradient(90deg, #10b981, #34d399)";
|
||
|
|
progressLabel.textContent = `\u2713 Completed! ${lastResult.processed_count} files processed`;
|
||
|
|
|
||
|
|
if (lastResult.total_original_mb && lastResult.total_compressed_mb) {
|
||
|
|
const totalReduction = ((1 - lastResult.total_compressed_mb / lastResult.total_original_mb) * 100).toFixed(1);
|
||
|
|
progressDetail.textContent = `${lastResult.total_original_mb.toFixed(2)} MB \u2192 ${lastResult.total_compressed_mb.toFixed(2)} MB (${totalReduction}% total reduction)`;
|
||
|
|
logToConsole(`\u2713 ${lastResult.total_original_mb.toFixed(2)} MB \u2192 ${lastResult.total_compressed_mb.toFixed(2)} MB (${totalReduction}% reduction)`);
|
||
|
|
} else {
|
||
|
|
progressDetail.textContent = `Successfully processed ${lastResult.processed_count} images.`;
|
||
|
|
}
|
||
|
|
|
||
|
|
logToConsole(`\u2713 Done: ${lastResult.processed_count} files processed`);
|
||
|
|
if (lastResult.error_count > 0) {
|
||
|
|
logToConsole(`\u26A0 ${lastResult.error_count} errors encountered`);
|
||
|
|
}
|
||
|
|
|
||
|
|
// Store zip_name for download
|
||
|
|
if (lastResult.zip_name) {
|
||
|
|
window._batchZipName = lastResult.zip_name;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Download
|
||
|
|
logToConsole("Preparing ZIP download...");
|
||
|
|
const dlSessionId = lastResult.session_id || activeSessionId || "";
|
||
|
|
const dlZipName = lastResult.zip_name || window._batchZipName || "processed_images.zip";
|
||
|
|
const dlUrl = getApiUrl(`/download-batch?session_id=${encodeURIComponent(dlSessionId)}&zip_name=${encodeURIComponent(dlZipName)}`);
|
||
|
|
|
||
|
|
try {
|
||
|
|
const res = await fetch(dlUrl, {
|
||
|
|
headers: dlSessionId ? { "X-Session-ID": dlSessionId } : {},
|
||
|
|
});
|
||
|
|
if (res.ok) {
|
||
|
|
const blob = await res.blob();
|
||
|
|
const url = window.URL.createObjectURL(blob);
|
||
|
|
const a = document.createElement("a");
|
||
|
|
a.href = url;
|
||
|
|
a.download = dlZipName;
|
||
|
|
document.body.appendChild(a);
|
||
|
|
a.click();
|
||
|
|
a.remove();
|
||
|
|
window.URL.revokeObjectURL(url);
|
||
|
|
showToast("Complete! Download started", "success");
|
||
|
|
} else {
|
||
|
|
throw new Error("Download request status " + res.status);
|
||
|
|
}
|
||
|
|
} catch (dlErr) {
|
||
|
|
logToConsole("Direct blob download failed, falling back to direct navigation: " + dlErr.message);
|
||
|
|
window.location.href = dlUrl;
|
||
|
|
showToast("Complete! Download started", "success");
|
||
|
|
}
|
||
|
|
} else {
|
||
|
|
throw new Error("No completion event received from server");
|
||
|
|
}
|
||
|
|
|
||
|
|
} catch (error) {
|
||
|
|
logToConsole(`\u274C Error: ${error.message}`, "error");
|
||
|
|
showToast(error.message, "error");
|
||
|
|
// Reset progress bar on error
|
||
|
|
progressBar.style.background = "linear-gradient(90deg, #ef4444, #f87171)";
|
||
|
|
progressLabel.textContent = "Batch Processing Failed";
|
||
|
|
progressDetail.textContent = error.message;
|
||
|
|
} finally {
|
||
|
|
showLoader(false);
|
||
|
|
}
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
async function previewBatch() {
|
||
|
|
let filesToPreview = [];
|
||
|
|
let totalCount = 0;
|
||
|
|
let totalSizeMb = 0;
|
||
|
|
|
||
|
|
if (batchFiles && batchFiles.length > 0) {
|
||
|
|
totalCount = batchFiles.length;
|
||
|
|
const totalBytes = batchFiles.reduce((acc, f) => acc + f.size, 0);
|
||
|
|
totalSizeMb = (totalBytes / (1024 * 1024)).toFixed(2);
|
||
|
|
filesToPreview = batchFiles.slice(0, 50).map((f) => ({
|
||
|
|
filename: f.webkitRelativePath || f.name,
|
||
|
|
size: f.size,
|
||
|
|
size_kb: (f.size / 1024).toFixed(1),
|
||
|
|
}));
|
||
|
|
} else {
|
||
|
|
try {
|
||
|
|
showLoader(true);
|
||
|
|
const res = await fetch("/preview-batch", {
|
||
|
|
headers: window._batchSessionId ? { "X-Session-ID": window._batchSessionId } : {},
|
||
|
|
});
|
||
|
|
const data = await res.json();
|
||
|
|
showLoader(false);
|
||
|
|
if (res.ok && data.count > 0) {
|
||
|
|
totalCount = data.count;
|
||
|
|
totalSizeMb = data.total_size_mb;
|
||
|
|
filesToPreview = (data.files || []).slice(0, 50);
|
||
|
|
} else {
|
||
|
|
showToast("No files selected yet. Click 'Select Folder' or 'Select Files' first.", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
} catch (e) {
|
||
|
|
showLoader(false);
|
||
|
|
showToast("No files selected yet. Click 'Select Folder' or 'Select Files' first.", "error");
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
// Create modal
|
||
|
|
const modal = document.createElement("div");
|
||
|
|
modal.style.cssText = `
|
||
|
|
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
|
||
|
|
background: rgba(0,0,0,0.8); z-index: 10000;
|
||
|
|
display: flex; align-items: center; justify-content: center;
|
||
|
|
`;
|
||
|
|
|
||
|
|
const content = document.createElement("div");
|
||
|
|
content.style.cssText = `
|
||
|
|
background: var(--bg-card); border-radius: 16px; padding: 32px;
|
||
|
|
max-width: 650px; width: 90%; max-height: 80vh; overflow-y: auto;
|
||
|
|
border: 1px solid var(--border);
|
||
|
|
`;
|
||
|
|
|
||
|
|
content.innerHTML = `
|
||
|
|
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
|
||
|
|
<h3 style="color: var(--primary); font-size: 1.4rem; margin: 0;">
|
||
|
|
<i class="fa-solid fa-list-check"></i> Files Ready for Processing
|
||
|
|
</h3>
|
||
|
|
<button onclick="this.closest('[style*=\\'fixed\\']').remove()" style="background: none; border: none; color: var(--text-secondary); font-size: 1.5rem; cursor: pointer;">
|
||
|
|
<i class="fa-solid fa-times"></i>
|
||
|
|
</button>
|
||
|
|
</div>
|
||
|
|
<div style="background: rgba(255,108,55,0.1); border: 1px solid rgba(255,108,55,0.25); padding: 14px 18px; border-radius: 8px; margin-bottom: 20px;">
|
||
|
|
<div style="font-size: 1.05rem; color: var(--primary); font-weight: 600;">
|
||
|
|
${totalCount} file(s) selected | ${totalSizeMb} MB total
|
||
|
|
</div>
|
||
|
|
${totalCount > 50 ? `<div style="font-size: 0.85rem; color: var(--text-secondary); margin-top: 4px;">Showing first 50 files</div>` : ""}
|
||
|
|
</div>
|
||
|
|
<div style="display: flex; flex-direction: column; gap: 8px;">
|
||
|
|
${filesToPreview
|
||
|
|
.map(
|
||
|
|
(f) => `
|
||
|
|
<div style="display: flex; justify-content: space-between; align-items: center; padding: 10px 14px; background: rgba(255,255,255,0.03); border: 1px solid var(--border); border-radius: 6px; font-size: 0.88rem;">
|
||
|
|
<span style="font-family: monospace; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 440px;" title="${f.filename}">
|
||
|
|
${f.filename}
|
||
|
|
</span>
|
||
|
|
<span style="color: var(--text-secondary); font-weight: 500; font-size: 0.8rem; white-space: nowrap;">
|
||
|
|
${f.size_kb || (f.size / 1024).toFixed(1)} KB
|
||
|
|
</span>
|
||
|
|
</div>
|
||
|
|
`,
|
||
|
|
)
|
||
|
|
.join("")}
|
||
|
|
</div>
|
||
|
|
`;
|
||
|
|
|
||
|
|
modal.appendChild(content);
|
||
|
|
modal.onclick = (e) => {
|
||
|
|
if (e.target === modal) modal.remove();
|
||
|
|
};
|
||
|
|
document.body.appendChild(modal);
|
||
|
|
}
|
||
|
|
|
||
|
|
function logToConsole(msg, type = "info") {
|
||
|
|
const console = document.getElementById("batch-console");
|
||
|
|
const line = document.createElement("div");
|
||
|
|
line.className = "console-line";
|
||
|
|
if (type === "error") line.classList.add("console-error");
|
||
|
|
line.innerText = `> ${msg}`;
|
||
|
|
console.appendChild(line);
|
||
|
|
console.scrollTop = console.scrollHeight;
|
||
|
|
}
|
||
|
|
|
||
|
|
// --- Masker Logic ---
|
||
|
|
let maskCanvas = null;
|
||
|
|
let maskCtx = null;
|
||
|
|
let isDrawing = false;
|
||
|
|
let maskStrokes = []; // Array of {size: int, points: []}
|
||
|
|
let currentStroke = null;
|
||
|
|
let lastPos = null;
|
||
|
|
|
||
|
|
function setupMaskerLogic(file, dataUrl) {
|
||
|
|
const dropZone = document.getElementById("drop-zone");
|
||
|
|
|
||
|
|
// Remove the onclick handler from dropzone to prevent file dialog
|
||
|
|
dropZone.onclick = null;
|
||
|
|
|
||
|
|
dropZone.innerHTML = "";
|
||
|
|
|
||
|
|
// Container
|
||
|
|
const container = document.createElement("div");
|
||
|
|
container.style.position = "relative";
|
||
|
|
container.style.display = "inline-flex";
|
||
|
|
container.style.justifyContent = "center";
|
||
|
|
container.style.alignItems = "center";
|
||
|
|
container.style.maxWidth = "100%";
|
||
|
|
|
||
|
|
// Close Button
|
||
|
|
const closeBtn = document.createElement("button");
|
||
|
|
closeBtn.innerHTML = '<i class="fa-solid fa-xmark"></i>';
|
||
|
|
closeBtn.style.position = "absolute";
|
||
|
|
closeBtn.style.top = "10px";
|
||
|
|
closeBtn.style.right = "10px";
|
||
|
|
closeBtn.style.zIndex = "100";
|
||
|
|
closeBtn.style.background = "rgba(239, 68, 68, 0.9)"; // Red
|
||
|
|
closeBtn.style.color = "white";
|
||
|
|
closeBtn.style.border = "none";
|
||
|
|
closeBtn.style.borderRadius = "50%";
|
||
|
|
closeBtn.style.width = "32px";
|
||
|
|
closeBtn.style.height = "32px";
|
||
|
|
closeBtn.style.cursor = "pointer";
|
||
|
|
closeBtn.style.boxShadow = "0 2px 4px rgba(0,0,0,0.2)";
|
||
|
|
closeBtn.onclick = (e) => {
|
||
|
|
e.stopPropagation();
|
||
|
|
resetToolState();
|
||
|
|
};
|
||
|
|
container.appendChild(closeBtn);
|
||
|
|
|
||
|
|
const img = new Image();
|
||
|
|
img.onload = function () {
|
||
|
|
maskCanvas = document.createElement("canvas");
|
||
|
|
maskCanvas.width = this.naturalWidth;
|
||
|
|
maskCanvas.height = this.naturalHeight;
|
||
|
|
maskCanvas.style.position = "absolute";
|
||
|
|
maskCanvas.style.top = "0";
|
||
|
|
maskCanvas.style.left = "0";
|
||
|
|
maskCanvas.style.width = "100%";
|
||
|
|
maskCanvas.style.height = "100%";
|
||
|
|
maskCanvas.style.cursor = "crosshair";
|
||
|
|
maskCanvas.style.touchAction = "none";
|
||
|
|
|
||
|
|
// Opacity Fix: Set transparency on the canvas element, not the brush
|
||
|
|
maskCanvas.style.opacity = "0.2";
|
||
|
|
|
||
|
|
maskCtx = maskCanvas.getContext("2d");
|
||
|
|
maskStrokes = [];
|
||
|
|
|
||
|
|
// Events
|
||
|
|
maskCanvas.addEventListener("mousedown", startDraw);
|
||
|
|
maskCanvas.addEventListener("mousemove", draw);
|
||
|
|
maskCanvas.addEventListener("mouseup", stopDraw);
|
||
|
|
maskCanvas.addEventListener("mouseleave", stopDraw);
|
||
|
|
|
||
|
|
// Touch support
|
||
|
|
maskCanvas.addEventListener("touchstart", (e) => {
|
||
|
|
const t = e.touches[0];
|
||
|
|
startDraw({
|
||
|
|
clientOrigin: t,
|
||
|
|
preventDefault: () => e.preventDefault(),
|
||
|
|
stopPropagation: () => e.stopPropagation(),
|
||
|
|
});
|
||
|
|
});
|
||
|
|
maskCanvas.addEventListener("touchmove", (e) => {
|
||
|
|
const t = e.touches[0];
|
||
|
|
draw({
|
||
|
|
clientOrigin: t,
|
||
|
|
preventDefault: () => e.preventDefault(),
|
||
|
|
stopPropagation: () => e.stopPropagation(),
|
||
|
|
});
|
||
|
|
});
|
||
|
|
maskCanvas.addEventListener("touchend", stopDraw);
|
||
|
|
|
||
|
|
container.appendChild(img);
|
||
|
|
container.appendChild(maskCanvas);
|
||
|
|
dropZone.appendChild(container); // Append Logic
|
||
|
|
|
||
|
|
// Style img
|
||
|
|
img.style.maxWidth = "100%";
|
||
|
|
img.style.height = "auto";
|
||
|
|
img.style.display = "block";
|
||
|
|
|
||
|
|
updateBrushCursor(
|
||
|
|
document.getElementById("param-brush-size")?.value || 30,
|
||
|
|
);
|
||
|
|
|
||
|
|
const hint = document.createElement("div");
|
||
|
|
hint.innerText =
|
||
|
|
"Click 'Process Images' to generate mask. Use Close button to reset.";
|
||
|
|
hint.style.marginTop = "10px";
|
||
|
|
hint.style.color = "#94a3b8";
|
||
|
|
hint.style.fontSize = "0.9rem";
|
||
|
|
dropZone.appendChild(hint);
|
||
|
|
};
|
||
|
|
img.src = dataUrl;
|
||
|
|
}
|
||
|
|
|
||
|
|
function resetToolState() {
|
||
|
|
currentFiles = [];
|
||
|
|
const dropZone = document.getElementById("drop-zone");
|
||
|
|
dropZone.onclick = triggerFileInput; // Restore handler
|
||
|
|
dropZone.innerHTML = `
|
||
|
|
<div id="upload-content">
|
||
|
|
<div class="upload-icon"><i class="fa-solid fa-cloud-arrow-up"></i></div>
|
||
|
|
<h3>Drag & Drop images here</h3>
|
||
|
|
<p style="color: var(--text-secondary); margin-top: 8px;">or click to browse from computer</p>
|
||
|
|
<div style="margin-top: 16px; font-size: 0.8rem; color: #64748b;">
|
||
|
|
Supported: PNG, JPG, WEBP, HEIC, BMP, TIFF, ICO
|
||
|
|
</div>
|
||
|
|
</div>
|
||
|
|
`;
|
||
|
|
dropZone.style.padding = "20px";
|
||
|
|
dropZone.style.minHeight = "250px";
|
||
|
|
document.getElementById("file-input").value = ""; // Reset input
|
||
|
|
}
|
||
|
|
|
||
|
|
// Helper
|
||
|
|
function getPos(e) {
|
||
|
|
// Check if it's a touch event wrapper or mouse event
|
||
|
|
const source = e.clientOrigin ? e.clientOrigin : e;
|
||
|
|
const rect = maskCanvas.getBoundingClientRect();
|
||
|
|
|
||
|
|
const scaleX = maskCanvas.width / rect.width;
|
||
|
|
const scaleY = maskCanvas.height / rect.height;
|
||
|
|
|
||
|
|
return {
|
||
|
|
x: (source.clientX - rect.left) * scaleX,
|
||
|
|
y: (source.clientY - rect.top) * scaleY,
|
||
|
|
};
|
||
|
|
}
|
||
|
|
|
||
|
|
function startDraw(e) {
|
||
|
|
if (e.buttons !== 1 && !e.clientOrigin) return; // Only Left click
|
||
|
|
|
||
|
|
e.stopPropagation(); // Stop opening file dialog
|
||
|
|
e.preventDefault(); // Stop text selection
|
||
|
|
|
||
|
|
isDrawing = true;
|
||
|
|
const pos = getPos(e);
|
||
|
|
lastPos = pos;
|
||
|
|
|
||
|
|
const size = document.getElementById("param-brush-size").value;
|
||
|
|
currentStroke = { size: size, points: [pos] };
|
||
|
|
maskStrokes.push(currentStroke);
|
||
|
|
|
||
|
|
// Visual Style: Solid Red (Opacity controlled by CSS on canvas)
|
||
|
|
maskCtx.lineCap = "round";
|
||
|
|
maskCtx.lineJoin = "round";
|
||
|
|
maskCtx.strokeStyle = "#ff0000";
|
||
|
|
maskCtx.lineWidth = size;
|
||
|
|
|
||
|
|
// Draw initial dot
|
||
|
|
maskCtx.beginPath();
|
||
|
|
maskCtx.moveTo(pos.x, pos.y);
|
||
|
|
maskCtx.lineTo(pos.x, pos.y);
|
||
|
|
maskCtx.stroke();
|
||
|
|
}
|
||
|
|
|
||
|
|
function draw(e) {
|
||
|
|
if (!isDrawing) return;
|
||
|
|
e.stopPropagation();
|
||
|
|
e.preventDefault();
|
||
|
|
|
||
|
|
const pos = getPos(e);
|
||
|
|
currentStroke.points.push(pos);
|
||
|
|
|
||
|
|
// Draw segment ONLY (fixes opacity stacking)
|
||
|
|
maskCtx.beginPath();
|
||
|
|
maskCtx.moveTo(lastPos.x, lastPos.y);
|
||
|
|
maskCtx.lineTo(pos.x, pos.y);
|
||
|
|
maskCtx.stroke();
|
||
|
|
|
||
|
|
lastPos = pos;
|
||
|
|
}
|
||
|
|
|
||
|
|
function stopDraw(e) {
|
||
|
|
if (isDrawing) {
|
||
|
|
isDrawing = false;
|
||
|
|
maskCtx.closePath();
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
function updateBrushCursor(size) {
|
||
|
|
// Optional: visual cursor feedback
|
||
|
|
}
|