diff --git a/cmd/image-manipulator/app.js b/cmd/image-manipulator/app.js index 466217d..a1c7988 100644 --- a/cmd/image-manipulator/app.js +++ b/cmd/image-manipulator/app.js @@ -1,1464 +1,1832 @@ -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: ` -
-
- - -
-
- - -
-
-
- -
- `, - }, - convert: { - title: "Convert Formats", - desc: "Convert images between PNG, JPG, WEBP, HEIC, and more.", - controls: ` -
-
- - -
-
- - -
-
- `, - }, - compress: { - title: "Compress Images", - desc: "Reduce file size optimized for web (Lossless-ish/High Efficiency).", - controls: ` -
- - -
-
- - - 80% -
-
-
- Original Est: - -- -
-
- New Est: - -- -
-
- Select an image to see stats -
-
- `, - }, - crop: { - title: "Crop Images", - desc: "Trim images to specific coordinates.", - controls: ` -
-
-
-
-
-
- `, - }, - filter: { - title: "Apply Filters", - desc: "Enhance images with artistic effects.", - controls: ` -
- - -
- `, - }, - rotate: { - title: "Rotate & Flip", - desc: "Change orientation of images.", - controls: ` -
- - -
- `, - }, - watermark: { - title: "Add Watermark", - desc: "Overlay logo or text image.", - controls: ` -
- - -
-
-
- - -
-
- - -
-
- `, - }, - masker: { - title: "Mask Generator", - desc: "Draw over the object to create a binary mask.", - controls: ` -
- - - 30px -
-
-

Draw with the red brush over the area you want to mask. The output will be white on black background.

-
- `, - }, - }; - - // 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 = ` -
- -
- `; - 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" - ? ` ${msg}` - : ` ${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 = - ' 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 = ` -
- Result -
-
-
${res.filename}
-
- ${res.info.width}x${res.info.height} - ${res.info.format} -
- - Download - -
- `; - 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: ` -
-
-
-
-
- `, - convert: toolConfigs.convert.controls, - compress: ` -
- - -
-
-
- - - -
-
- - -
-
- - `, - crop: toolConfigs.crop.controls, - filter: toolConfigs.filter.controls, - rotate: toolConfigs.rotate.controls, - watermark: ` -
- - -
-
-
- - -
-
- - -
-
- `, - }; - - 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 = ` -
-

- Files Ready for Processing -

- -
-
-
- ${totalCount} file(s) selected | ${totalSizeMb} MB total -
- ${totalCount > 50 ? `
Showing first 50 files
` : ""} -
-
- ${filesToPreview - .map( - (f) => ` -
- - ${f.filename} - - - ${f.size_kb || (f.size / 1024).toFixed(1)} KB - -
- `, - ) - .join("")} -
- `; - - 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 = ''; - 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 = ` -
-
-

Drag & Drop images here

-

or click to browse from computer

-
- Supported: PNG, JPG, WEBP, HEIC, BMP, TIFF, ICO -
-
- `; - 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(); +/** + * 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); + }); - const pos = getPos(e); - currentStroke.points.push(pos); + ["dragenter", "dragover"].forEach(evtName => { + target.addEventListener(evtName, () => { + const emptyDrop = document.getElementById("ps-empty-dropzone"); + if (emptyDrop) emptyDrop.classList.add("dragover"); + }, false); + }); - // Draw segment ONLY (fixes opacity stacking) - maskCtx.beginPath(); - maskCtx.moveTo(lastPos.x, lastPos.y); - maskCtx.lineTo(pos.x, pos.y); - maskCtx.stroke(); + ["dragleave", "drop"].forEach(evtName => { + target.addEventListener(evtName, () => { + const emptyDrop = document.getElementById("ps-empty-dropzone"); + if (emptyDrop) emptyDrop.classList.remove("dragover"); + }, false); + }); - lastPos = pos; - } + 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(); + } + }; - function stopDraw(e) { - if (isDrawing) { - isDrawing = false; - maskCtx.closePath(); + 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; } } - function updateBrushCursor(size) { - // Optional: visual cursor feedback - } \ No newline at end of file + 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 = ` ${count} image${count === 1 ? "" : "s"} (${totalMb} MB)`; + 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 = ` Batch All (${count})`; + } else { + btnBatchHeader.style.display = "none"; + } + } + + if (btnBatchFooter) { + if (count > 1) { + btnBatchFooter.style.display = "inline-flex"; + btnBatchFooter.innerHTML = ` 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 = ` + thumb +
+ ${item.name} + ${item.naturalW}×${item.naturalH} · ${sizeKb}KB +
+ + `; + 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: ` +
+ Aspect: + + + + + + +
+
+ + -- +
+ `, + resize: ` +
+ Scale Presets: + + + + + +
+ `, + adjust: ` +
+ Presets: + + + + +
+ `, + filter: ` +
+ Quick Filter: + + + + + + +
+ `, + rotate: ` +
+ Transform: + + + + + +
+ `, + round_corners: ` +
+ Radius: + + 35px +
+
+ +
+ `, + border: ` +
+ Canvas Aspect Pad: + + + + +
+ `, + watermark: ` +
+ Position: + + + + + +
+ `, + masker: ` +
+ Brush Size: + + 35px +
+
+ + +
+ `, + convert: ` +
+ Target Format: + + + + + + +
+ `, + compress: ` +
+ Quality: + + 80% +
+
+ Simulating... +
+ `, + strip_metadata: ` +
+ Privacy Guard Active: Strips EXIF, GPS, Camera Model, Timestamps +
+ ` + }; + + 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: ` +
Visual Crop Coordinates
+
+ + +
+
+
Drag to Frame
+

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.

+
+ `, + resize: ` +
Dimensions & Resampling
+
+
+ + +
+
+ + +
+
+
+ +
+ `, + adjust: ` +
Color Grading Sliders
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ `, + filter: ` +
Select Artistic Filter
+
+ + +
+ `, + rotate: ` +
Orientation & Angle
+
+ + +
+
+ + +
+ `, + round_corners: ` +
Corner Geometry
+
+ + +
+
+ +
+ `, + border: ` +
Border & Canvas Framing
+
+ + +
+
+ +
+ + +
+
+
+
+
+
+
+
+
+
+
+ + +
+ `, + watermark: ` +
Watermark Stamp
+
+ + +
+
+ + +
+
+ + +
+ `, + masker: ` +
Mask Generator & Brush
+
+ + +
+
+

Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.

+
+ `, + convert: ` +
Transcode Format
+
+ + +
+
+ + +
+ `, + compress: ` +
Compression Engine
+
+ + +
+
+ + +
+
+ + +
+
+
+ Original Size: + -- +
+
+ Estimated Output: + -- +
+
+ Reduction: -- +
+
+ `, + strip_metadata: ` +
EXIF Privacy Cleaner
+
+ + +
+
+
Cleans All Hidden Metadata:
+
• GPS Geolocation Coordinates
+
• Camera Model, Serial Number & Lens
+
• Creation Date, Exposure & Shutter Speeds
+
• Embedded Thumbnails & Author Tags
+
+ ` + }; + + 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 = ` ${msg}`; + container.appendChild(toast); + setTimeout(() => toast.remove(), 4000); +} +window.showToast = showToast; diff --git a/cmd/image-manipulator/handlers1.go b/cmd/image-manipulator/handlers1.go index 250d1b5..6231701 100644 --- a/cmd/image-manipulator/handlers1.go +++ b/cmd/image-manipulator/handlers1.go @@ -2,6 +2,7 @@ package main import ( "archive/zip" + "bytes" "encoding/base64" "encoding/json" "fmt" @@ -48,6 +49,18 @@ type BatchResult struct { Results []SingleResult `json:"results"` } +func parseFormFloat(r *http.Request, key string, def float64) float64 { + val := r.FormValue(key) + if val == "" { + return def + } + f, err := strconv.ParseFloat(val, 64) + if err != nil { + return def + } + return f +} + func parseFormInt(r *http.Request, key string, def int) int { val := r.FormValue(key) if val == "" { @@ -268,9 +281,23 @@ func cropHandler(w http.ResponseWriter, r *http.Request) { top := parseFormInt(r, "top", 0) right := parseFormInt(r, "right", 800) bottom := parseFormInt(r, "bottom", 600) + leftPct := parseFormFloat(r, "left_pct", -1) + topPct := parseFormFloat(r, "top_pct", -1) + rightPct := parseFormFloat(r, "right_pct", -1) + bottomPct := parseFormFloat(r, "bottom_pct", -1) handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { - return cropImage(img, left, top, right, bottom), format, 0 + bounds := img.Bounds() + l, t, rVal, b := left, top, right, bottom + if leftPct >= 0 && rightPct > leftPct && topPct >= 0 && bottomPct > topPct { + wDx := float64(bounds.Dx()) + hDy := float64(bounds.Dy()) + l = int(wDx * leftPct / 100.0) + rVal = int(wDx * rightPct / 100.0) + t = int(hDy * topPct / 100.0) + b = int(hDy * bottomPct / 100.0) + } + return cropImage(img, l, t, rVal, b), format, 0 }) } @@ -430,3 +457,55 @@ func downloadAllHandler(w http.ResponseWriter, r *http.Request) { writer.Write(imageBytes) } } + +func adjustHandler(w http.ResponseWriter, r *http.Request) { + brightness := parseFormFloat(r, "brightness", 0) + contrast := parseFormFloat(r, "contrast", 0) + saturation := parseFormFloat(r, "saturation", 0) + gamma := parseFormFloat(r, "gamma", 1.0) + + handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { + return adjustColor(img, brightness, contrast, saturation, gamma), format, 0 + }) +} + +func borderHandler(w http.ResponseWriter, r *http.Request) { + borderWidth := parseFormInt(r, "border_width", 20) + borderColor := r.FormValue("border_color") + if borderColor == "" { + borderColor = "#ffffff" + } + padAspect := r.FormValue("pad_aspect") + + handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { + return addBorderCanvas(img, borderWidth, borderColor, padAspect), format, 0 + }) +} + +func roundCornersHandler(w http.ResponseWriter, r *http.Request) { + radius := parseFormInt(r, "radius", 30) + isCircle := r.FormValue("is_circle") == "true" + + handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { + return roundCorners(img, radius, isCircle), "PNG", 0 + }) +} + +func stripMetadataHandler(w http.ResponseWriter, r *http.Request) { + quality := parseFormInt(r, "quality", 95) + targetFormat := strings.ToLower(r.FormValue("format")) + + handleProcessing(w, r, func(img image.Image, format string, idx int, filename string) (image.Image, string, float64) { + fmtTarget := targetFormat + if fmtTarget == "" || fmtTarget == "original" { + fmtTarget = format + } + buf, finalFmt := compressLogic(img, fmtTarget, quality) + sizeKB := float64(len(buf)) / 1024.0 + cleanImg, _, _ := image.Decode(bytes.NewReader(buf)) + if cleanImg == nil { + cleanImg = img + } + return cleanImg, finalFmt, sizeKB + }) +} diff --git a/cmd/image-manipulator/handlers2.go b/cmd/image-manipulator/handlers2.go index 6c98242..1570cab 100644 --- a/cmd/image-manipulator/handlers2.go +++ b/cmd/image-manipulator/handlers2.go @@ -1,6 +1,8 @@ package main import ( + "bytes" + "encoding/base64" "encoding/json" "fmt" "image" @@ -459,11 +461,25 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { buf, finalFmt = compressLogic(img, targetFmt, q) } case "crop": - l, t, r, b := 0, 0, 800, 600 - if val, ok := data.Params["left"].(float64); ok { l = int(val) } - if val, ok := data.Params["top"].(float64); ok { t = int(val) } - if val, ok := data.Params["right"].(float64); ok { r = int(val) } - if val, ok := data.Params["bottom"].(float64); ok { b = int(val) } + bounds := img.Bounds() + wDx, hDy := float64(bounds.Dx()), float64(bounds.Dy()) + l, t, r, b := 0, 0, bounds.Dx(), bounds.Dy() + if lp, ok := data.Params["left_pct"].(float64); ok { + rp, _ := data.Params["right_pct"].(float64) + tp, _ := data.Params["top_pct"].(float64) + bp, _ := data.Params["bottom_pct"].(float64) + if rp > lp && bp > tp { + l = int(wDx * lp / 100.0) + r = int(wDx * rp / 100.0) + t = int(hDy * tp / 100.0) + b = int(hDy * bp / 100.0) + } + } else { + if val, ok := data.Params["left"].(float64); ok { l = int(val) } + if val, ok := data.Params["top"].(float64); ok { t = int(val) } + if val, ok := data.Params["right"].(float64); ok { r = int(val) } + if val, ok := data.Params["bottom"].(float64); ok { b = int(val) } + } processed := cropImage(img, l, t, r, b) buf, finalFmt = compressLogic(processed, format, 95) case "filter": @@ -479,25 +495,69 @@ func batchProcessSessionHandler(w http.ResponseWriter, r *http.Request) { buf, finalFmt = compressLogic(processed, format, 95) case "watermark": wmPath, _ := data.Params["watermark_path"].(string) + wmBase64, _ := data.Params["watermark_base64"].(string) pos := "bottom_right" if p, ok := data.Params["position"].(string); ok && p != "" { pos = p } op := 50 if o, ok := data.Params["opacity"].(float64); ok { op = int(o) } - if wmPath != "" { + + var wmImg image.Image + if wmBase64 != "" { + if commaIdx := strings.Index(wmBase64, ","); commaIdx != -1 { + wmBase64 = wmBase64[commaIdx+1:] + } + if decoded, err := base64.StdEncoding.DecodeString(wmBase64); err == nil { + wmImg, _, _ = image.Decode(bytes.NewReader(decoded)) + } + } else if wmPath != "" { if wmFile, err := os.Open(wmPath); err == nil { - if wmImg, _, err := image.Decode(wmFile); err == nil { - img = watermarkImage(img, wmImg, pos, op) - } + wmImg, _, _ = image.Decode(wmFile) wmFile.Close() } } + if wmImg != nil { + img = watermarkImage(img, wmImg, pos, op) + } buf, finalFmt = compressLogic(img, format, 95) + case "adjust": + brightness, contrast, saturation := 0.0, 0.0, 0.0 + gamma := 1.0 + if b, ok := data.Params["brightness"].(float64); ok { brightness = b } + if c, ok := data.Params["contrast"].(float64); ok { contrast = c } + if s, ok := data.Params["saturation"].(float64); ok { saturation = s } + if g, ok := data.Params["gamma"].(float64); ok && g > 0 { gamma = g } + processed := adjustColor(img, brightness, contrast, saturation, gamma) + buf, finalFmt = compressLogic(processed, format, 95) + case "border": + borderWidth := 20 + if bw, ok := data.Params["border_width"].(float64); ok { borderWidth = int(bw) } + borderColor := "#ffffff" + if bc, ok := data.Params["border_color"].(string); ok && bc != "" { borderColor = bc } + padAspect := "" + if pa, ok := data.Params["pad_aspect"].(string); ok { padAspect = pa } + processed := addBorderCanvas(img, borderWidth, borderColor, padAspect) + buf, finalFmt = compressLogic(processed, format, 95) + case "round_corners": + radius := 30 + if r, ok := data.Params["radius"].(float64); ok { radius = int(r) } + isCircle := false + if c, ok := data.Params["is_circle"].(bool); ok { isCircle = c } + processed := roundCorners(img, radius, isCircle) + buf, finalFmt = compressLogic(processed, "PNG", 95) + case "strip_metadata": + targetFmt := format + if f, ok := data.Params["format"].(string); ok && f != "" && f != "original" { + targetFmt = f + } + q := 95 + if qval, ok := data.Params["quality"].(float64); ok { q = int(qval) } + buf, finalFmt = compressLogic(img, targetFmt, q) default: buf, finalFmt = compressLogic(img, format, 95) } relPath, _ := filepath.Rel(uploadsDir, file) - if data.Operation == "convert" || (data.Operation == "compress" && data.Params["format"] != nil && data.Params["format"] != "original" && data.Params["format"] != "") { + if data.Operation == "convert" || data.Operation == "round_corners" || (data.Operation == "compress" && data.Params["format"] != nil && data.Params["format"] != "original" && data.Params["format"] != "") { ext := strings.ToLower(finalFmt) if ext == "jpeg" { ext = "jpg" diff --git a/cmd/image-manipulator/index.html b/cmd/image-manipulator/index.html index 5bf3d79..d9c9c30 100644 --- a/cmd/image-manipulator/index.html +++ b/cmd/image-manipulator/index.html @@ -1,263 +1,339 @@ - + - - - - ImagePro Toolkit | Professional Image Manipulation - - + + + + + + Photoshop Lite · Obsidian Liquid Studio + + + + + + - - - - - - -
-
-
+ + + + + +
- - - -
- -
-
-

Resize Images

-

- Change image dimensions while maintaining quality. -

-
-
+ +
- -
-
-
-
- + + - - -
-
-
- - - -
- - +
+ Preparing files... + 0.0 MB/s
-
- -
- Or drag & drop files/folders here -
-
+ +
+
> Initializing Obsidian batch engine...
-

- Files will be uploaded and processed. Results will download as a - ZIP file. -

-
-
-
- - +
+
-
- - -
- -
- - -
- -
-
> Ready to process...
-
- - -
- -
-
-

Processing...

-
- - +
- - - \ No newline at end of file + + + diff --git a/cmd/image-manipulator/main.go b/cmd/image-manipulator/main.go index 5bcf7df..97ad207 100644 --- a/cmd/image-manipulator/main.go +++ b/cmd/image-manipulator/main.go @@ -96,6 +96,7 @@ func main() { r.Get("/", indexHandler) r.Get("/styles.css", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/css; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") for _, p := range []string{ "cmd/image-manipulator/styles.css", "web/image-manipulator/styles.css", @@ -109,6 +110,7 @@ func main() { }) r.Get("/app.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") for _, p := range []string{ "cmd/image-manipulator/app.js", "web/image-manipulator/app.js", @@ -133,6 +135,10 @@ func main() { r.Post("/rotate", rotateHandler) r.Post("/watermark", watermarkHandler) r.Post("/mask", maskHandler) + r.Post("/adjust", adjustHandler) + r.Post("/border", borderHandler) + r.Post("/round-corners", roundCornersHandler) + r.Post("/strip-metadata", stripMetadataHandler) r.Post("/download-all", downloadAllHandler) r.Post("/create-session", createSessionHandler) @@ -172,6 +178,7 @@ func main() { func indexHandler(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") for _, p := range []string{ "web/image-manipulator/index.html", "cmd/image-manipulator/index.html", diff --git a/cmd/image-manipulator/processor.go b/cmd/image-manipulator/processor.go index 3c0d306..c0b9cb7 100644 --- a/cmd/image-manipulator/processor.go +++ b/cmd/image-manipulator/processor.go @@ -9,6 +9,7 @@ import ( "image/gif" "image/jpeg" "image/png" + "math" "os" "os/exec" "strconv" @@ -45,9 +46,9 @@ func resizeImage(img image.Image, width, height int, maintainAspect bool) image. } func filterImage(img image.Image, filterType string) image.Image { - switch filterType { + switch strings.ToUpper(filterType) { case "BLUR": - return imaging.Blur(img, 2.0) + return imaging.Blur(img, 2.5) case "SHARPEN": return imaging.Sharpen(img, 2.0) case "GRAYSCALE": @@ -57,24 +58,203 @@ func filterImage(img image.Image, filterType string) image.Image { case "SEPIA": gray := imaging.Grayscale(img) return imaging.AdjustSaturation(imaging.AdjustSigmoid(gray, 0.5, 3.0), 50) + case "EMBOSS": + kernel := [9]float64{ + -2, -1, 0, + -1, 1, 1, + 0, 1, 2, + } + return imaging.Convolve3x3(img, kernel, nil) + case "CONTOUR", "EDGE_ENHANCE": + kernel := [9]float64{ + -1, -1, -1, + -1, 8, -1, + -1, -1, -1, + } + return imaging.Convolve3x3(img, kernel, nil) + case "WARM": + return imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA { + r := int(c.R) + 25 + b := int(c.B) - 15 + if r > 255 { r = 255 } + if b < 0 { b = 0 } + return color.NRGBA{R: uint8(r), G: c.G, B: uint8(b), A: c.A} + }) + case "COOL": + return imaging.AdjustFunc(img, func(c color.NRGBA) color.NRGBA { + r := int(c.R) - 15 + b := int(c.B) + 30 + if r < 0 { r = 0 } + if b > 255 { b = 255 } + return color.NRGBA{R: uint8(r), G: c.G, B: uint8(b), A: c.A} + }) + case "VINTAGE": + sepia := imaging.AdjustSaturation(imaging.AdjustSigmoid(imaging.Grayscale(img), 0.5, 2.5), 35) + return imaging.AdjustContrast(sepia, 15) default: return img } } +func parseHexColor(hexStr string) color.NRGBA { + hexStr = strings.TrimPrefix(strings.TrimSpace(hexStr), "#") + if len(hexStr) == 3 { + hexStr = string([]byte{hexStr[0], hexStr[0], hexStr[1], hexStr[1], hexStr[2], hexStr[2]}) + } + if len(hexStr) == 6 { + val, err := strconv.ParseUint(hexStr, 16, 32) + if err == nil { + return color.NRGBA{ + R: uint8(val >> 16), + G: uint8((val >> 8) & 0xFF), + B: uint8(val & 0xFF), + A: 255, + } + } + } else if len(hexStr) == 8 { + val, err := strconv.ParseUint(hexStr, 16, 32) + if err == nil { + return color.NRGBA{ + R: uint8(val >> 24), + G: uint8((val >> 16) & 0xFF), + B: uint8((val >> 8) & 0xFF), + A: uint8(val & 0xFF), + } + } + } + return color.NRGBA{0, 0, 0, 255} +} + +func adjustColor(img image.Image, brightness, contrast, saturation, gamma float64) image.Image { + res := img + if brightness != 0 { + res = imaging.AdjustBrightness(res, brightness) + } + if contrast != 0 { + res = imaging.AdjustContrast(res, contrast) + } + if saturation != 0 { + res = imaging.AdjustSaturation(res, saturation) + } + if gamma > 0 && gamma != 1.0 { + res = imaging.AdjustGamma(res, gamma) + } + return res +} + +func roundCorners(img image.Image, radius int, isCircle bool) image.Image { + bounds := img.Bounds() + w, h := bounds.Dx(), bounds.Dy() + if isCircle { + radius = w / 2 + if h/2 < radius { + radius = h / 2 + } + } + if radius <= 0 { + return img + } + + dst := image.NewNRGBA(image.Rect(0, 0, w, h)) + rSq := float64(radius * radius) + innerRSq := float64((radius - 1) * (radius - 1)) + + for y := 0; y < h; y++ { + for x := 0; x < w; x++ { + c := color.NRGBAModel.Convert(img.At(bounds.Min.X+x, bounds.Min.Y+y)).(color.NRGBA) + + var dx, dy float64 + inCorner := false + + if x < radius && y < radius { + dx, dy = float64(radius-x), float64(radius-y) + inCorner = true + } else if x >= w-radius && y < radius { + dx, dy = float64(x-(w-radius-1)), float64(radius-y) + inCorner = true + } else if x < radius && y >= h-radius { + dx, dy = float64(radius-x), float64(y-(h-radius-1)) + inCorner = true + } else if x >= w-radius && y >= h-radius { + dx, dy = float64(x-(w-radius-1)), float64(y-(h-radius-1)) + inCorner = true + } + + if inCorner { + distSq := dx*dx + dy*dy + if distSq > rSq { + c.A = 0 + } else if distSq > innerRSq { + dist := math.Sqrt(distSq) + factor := float64(radius) - dist + if factor < 0 { + factor = 0 + } else if factor > 1 { + factor = 1 + } + c.A = uint8(float64(c.A) * factor) + } + } + dst.SetNRGBA(x, y, c) + } + } + return dst +} + +func addBorderCanvas(img image.Image, borderWidth int, borderColorHex string, padAspect string) image.Image { + bounds := img.Bounds() + w, h := bounds.Dx(), bounds.Dy() + borderColor := parseHexColor(borderColorHex) + + newW := w + borderWidth*2 + newH := h + borderWidth*2 + + if padAspect != "" && padAspect != "none" { + var targetRatio float64 + switch padAspect { + case "1:1": + targetRatio = 1.0 + case "16:9": + targetRatio = 16.0 / 9.0 + case "9:16": + targetRatio = 9.0 / 16.0 + case "4:5": + targetRatio = 4.0 / 5.0 + case "4:3": + targetRatio = 4.0 / 3.0 + } + if targetRatio > 0 { + curRatio := float64(newW) / float64(newH) + if curRatio < targetRatio { + newW = int(float64(newH) * targetRatio) + } else if curRatio > targetRatio { + newH = int(float64(newW) / targetRatio) + } + } + } + + canvas := imaging.New(newW, newH, borderColor) + posX := (newW - w) / 2 + posY := (newH - h) / 2 + return imaging.Paste(canvas, img, image.Pt(posX, posY)) +} + func rotateImage(img image.Image, op string) image.Image { switch op { case "90": - return imaging.Rotate270(img) // Python's -90 is Rotate270 + return imaging.Rotate270(img) // Clockwise 90 case "180": return imaging.Rotate180(img) case "270": - return imaging.Rotate90(img) // Python's 90 is Rotate90 + return imaging.Rotate90(img) // Clockwise 270 case "FLIP_H": return imaging.FlipH(img) case "FLIP_V": return imaging.FlipV(img) default: + if angle, err := strconv.ParseFloat(op, 64); err == nil { + return imaging.Rotate(img, -angle, color.Transparent) + } return img } } diff --git a/cmd/image-manipulator/styles.css b/cmd/image-manipulator/styles.css index 556769b..d6d761f 100644 --- a/cmd/image-manipulator/styles.css +++ b/cmd/image-manipulator/styles.css @@ -1,491 +1,1311 @@ +/* ═══════════════════════════════════════════════════════════════════ + IMAGEPRO · PHOTOSHOP LITE · BLACK OBSIDIAN LIQUID GLASS + GPU-accelerated 120 FPS hardware compositing, fluid reflections, + and precision Photoshop-inspired ergonomics. +═══════════════════════════════════════════════════════════════════ */ + :root { - --primary: #FF6C37; - --primary-dark: #e55f2c; - --secondary: #FF8559; - --bg-dark: #1a1a1a; - --bg-card: #252525; - --bg-input: #2b2b2b; - --text-main: #EAEAEA; - --text-secondary: #A6A6A6; - --border: #333333; - --border-focus: #FF6C37; - --sidebar-width: 260px; - } + --bg-void: #000000; + --bg-smoke: rgba(10, 10, 14, 0.78); + --bg-smoke-heavy: rgba(6, 6, 9, 0.92); + --bg-card: rgba(14, 14, 20, 0.68); + --bg-card-hover: rgba(22, 22, 32, 0.84); + --bg-input: rgba(18, 18, 26, 0.75); + --bg-input-focus: rgba(26, 26, 38, 0.95); - * { margin: 0; padding: 0; box-sizing: border-box; } + /* Primary Brand: Obsidian Flame & Cyan Caustics */ + --primary: #ff6c37; + --primary-hover: #ff8252; + --primary-dark: #e5531d; + --primary-alpha: rgba(255, 108, 55, 0.18); + --primary-alpha2: rgba(255, 108, 55, 0.35); + --primary-glow: rgba(255, 108, 55, 0.45); - body { - font-family: 'Inter', sans-serif; - background-color: var(--bg-dark); - color: var(--text-main); - height: 100vh; - display: flex; - overflow: hidden; - position: relative; - } + --accent-cyan: #00f2fe; + --accent-cyan-hover: #38f9d7; + --accent-cyan-alpha: rgba(0, 242, 254, 0.16); + --accent-cyan-glow: rgba(0, 242, 254, 0.40); - /* Sidebar */ - .sidebar { - width: var(--sidebar-width); - background: rgba(255, 255, 255, 0.05); - - border-right: 1px solid var(--border); - display: flex; - flex-direction: column; - padding: 24px; - transition: transform 0.3s ease; - position: relative; - z-index: 10; - box-shadow: 0 0 30px rgba(0, 0, 0, 0.3); - } + --accent-emerald: #10b981; + --accent-emerald-alpha: rgba(16, 185, 129, 0.18); + --accent-purple: #a855f7; + --accent-purple-alpha: rgba(168, 85, 247, 0.18); - .logo { - display: flex; - align-items: center; - gap: 12px; - font-size: 1.25rem; - font-weight: 700; - color: var(--primary); - margin-bottom: 40px; - padding-bottom: 24px; - border-bottom: 1px solid var(--border); - } + --text-1: #ffffff; + --text-2: #cbd5e1; + --text-3: #94a3b8; + --text-muted: #64748b; - .logo i { - font-size: 1.5rem; - color: var(--primary); - filter: drop-shadow(0 0 10px var(--primary)); - } + --border-1: rgba(255, 255, 255, 0.08); + --border-2: rgba(255, 255, 255, 0.15); + --border-3: rgba(255, 255, 255, 0.28); + --border-focus: rgba(255, 108, 55, 0.65); + --border-cyan: rgba(0, 242, 254, 0.50); - .nav-links { - display: flex; - flex-direction: column; - gap: 8px; - flex: 1; - } + --r-sm: 6px; + --r-md: 10px; + --r-lg: 16px; + --r-xl: 22px; + --r-full: 9999px; - .nav-item { - display: flex; - align-items: center; - gap: 12px; - padding: 12px 16px; - color: var(--text-secondary); - text-decoration: none; - border-radius: 12px; - transition: all 0.3s; - cursor: pointer; - font-weight: 500; - background: transparent; - } + /* Liquid Glass Shadow Tokens */ + --sh-liquid: + 0 1px 0 rgba(255, 255, 255, 0.38) inset, + 0 -1px 0 rgba(0, 0, 0, 0.70) inset, + 0 18px 48px rgba(0, 0, 0, 0.75); + --sh-liquid-hover: + 0 1.5px 0 rgba(255, 255, 255, 0.55) inset, + 0 -1px 0 rgba(0, 0, 0, 0.80) inset, + 0 24px 60px rgba(0, 0, 0, 0.85), + 0 0 30px var(--primary-glow); + --sh-glass: + 0 1px 0 rgba(255, 255, 255, 0.20) inset, + 0 -1px 0 rgba(0, 0, 0, 0.60) inset, + 0 8px 24px rgba(0, 0, 0, 0.55); - .nav-item:hover { - background: rgba(0, 245, 255, 0.1); - color: #fff; - transform: translateX(5px); - } - - .nav-item.active { - background: var(--primary); - color: #fff; - box-shadow: 0 4px 20px rgba(255, 108, 55, 0.4); - } - - .nav-item i { width: 24px; text-align: center; } - - .divider { - height: 1px; - background: linear-gradient(90deg, transparent, var(--border), transparent); - margin: 16px 0; - } - - .section-title { - font-size: 0.75rem; - text-transform: uppercase; - letter-spacing: 0.05em; - color: var(--primary); - margin-bottom: 12px; - padding-left: 12px; - font-weight: 600; - } - - /* Main Content */ - .main-content { - flex: 1; - overflow-y: auto; - padding: 40px; - position: relative; - z-index: 5; - } - - .header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 32px; - background: var(--bg-card); - - border: 1px solid var(--border); - border-radius: 20px; - padding: 25px 30px; - box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2); - } - - .page-title h2 { - font-size: 1.875rem; - font-weight: 700; - margin-bottom: 8px; - color: #fff; - - - - } - .page-title p { color: var(--text-secondary); } - - /* Tools Container */ - .tool-view { display: none; animation: fadeIn 0.4s ease; } - .tool-view.active { display: block; } - - @keyframes fadeIn { - from { opacity: 0; transform: translateY(10px); } - to { opacity: 1; transform: translateY(0); } - } - - /* Upload Area */ - .upload-area { - border: 2px dashed var(--border); - border-radius: 20px; - padding: 20px; - min-height: 250px; - text-align: center; - background: rgba(255, 108, 55, 0.05); - - transition: all 0.3s; - cursor: pointer; - position: relative; - overflow: hidden; - margin-bottom: 32px; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - } - - .upload-area:hover, .upload-area.dragover { - border-color: var(--primary); - background: rgba(255, 108, 55, 0.1); - transform: translateY(-5px); - box-shadow: 0 20px 60px rgba(255, 108, 55, 0.4); - } - - .upload-icon { - font-size: 48px; - color: var(--primary); - margin-bottom: 16px; - filter: drop-shadow(0 0 20px var(--primary)); - } - - /* Controls Panel */ - .controls-panel { - background: var(--bg-card); - - border: 1px solid var(--border); - border-radius: 20px; - padding: 24px; - margin-bottom: 32px; - box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2); - } - - .input-group { margin-bottom: 20px; } - .input-group label { display: block; margin-bottom: 8px; font-weight: 500; color: var(--text-secondary); } - - input[type="text"], input[type="number"], select { - width: 100%; - padding: 12px 16px; - background: rgba(0, 0, 0, 0.3); - border: 2px solid var(--border); - border-radius: 12px; - color: #fff; - font-size: 1rem; - transition: all 0.2s; - } - - input[type="text"]:focus, input[type="number"]:focus, select:focus { - outline: none; - border-color: var(--primary); - box-shadow: 0 0 20px rgba(255, 108, 55, 0.4); - } - - .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } - .grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; } - - /* Range Slider */ - input[type="range"] { - width: 100%; - height: 6px; - background: var(--border); - border-radius: 3px; - appearance: none; - } - - input[type="range"]::-webkit-slider-thumb { - appearance: none; - width: 20px; - height: 20px; - background: var(--primary); - border-radius: 50%; - cursor: pointer; - transition: transform 0.2s; - box-shadow: 0 0 15px rgba(0, 245, 255, 0.6); - } - - input[type="range"]::-webkit-slider-thumb:hover { - transform: scale(1.2); - } - - /* Buttons */ - .btn { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - padding: 12px 24px; - background: var(--primary); - color: white; - border: none; - border-radius: 12px; - font-weight: 700; - font-size: 1rem; - cursor: pointer; - transition: all 0.4s cubic-bezier(0.23, 1, 0.320, 1); - width: 100%; - box-shadow: 0 10px 30px rgba(255, 108, 55, 0.4); - - .btn::after { - content: ''; - position: absolute; - top: 50%; - left: 50%; - width: 0; - height: 0; - border-radius: 50%; - background: rgba(255, 255, 255, 0.5); - transform: translate(-50%, -50%); - transition: width 0.6s, height 0.6s; - } - - .btn:active::after { - width: 300px; - height: 300px; - } - - .btn-secondary { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.05)); - box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); - } - .btn-secondary:hover { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1)); - } - - /* Results */ - .results-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); - gap: 24px; - } - - .result-card { - background-color: var(--bg-card); - border: 1px solid var(--border); - border-radius: 12px; - overflow: hidden; - transition: transform 0.3s; - } - - .result-card:hover { transform: translateY(-4px); border-color: var(--primary); } - - .image-preview { - height: 200px; - background-color: #000; - display: flex; - align-items: center; - justify-content: center; - overflow: hidden; - } - - .image-preview img { - max-width: 100%; - max-height: 100%; - object-fit: contain; - } - - .card-body { padding: 16px; } - .file-name { font-weight: 600; margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } - .file-meta { font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 16px; display: flex; justify-content: space-between; } - - .download-link { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - padding: 8px; - background-color: rgba(99, 102, 241, 0.1); - color: var(--primary); - text-decoration: none; - border-radius: 6px; - font-size: 0.875rem; - font-weight: 500; - transition: background 0.2s; - } - - .download-link:hover { background-color: rgba(99, 102, 241, 0.2); } - - /* Batch Console */ - .console { - background-color: #000; - border-radius: 8px; - padding: 16px; - font-family: 'Courier New', monospace; - font-size: 0.9rem; - color: #10b981; - height: 300px; - overflow-y: auto; - margin-top: 24px; - border: 1px solid var(--border); - } - - .console-line { margin-bottom: 4px; } - .console-error { color: #ef4444; } - - /* Toast Messages */ - .toast-container { - position: fixed; - bottom: 24px; - right: 24px; - z-index: 1000; - } - - .toast { - background-color: var(--bg-card); - border-left: 4px solid var(--primary); - padding: 16px 24px; - border-radius: 8px; - box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); - margin-top: 12px; - display: flex; - align-items: center; - gap: 12px; - animation: slideIn 0.3s ease; - } - - .toast.error { border-left-color: #ef4444; } - .toast.success { border-left-color: #10b981; } - - @keyframes slideIn { - from { transform: translateX(100%); opacity: 0; } - to { transform: translateX(0); opacity: 1; } - } - - /* Loading */ - .loader { - display: none; - position: fixed; - top: 0; left: 0; width: 100%; height: 100%; - background: rgba(15, 23, 42, 0.8); - z-index: 999; - justify-content: center; - align-items: center; - flex-direction: column; - animation: glow 3s ease-in-out infinite; - } - - .loader.active { display: flex; } - - @keyframes glow { - 0%, 100% { filter: drop-shadow(0 0 20px #8b5cf6); } - 50% { filter: drop-shadow(0 0 35px #a78bfa); } - } - - /* Custom Animated Loader Spinner */ - .spinner { - width: 50px; - height: 50px; - border: 5px solid rgba(139, 92, 246, 0.3); - border-top-color: #8b5cf6; - border-radius: 50%; - animation: loaderSpin 1s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite; - } - - @keyframes loaderSpin { - 0% { transform: rotate(0deg) scale(1); } - 50% { transform: rotate(180deg) scale(1.2); } - 100% { transform: rotate(360deg) scale(1); } - } - - /* Text Shadow Pulse on Hover */ - h1, h2, h3 { - transition: all 0.3s ease; - } - - h1:hover, h2:hover, h3:hover { - text-shadow: 0 0 20px rgba(139, 92, 246, 0.8), - 0 0 40px rgba(139, 92, 246, 0.5), - 0 0 60px rgba(139, 92, 246, 0.3); - transform: translateY(-2px); - } - - /* Icon Float Animation */ - .icon-float { - animation: floatIcon 3s ease-in-out infinite; - } - - @keyframes floatIcon { - 0%, 100% { transform: translateY(0px); } - 50% { transform: translateY(-15px); } - } - - /* Input Focus Glow Effect */ - input[type="range"]:focus { - outline: none; - box-shadow: 0 0 0 3px rgba(255, 108, 55, 0.4); - } - - /* Tooltip Fade In */ - [title]:hover::after { - content: attr(title); - position: absolute; - bottom: 125%; - left: 50%; - transform: translateX(-50%); - padding: 8px 12px; - background: rgba(139, 92, 246, 0.95); - color: white; - border-radius: 6px; - font-size: 12px; - white-space: nowrap; - opacity: 0; - animation: tooltipFade 0.3s ease forwards; - pointer-events: none; - } - - @keyframes tooltipFade { - to { opacity: 1; transform: translateX(-50%) translateY(-5px); } - } - /* Scrollbar */ - ::-webkit-scrollbar { width: 12px; height: 12px; } - ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.3); border-radius: 10px; } - ::-webkit-scrollbar-thumb { background: linear-gradient(135deg, #8b5cf6, #a78bfa); border-radius: 10px; } - -/* ─── Low-end device & responsiveness performance optimizations ─── */ -@media (prefers-reduced-motion: reduce) { - *, *::before, *::after { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } + --font-main: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; } -.sidebar { - contain: layout style; + +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; } -.main-content { - contain: content; + +html, body { + width: 100%; + height: 100%; + overflow: hidden; + background-color: var(--bg-void); + color: var(--text-1); + font-family: var(--font-main); + font-size: 13px; + line-height: 1.45; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + user-select: none; +} + +/* Ambient Obsidian Caustics */ +.ambient-canvas { + position: fixed; + inset: 0; + pointer-events: none; + z-index: 0; + overflow: hidden; + background: + radial-gradient(circle at 10% 15%, rgba(255, 108, 55, 0.09) 0%, transparent 45%), + radial-gradient(circle at 90% 85%, rgba(0, 242, 254, 0.07) 0%, transparent 50%), + radial-gradient(circle at 50% 50%, rgba(168, 85, 247, 0.04) 0%, transparent 60%), + #000000; +} + +/* ═══════════════════════════════════════════════════════════════════ + APP ROOT LAYOUT +═══════════════════════════════════════════════════════════════════ */ +.ps-app-root { + display: flex; + flex-direction: column; + width: 100vw; + height: 100vh; + position: relative; + z-index: 1; + overflow: hidden; +} + +/* ═══════════════════════════════════════════════════════════════════ + TOP APPLICATION BAR & CONTEXTUAL OPTIONS STRIP +═══════════════════════════════════════════════════════════════════ */ +.ps-app-header { + height: 52px; + min-height: 52px; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(24px) saturate(190%); + -webkit-backdrop-filter: blur(24px) saturate(190%); + border-bottom: 1px solid var(--border-2); + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 16px; + gap: 16px; + position: relative; + z-index: 50; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6); +} + +.ps-header-left { + display: flex; + align-items: center; + gap: 12px; + flex-shrink: 0; +} + +.ps-brand-badge { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; +} + +.ps-logo-icon { + width: 32px; + height: 32px; + border-radius: var(--r-md); + background: linear-gradient(135deg, rgba(255, 108, 55, 0.35) 0%, rgba(0, 242, 254, 0.25) 100%); + border: 1px solid var(--border-cyan); + box-shadow: 0 0 16px var(--accent-cyan-alpha), 0 0 12px var(--primary-alpha); + display: flex; + align-items: center; + justify-content: center; + font-family: var(--font-mono); + font-weight: 800; + font-size: 15px; + color: #ffffff; + letter-spacing: -0.5px; +} + +.ps-brand-text { + display: flex; + flex-direction: column; +} + +.ps-brand-text h1 { + font-size: 13.5px; + font-weight: 700; + color: var(--text-1); + letter-spacing: -0.01em; + display: flex; + align-items: center; + gap: 6px; +} + +.ps-brand-text span { + font-size: 9.5px; + font-weight: 600; + color: var(--accent-cyan); + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.ps-menu-divider { + width: 1px; + height: 22px; + background: var(--border-2); +} + +.ps-file-btns { + display: flex; + align-items: center; + gap: 6px; +} + +/* Contextual Tool Options Strip (Center Header) */ +.ps-tool-options-strip { + flex: 1; + display: flex; + align-items: center; + gap: 12px; + overflow-x: auto; + padding: 4px 0; + scrollbar-width: none; +} + +.ps-tool-options-strip::-webkit-scrollbar { + display: none; +} + +.ps-options-group { + display: flex; + align-items: center; + gap: 8px; + padding: 3px 10px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + white-space: nowrap; +} + +.ps-options-label { + font-size: 11px; + font-weight: 600; + color: var(--text-3); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.ps-header-right { + display: flex; + align-items: center; + gap: 10px; + flex-shrink: 0; +} + +.ps-counter-pill { + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; + color: var(--text-2); + padding: 5px 10px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid var(--border-1); + border-radius: var(--r-full); + display: flex; + align-items: center; + gap: 6px; +} + +.ps-counter-pill.has-files { + border-color: var(--primary-alpha2); + color: var(--primary); + background: var(--primary-alpha); + box-shadow: 0 0 12px var(--primary-alpha); +} + +/* ═══════════════════════════════════════════════════════════════════ + MAIN WORKSPACE LAYOUT (Tool Dock + Canvas Stage + Inspector) +═══════════════════════════════════════════════════════════════════ */ +.ps-main-body { + flex: 1; + display: flex; + position: relative; + overflow: hidden; + height: calc(100vh - 52px); +} + +/* ═══════════════════════════════════════════════════════════════════ + LEFT SLIM TOOL DOCK (Photoshop Iconic Palette) +═══════════════════════════════════════════════════════════════════ */ +.ps-tool-dock { + width: 58px; + height: 100%; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(28px) saturate(190%); + -webkit-backdrop-filter: blur(28px) saturate(190%); + border-right: 1px solid var(--border-1); + box-shadow: 6px 0 24px rgba(0, 0, 0, 0.65); + display: flex; + flex-direction: column; + align-items: center; + padding: 12px 0 16px; + gap: 5px; + position: relative; + z-index: 40; + flex-shrink: 0; +} + +.ps-tool-btn { + width: 42px; + height: 42px; + border-radius: var(--r-md); + border: 1px solid transparent; + background: transparent; + color: var(--text-3); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + position: relative; + transition: all 0.18s cubic-bezier(0.16, 1, 0.3, 1); + font-size: 16px; + outline: none; +} + +.ps-tool-btn:hover { + background: rgba(255, 255, 255, 0.06); + color: var(--text-1); + border-color: var(--border-1); + transform: translateY(-1px); +} + +.ps-tool-btn.active { + background: linear-gradient(135deg, rgba(255, 108, 55, 0.28) 0%, rgba(255, 108, 55, 0.08) 100%); + color: #ffffff; + border-color: var(--primary-alpha2); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 0 16px var(--primary-alpha); +} + +.ps-tool-btn.active::before { + content: ''; + position: absolute; + left: -1px; + top: 10px; + bottom: 10px; + width: 3px; + border-radius: 0 var(--r-sm) var(--r-sm) 0; + background: var(--primary); + box-shadow: 0 0 8px var(--primary); +} + +.ps-tool-btn i { + transition: transform 0.18s ease; +} + +.ps-tool-btn:hover i { + transform: scale(1.15); +} + +.ps-tool-btn.active i { + color: var(--primary); + filter: drop-shadow(0 0 8px var(--primary-glow)); +} + +.ps-tool-shortcut { + position: absolute; + bottom: 3px; + right: 4px; + font-size: 8px; + font-family: var(--font-mono); + font-weight: 700; + color: var(--text-muted); + pointer-events: none; + opacity: 0.6; +} + +.ps-dock-divider { + width: 30px; + height: 1px; + background: var(--border-1); + margin: 6px 0; +} + +/* Tooltip on hover */ +[data-tooltip] { + position: relative; +} + +[data-tooltip]::after { + content: attr(data-tooltip); + position: absolute; + left: 68px; + top: 50%; + transform: translateY(-50%) scale(0.95); + background: rgba(14, 14, 20, 0.94); + backdrop-filter: blur(14px); + color: #ffffff; + border: 1px solid var(--border-2); + padding: 4px 9px; + border-radius: var(--r-sm); + font-size: 11px; + font-weight: 500; + white-space: nowrap; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s ease, transform 0.15s ease; + z-index: 100; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.8); +} + +[data-tooltip]:hover::after { + opacity: 1; + transform: translateY(-50%) scale(1); +} + +/* ═══════════════════════════════════════════════════════════════════ + CENTER WORKSPACE & VIEWPORT (Photoshop Canvas Stage) +═══════════════════════════════════════════════════════════════════ */ +.ps-workspace { + flex: 1; + height: 100%; + display: flex; + flex-direction: column; + position: relative; + overflow: hidden; + background: radial-gradient(circle at center, #111116 0%, #050507 100%); +} + +.ps-viewport { + flex: 1; + position: relative; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + background-image: + linear-gradient(45deg, #0e0e14 25%, transparent 25%), + linear-gradient(-45deg, #0e0e14 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #0e0e14 75%), + linear-gradient(-45deg, transparent 75%, #0e0e14 75%); + background-size: 24px 24px; + background-position: 0 0, 0 12px, 12px -12px, -12px 0px; +} + +/* Empty State Dropzone */ +.ps-dropzone-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + max-width: 580px; + width: 90%; + padding: 48px 36px; + background: var(--bg-smoke); + backdrop-filter: blur(28px) saturate(180%); + -webkit-backdrop-filter: blur(28px) saturate(180%); + border: 2px dashed var(--border-2); + border-radius: var(--r-xl); + box-shadow: var(--sh-liquid); + cursor: pointer; + transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1); + text-align: center; + position: relative; +} + +.ps-dropzone-empty:hover, .ps-dropzone-empty.dragover { + border-color: var(--primary); + background: rgba(255, 108, 55, 0.08); + box-shadow: var(--sh-liquid-hover); + transform: translateY(-2px); +} + +.ps-dropzone-icon { + width: 68px; + height: 68px; + border-radius: 50%; + background: var(--primary-alpha); + border: 1px solid var(--primary-alpha2); + display: flex; + align-items: center; + justify-content: center; + font-size: 30px; + color: var(--primary); + margin-bottom: 18px; + box-shadow: 0 0 28px var(--primary-glow); +} + +.ps-dropzone-empty h2 { + font-size: 18px; + font-weight: 700; + color: var(--text-1); +} + +.ps-dropzone-empty p { + font-size: 12.5px; + color: var(--text-3); + margin-top: 6px; +} + +.ps-dropzone-actions { + display: flex; + gap: 12px; + margin-top: 24px; +} + +/* Image Canvas Stage */ +.ps-stage-container { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + max-width: calc(100% - 48px); + max-height: calc(100% - 48px); + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.85); + border-radius: var(--r-md); + overflow: visible; + transition: transform 0.1s ease-out; +} + +.ps-active-img { + max-width: 100%; + max-height: calc(100vh - 200px); + display: block; + object-fit: contain; + border-radius: var(--r-md); + border: 1px solid var(--border-2); + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.7); + user-select: none; + pointer-events: none; +} + +/* Zoom / Viewport HUD Controls */ +.ps-viewport-hud { + position: absolute; + bottom: 16px; + right: 18px; + display: flex; + align-items: center; + gap: 6px; + background: rgba(14, 14, 20, 0.88); + backdrop-filter: blur(16px); + border: 1px solid var(--border-2); + border-radius: var(--r-full); + padding: 4px 8px; + z-index: 30; + box-shadow: var(--sh-glass); +} + +.ps-hud-btn { + background: none; + border: none; + color: var(--text-2); + width: 26px; + height: 26px; + border-radius: 50%; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 11px; + transition: background 0.15s ease, color 0.15s ease; +} + +.ps-hud-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.ps-hud-val { + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; + color: var(--text-1); + min-width: 44px; + text-align: center; +} + +/* ═══════════════════════════════════════════════════════════════════ + VISUAL INTERACTIVE CROPPER OVERLAY (Photoshop Marquee Cropper) +═══════════════════════════════════════════════════════════════════ */ +.ps-crop-overlay { + position: absolute; + inset: 0; + pointer-events: auto; + z-index: 25; + user-select: none; + overflow: hidden; +} + +/* Darkened Scrims Outside the Active Crop Box */ +.crop-scrim { + position: absolute; + background: rgba(0, 0, 0, 0.65); + pointer-events: auto; + transition: background 0.15s ease; +} + +.crop-scrim-top { top: 0; left: 0; right: 0; } +.crop-scrim-bottom { bottom: 0; left: 0; right: 0; } +.crop-scrim-left { top: 0; bottom: 0; left: 0; } +.crop-scrim-right { top: 0; bottom: 0; right: 0; } + +/* The Crop Rectangle Box */ +.crop-box { + position: absolute; + border: 1.5px solid var(--accent-cyan); + box-shadow: + 0 0 0 1px rgba(0, 0, 0, 0.8), + 0 0 16px var(--accent-cyan-glow); + cursor: move; + pointer-events: auto; + z-index: 28; +} + +/* Rule of Thirds Grid Lines inside Crop Box */ +.crop-grid { + position: absolute; + inset: 0; + pointer-events: none; +} + +.crop-grid-h1, .crop-grid-h2 { + position: absolute; + left: 0; + right: 0; + height: 1px; + background: rgba(255, 255, 255, 0.35); + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); +} +.crop-grid-h1 { top: 33.333%; } +.crop-grid-h2 { top: 66.666%; } + +.crop-grid-v1, .crop-grid-v2 { + position: absolute; + top: 0; + bottom: 0; + width: 1px; + background: rgba(255, 255, 255, 0.35); + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); +} +.crop-grid-v1 { left: 33.333%; } +.crop-grid-v2 { left: 66.666%; } + +/* Live Dimension Tag Above Crop Box */ +.crop-dim-badge { + position: absolute; + top: -28px; + left: 50%; + transform: translateX(-50%); + background: rgba(10, 10, 16, 0.92); + border: 1px solid var(--accent-cyan); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.7); + padding: 3px 8px; + border-radius: var(--r-sm); + font-family: var(--font-mono); + font-size: 11px; + font-weight: 700; + color: var(--accent-cyan); + white-space: nowrap; + pointer-events: none; + z-index: 30; +} + +/* 8 Resizing Handles */ +.crop-handle { + position: absolute; + width: 10px; + height: 10px; + background: #ffffff; + border: 1.5px solid #000000; + box-shadow: 0 0 6px var(--accent-cyan); + border-radius: 2px; + z-index: 32; +} + +.crop-handle-nw { top: -5px; left: -5px; cursor: nwse-resize; } +.crop-handle-n { top: -5px; left: calc(50% - 5px); cursor: ns-resize; width: 14px; } +.crop-handle-ne { top: -5px; right: -5px; cursor: nesw-resize; } +.crop-handle-e { top: calc(50% - 5px); right: -5px; cursor: ew-resize; height: 14px; } +.crop-handle-se { bottom: -5px; right: -5px; cursor: nwse-resize; } +.crop-handle-s { bottom: -5px; left: calc(50% - 5px); cursor: ns-resize; width: 14px; } +.crop-handle-sw { bottom: -5px; left: -5px; cursor: nesw-resize; } +.crop-handle-w { top: calc(50% - 5px); left: -5px; cursor: ew-resize; height: 14px; } + +/* ═══════════════════════════════════════════════════════════════════ + MASK CANVAS OVERLAY & LIVE BRUSH CURSOR +═══════════════════════════════════════════════════════════════════ */ +.ps-mask-canvas { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + cursor: crosshair; + z-index: 26; + opacity: 0.35; + touch-action: none; +} + +#brush-cursor-ring { + position: fixed; + pointer-events: none; + border: 1.5px solid #ff3333; + border-radius: 50%; + transform: translate(-50%, -50%); + display: none; + z-index: 1000; + box-shadow: 0 0 8px rgba(255, 51, 51, 0.6); +} + +/* ═══════════════════════════════════════════════════════════════════ + BOTTOM FILMSTRIP / QUEUE TRAY (Multi-File Bar) +═══════════════════════════════════════════════════════════════════ */ +.ps-filmstrip { + height: 82px; + min-height: 82px; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(24px) saturate(190%); + -webkit-backdrop-filter: blur(24px) saturate(190%); + border-top: 1px solid var(--border-2); + display: flex; + align-items: center; + padding: 0 16px; + gap: 12px; + position: relative; + z-index: 35; + box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.5); +} + +.ps-filmstrip-left { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + border-right: 1px solid var(--border-1); + padding-right: 12px; +} + +.ps-filmstrip-scroll { + flex: 1; + display: flex; + align-items: center; + gap: 8px; + overflow-x: auto; + padding: 4px 0; + scrollbar-width: thin; + scrollbar-color: var(--border-2) transparent; +} + +.ps-filmstrip-scroll::-webkit-scrollbar { + height: 5px; +} +.ps-filmstrip-scroll::-webkit-scrollbar-thumb { + background: var(--border-2); + border-radius: var(--r-full); +} + +.ps-thumb-card { + height: 64px; + min-width: 140px; + max-width: 180px; + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px; + background: var(--bg-input); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + cursor: pointer; + position: relative; + transition: all 0.18s ease; + flex-shrink: 0; +} + +.ps-thumb-card:hover { + background: var(--bg-card-hover); + border-color: var(--border-2); + transform: translateY(-2px); +} + +.ps-thumb-card.active { + background: linear-gradient(135deg, rgba(255, 108, 55, 0.22) 0%, rgba(255, 108, 55, 0.06) 100%); + border-color: var(--primary); + box-shadow: 0 0 12px var(--primary-alpha); +} + +.ps-thumb-img { + width: 48px; + height: 48px; + border-radius: var(--r-sm); + object-fit: cover; + background: #000; + border: 1px solid var(--border-1); + flex-shrink: 0; +} + +.ps-thumb-meta { + display: flex; + flex-direction: column; + overflow: hidden; + gap: 2px; +} + +.ps-thumb-name { + font-size: 11px; + font-weight: 600; + color: var(--text-1); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.ps-thumb-size { + font-size: 10px; + font-family: var(--font-mono); + color: var(--text-3); +} + +.ps-thumb-close { + position: absolute; + top: 3px; + right: 4px; + width: 16px; + height: 16px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.7); + border: 1px solid var(--border-1); + color: var(--text-3); + display: none; + align-items: center; + justify-content: center; + font-size: 9px; + cursor: pointer; +} + +.ps-thumb-card:hover .ps-thumb-close { + display: flex; +} + +.ps-thumb-close:hover { + background: #ef4444; + color: #fff; +} + +/* ═══════════════════════════════════════════════════════════════════ + RIGHT INSPECTOR PANEL (Photoshop Properties & Batch Hub) +═══════════════════════════════════════════════════════════════════ */ +.ps-inspector { + width: 320px; + height: 100%; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(28px) saturate(190%); + -webkit-backdrop-filter: blur(28px) saturate(190%); + border-left: 1px solid var(--border-1); + box-shadow: -6px 0 24px rgba(0, 0, 0, 0.65); + display: flex; + flex-direction: column; + position: relative; + z-index: 40; + flex-shrink: 0; +} + +.ps-inspector-tabs { + display: flex; + border-bottom: 1px solid var(--border-1); + padding: 0 8px; + background: rgba(0, 0, 0, 0.2); +} + +.ps-inspector-tab { + flex: 1; + padding: 12px 6px; + text-align: center; + font-size: 11.5px; + font-weight: 600; + color: var(--text-3); + cursor: pointer; + border-bottom: 2px solid transparent; + transition: all 0.2s ease; + user-select: none; +} + +.ps-inspector-tab:hover { + color: var(--text-1); +} + +.ps-inspector-tab.active { + color: var(--primary); + border-bottom-color: var(--primary); +} + +.ps-inspector-content { + flex: 1; + overflow-y: auto; + padding: 18px 20px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.ps-section-title { + font-size: 10.5px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-muted); + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; +} + +.ps-action-footer { + padding: 16px 20px; + border-top: 1px solid var(--border-1); + background: rgba(0, 0, 0, 0.3); + display: flex; + flex-direction: column; + gap: 10px; +} + +/* ═══════════════════════════════════════════════════════════════════ + FORM CONTROLS & RANGE SLIDERS +═══════════════════════════════════════════════════════════════════ */ +.input-group { + display: flex; + flex-direction: column; + margin-bottom: 12px; +} + +.input-group label { + font-size: 11.5px; + font-weight: 600; + color: var(--text-2); + margin-bottom: 6px; + display: flex; + align-items: center; + justify-content: space-between; +} + +.label-val { + font-family: var(--font-mono); + font-size: 11px; + color: var(--primary); + font-weight: 700; +} + +input[type="text"], +input[type="number"], +input[type="color"], +select, +textarea { + width: 100%; + height: 36px; + padding: 0 12px; + background: var(--bg-input); + border: 1px solid var(--border-2); + border-radius: var(--r-md); + color: var(--text-1); + font-family: var(--font-main); + font-size: 12.5px; + outline: none; + transition: all 0.2s ease; + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.5); +} + +input[type="text"]:focus, +input[type="number"]:focus, +select:focus, +textarea:focus { + border-color: var(--border-focus); + background: var(--bg-input-focus); + box-shadow: 0 0 0 1px var(--primary-alpha2), 0 0 16px var(--primary-alpha); +} + +select { + cursor: pointer; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='rgba(255,255,255,0.6)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 12px center; + padding-right: 32px; + appearance: none; + -webkit-appearance: none; +} + +select option { + background: #121218; + color: var(--text-1); +} + +/* Custom Range Sliders */ +input[type="range"] { + -webkit-appearance: none; + width: 100%; + height: 5px; + border-radius: var(--r-full); + background: rgba(255, 255, 255, 0.12); + outline: none; + cursor: pointer; + margin: 8px 0; +} + +input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--primary); + border: 2px solid #ffffff; + box-shadow: 0 0 10px var(--primary-glow); + cursor: pointer; + transition: transform 0.15s ease; +} + +input[type="range"]::-webkit-slider-thumb:hover { + transform: scale(1.25); +} + +/* Segment Pill Buttons */ +.seg-pills-row { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin-top: 4px; +} + +.seg-pill { + padding: 5px 10px; + background: var(--bg-input); + border: 1px solid var(--border-2); + border-radius: var(--r-md); + font-size: 11px; + font-weight: 600; + color: var(--text-2); + cursor: pointer; + transition: all 0.18s ease; + user-select: none; +} + +.seg-pill:hover { + background: rgba(255, 255, 255, 0.08); + color: var(--text-1); + border-color: var(--border-3); +} + +.seg-pill.active { + background: var(--primary-alpha); + border-color: var(--primary-alpha2); + color: var(--primary); + box-shadow: 0 0 12px var(--primary-alpha); +} + +/* Color Swatches */ +.color-swatches-row { + display: flex; + gap: 8px; + align-items: center; + margin-top: 6px; +} + +.color-swatch { + width: 24px; + height: 24px; + border-radius: 50%; + border: 2px solid rgba(255, 255, 255, 0.2); + cursor: pointer; + transition: transform 0.15s ease, border-color 0.15s ease; +} + +.color-swatch:hover { + transform: scale(1.2); + border-color: #ffffff; +} + +/* ═══════════════════════════════════════════════════════════════════ + BUTTONS +═══════════════════════════════════════════════════════════════════ */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + height: 38px; + padding: 0 16px; + background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); + color: #ffffff; + font-family: var(--font-main); + font-size: 12.5px; + font-weight: 600; + border-radius: var(--r-md); + border: 1px solid rgba(255, 255, 255, 0.25); + cursor: pointer; + transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 -1px 0 rgba(0, 0, 0, 0.50) inset, + 0 8px 20px var(--primary-glow); + text-decoration: none; + user-select: none; + white-space: nowrap; +} + +.btn:hover { + transform: translateY(-2px); + box-shadow: + 0 1.5px 0 rgba(255, 255, 255, 0.60) inset, + 0 12px 28px var(--primary-glow); + filter: brightness(1.08); +} + +.btn:active { + transform: translateY(0); +} + +.btn-secondary { + background: var(--bg-card); + border: 1px solid var(--border-2); + color: var(--text-2); + box-shadow: var(--sh-glass); +} + +.btn-secondary:hover { + background: var(--bg-card-hover); + color: var(--text-1); + border-color: var(--border-3); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.45); +} + +.btn-cyan { + background: linear-gradient(135deg, var(--accent-cyan) 0%, #0072ff 100%); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 8px 20px var(--accent-cyan-glow); + color: #000000; + font-weight: 700; +} + +.btn-cyan:hover { + box-shadow: + 0 1.5px 0 rgba(255, 255, 255, 0.60) inset, + 0 12px 28px var(--accent-cyan-glow); + filter: brightness(1.1); +} + +.btn-sm { + height: 30px; + padding: 0 10px; + font-size: 11.5px; +} + +.btn-icon-only { + width: 32px; + height: 32px; + padding: 0; + border-radius: var(--r-md); +} + +/* ═══════════════════════════════════════════════════════════════════ + BATCH PROGRESS MODAL & GLASS HUD +═══════════════════════════════════════════════════════════════════ */ +.ps-modal-backdrop { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.82); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + z-index: 2000; + display: flex; + align-items: center; + justify-content: center; +} + +.ps-modal-card { + width: 90%; + max-width: 540px; + background: var(--bg-smoke-heavy); + border: 1px solid var(--border-3); + border-radius: var(--r-xl); + padding: 28px 32px; + box-shadow: var(--sh-liquid-hover); + display: flex; + flex-direction: column; + gap: 18px; + position: relative; +} + +.ps-progress-header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.ps-progress-header h3 { + font-size: 16px; + font-weight: 700; + color: var(--text-1); + display: flex; + align-items: center; + gap: 8px; +} + +.ps-progress-pct { + font-family: var(--font-mono); + font-size: 18px; + font-weight: 800; + color: var(--primary); +} + +.ps-progress-track { + width: 100%; + height: 8px; + background: rgba(255, 255, 255, 0.08); + border-radius: var(--r-full); + overflow: hidden; + position: relative; +} + +.ps-progress-fill { + height: 100%; + width: 0%; + background: linear-gradient(90deg, var(--primary) 0%, var(--accent-cyan) 100%); + border-radius: var(--r-full); + transition: width 0.2s ease; + box-shadow: 0 0 16px var(--primary-glow); +} + +.ps-progress-stats { + display: flex; + align-items: center; + justify-content: space-between; + font-family: var(--font-mono); + font-size: 11.5px; + color: var(--text-3); +} + +.ps-progress-speed { + color: var(--accent-cyan); + font-weight: 600; +} + +.ps-console-box { + max-height: 140px; + overflow-y: auto; + background: rgba(0, 0, 0, 0.6); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + padding: 10px 14px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-3); + display: flex; + flex-direction: column; + gap: 4px; +} + +.ps-console-line { + white-space: pre-wrap; + word-break: break-all; +} + +.ps-console-line.error { + color: #ef4444; +} + +.ps-console-line.success { + color: var(--accent-emerald); +} + +/* ═══════════════════════════════════════════════════════════════════ + TOAST NOTIFICATIONS +═══════════════════════════════════════════════════════════════════ */ +.toast-container { + position: fixed; + bottom: 24px; + right: 24px; + z-index: 9999; + display: flex; + flex-direction: column; + gap: 10px; + pointer-events: none; +} + +.toast { + pointer-events: auto; + padding: 12px 18px; + background: rgba(14, 14, 20, 0.95); + backdrop-filter: blur(20px); + -webkit-backdrop-filter: blur(20px); + border: 1px solid var(--border-2); + border-radius: var(--r-lg); + box-shadow: var(--sh-liquid); + display: flex; + align-items: center; + gap: 10px; + font-size: 12.5px; + font-weight: 500; + color: var(--text-1); + transform: translateY(20px); + opacity: 0; + animation: toastIn 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +@keyframes toastIn { + to { + transform: translateY(0); + opacity: 1; + } +} + +.toast.success { + border-color: rgba(16, 185, 129, 0.4); +} +.toast.success i { + color: var(--accent-emerald); +} + +.toast.error { + border-color: rgba(239, 68, 68, 0.4); +} +.toast.error i { + color: #ef4444; } diff --git a/web/image-manipulator/app.js b/web/image-manipulator/app.js index 466217d..a1c7988 100644 --- a/web/image-manipulator/app.js +++ b/web/image-manipulator/app.js @@ -1,1464 +1,1832 @@ -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: ` -
-
- - -
-
- - -
-
-
- -
- `, - }, - convert: { - title: "Convert Formats", - desc: "Convert images between PNG, JPG, WEBP, HEIC, and more.", - controls: ` -
-
- - -
-
- - -
-
- `, - }, - compress: { - title: "Compress Images", - desc: "Reduce file size optimized for web (Lossless-ish/High Efficiency).", - controls: ` -
- - -
-
- - - 80% -
-
-
- Original Est: - -- -
-
- New Est: - -- -
-
- Select an image to see stats -
-
- `, - }, - crop: { - title: "Crop Images", - desc: "Trim images to specific coordinates.", - controls: ` -
-
-
-
-
-
- `, - }, - filter: { - title: "Apply Filters", - desc: "Enhance images with artistic effects.", - controls: ` -
- - -
- `, - }, - rotate: { - title: "Rotate & Flip", - desc: "Change orientation of images.", - controls: ` -
- - -
- `, - }, - watermark: { - title: "Add Watermark", - desc: "Overlay logo or text image.", - controls: ` -
- - -
-
-
- - -
-
- - -
-
- `, - }, - masker: { - title: "Mask Generator", - desc: "Draw over the object to create a binary mask.", - controls: ` -
- - - 30px -
-
-

Draw with the red brush over the area you want to mask. The output will be white on black background.

-
- `, - }, - }; - - // 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 = ` -
- -
- `; - 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" - ? ` ${msg}` - : ` ${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 = - ' 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 = ` -
- Result -
-
-
${res.filename}
-
- ${res.info.width}x${res.info.height} - ${res.info.format} -
- - Download - -
- `; - 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: ` -
-
-
-
-
- `, - convert: toolConfigs.convert.controls, - compress: ` -
- - -
-
-
- - - -
-
- - -
-
- - `, - crop: toolConfigs.crop.controls, - filter: toolConfigs.filter.controls, - rotate: toolConfigs.rotate.controls, - watermark: ` -
- - -
-
-
- - -
-
- - -
-
- `, - }; - - 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 = ` -
-

- Files Ready for Processing -

- -
-
-
- ${totalCount} file(s) selected | ${totalSizeMb} MB total -
- ${totalCount > 50 ? `
Showing first 50 files
` : ""} -
-
- ${filesToPreview - .map( - (f) => ` -
- - ${f.filename} - - - ${f.size_kb || (f.size / 1024).toFixed(1)} KB - -
- `, - ) - .join("")} -
- `; - - 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 = ''; - 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 = ` -
-
-

Drag & Drop images here

-

or click to browse from computer

-
- Supported: PNG, JPG, WEBP, HEIC, BMP, TIFF, ICO -
-
- `; - 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(); +/** + * 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); + }); - const pos = getPos(e); - currentStroke.points.push(pos); + ["dragenter", "dragover"].forEach(evtName => { + target.addEventListener(evtName, () => { + const emptyDrop = document.getElementById("ps-empty-dropzone"); + if (emptyDrop) emptyDrop.classList.add("dragover"); + }, false); + }); - // Draw segment ONLY (fixes opacity stacking) - maskCtx.beginPath(); - maskCtx.moveTo(lastPos.x, lastPos.y); - maskCtx.lineTo(pos.x, pos.y); - maskCtx.stroke(); + ["dragleave", "drop"].forEach(evtName => { + target.addEventListener(evtName, () => { + const emptyDrop = document.getElementById("ps-empty-dropzone"); + if (emptyDrop) emptyDrop.classList.remove("dragover"); + }, false); + }); - lastPos = pos; - } + 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(); + } + }; - function stopDraw(e) { - if (isDrawing) { - isDrawing = false; - maskCtx.closePath(); + 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; } } - function updateBrushCursor(size) { - // Optional: visual cursor feedback - } \ No newline at end of file + 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 = ` ${count} image${count === 1 ? "" : "s"} (${totalMb} MB)`; + 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 = ` Batch All (${count})`; + } else { + btnBatchHeader.style.display = "none"; + } + } + + if (btnBatchFooter) { + if (count > 1) { + btnBatchFooter.style.display = "inline-flex"; + btnBatchFooter.innerHTML = ` 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 = ` + thumb +
+ ${item.name} + ${item.naturalW}×${item.naturalH} · ${sizeKb}KB +
+ + `; + 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: ` +
+ Aspect: + + + + + + +
+
+ + -- +
+ `, + resize: ` +
+ Scale Presets: + + + + + +
+ `, + adjust: ` +
+ Presets: + + + + +
+ `, + filter: ` +
+ Quick Filter: + + + + + + +
+ `, + rotate: ` +
+ Transform: + + + + + +
+ `, + round_corners: ` +
+ Radius: + + 35px +
+
+ +
+ `, + border: ` +
+ Canvas Aspect Pad: + + + + +
+ `, + watermark: ` +
+ Position: + + + + + +
+ `, + masker: ` +
+ Brush Size: + + 35px +
+
+ + +
+ `, + convert: ` +
+ Target Format: + + + + + + +
+ `, + compress: ` +
+ Quality: + + 80% +
+
+ Simulating... +
+ `, + strip_metadata: ` +
+ Privacy Guard Active: Strips EXIF, GPS, Camera Model, Timestamps +
+ ` + }; + + 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: ` +
Visual Crop Coordinates
+
+ + +
+
+
Drag to Frame
+

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.

+
+ `, + resize: ` +
Dimensions & Resampling
+
+
+ + +
+
+ + +
+
+
+ +
+ `, + adjust: ` +
Color Grading Sliders
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+ `, + filter: ` +
Select Artistic Filter
+
+ + +
+ `, + rotate: ` +
Orientation & Angle
+
+ + +
+
+ + +
+ `, + round_corners: ` +
Corner Geometry
+
+ + +
+
+ +
+ `, + border: ` +
Border & Canvas Framing
+
+ + +
+
+ +
+ + +
+
+
+
+
+
+
+
+
+
+
+ + +
+ `, + watermark: ` +
Watermark Stamp
+
+ + +
+
+ + +
+
+ + +
+ `, + masker: ` +
Mask Generator & Brush
+
+ + +
+
+

Paint over the foreground object with the red brush. The generated binary mask outputs pure white on a black canvas.

+
+ `, + convert: ` +
Transcode Format
+
+ + +
+
+ + +
+ `, + compress: ` +
Compression Engine
+
+ + +
+
+ + +
+
+ + +
+
+
+ Original Size: + -- +
+
+ Estimated Output: + -- +
+
+ Reduction: -- +
+
+ `, + strip_metadata: ` +
EXIF Privacy Cleaner
+
+ + +
+
+
Cleans All Hidden Metadata:
+
• GPS Geolocation Coordinates
+
• Camera Model, Serial Number & Lens
+
• Creation Date, Exposure & Shutter Speeds
+
• Embedded Thumbnails & Author Tags
+
+ ` + }; + + 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 = ` ${msg}`; + container.appendChild(toast); + setTimeout(() => toast.remove(), 4000); +} +window.showToast = showToast; diff --git a/web/image-manipulator/index.html b/web/image-manipulator/index.html index 5bf3d79..d9c9c30 100644 --- a/web/image-manipulator/index.html +++ b/web/image-manipulator/index.html @@ -1,263 +1,339 @@ - + - - - - ImagePro Toolkit | Professional Image Manipulation - - + + + + + + Photoshop Lite · Obsidian Liquid Studio + + + + + + - - - - - - -
-
-
+ + + + + +
- - - -
- -
-
-

Resize Images

-

- Change image dimensions while maintaining quality. -

-
-
+ +
- -
-
-
-
- + + - - -
-
-
- - - -
- - +
+ Preparing files... + 0.0 MB/s
-
- -
- Or drag & drop files/folders here -
-
+ +
+
> Initializing Obsidian batch engine...
-

- Files will be uploaded and processed. Results will download as a - ZIP file. -

-
-
-
- - +
+
-
- - -
- -
- - -
- -
-
> Ready to process...
-
- - -
- -
-
-

Processing...

-
- - +
- - - \ No newline at end of file + + + diff --git a/web/image-manipulator/styles.css b/web/image-manipulator/styles.css index 556769b..d6d761f 100644 --- a/web/image-manipulator/styles.css +++ b/web/image-manipulator/styles.css @@ -1,491 +1,1311 @@ +/* ═══════════════════════════════════════════════════════════════════ + IMAGEPRO · PHOTOSHOP LITE · BLACK OBSIDIAN LIQUID GLASS + GPU-accelerated 120 FPS hardware compositing, fluid reflections, + and precision Photoshop-inspired ergonomics. +═══════════════════════════════════════════════════════════════════ */ + :root { - --primary: #FF6C37; - --primary-dark: #e55f2c; - --secondary: #FF8559; - --bg-dark: #1a1a1a; - --bg-card: #252525; - --bg-input: #2b2b2b; - --text-main: #EAEAEA; - --text-secondary: #A6A6A6; - --border: #333333; - --border-focus: #FF6C37; - --sidebar-width: 260px; - } + --bg-void: #000000; + --bg-smoke: rgba(10, 10, 14, 0.78); + --bg-smoke-heavy: rgba(6, 6, 9, 0.92); + --bg-card: rgba(14, 14, 20, 0.68); + --bg-card-hover: rgba(22, 22, 32, 0.84); + --bg-input: rgba(18, 18, 26, 0.75); + --bg-input-focus: rgba(26, 26, 38, 0.95); - * { margin: 0; padding: 0; box-sizing: border-box; } + /* Primary Brand: Obsidian Flame & Cyan Caustics */ + --primary: #ff6c37; + --primary-hover: #ff8252; + --primary-dark: #e5531d; + --primary-alpha: rgba(255, 108, 55, 0.18); + --primary-alpha2: rgba(255, 108, 55, 0.35); + --primary-glow: rgba(255, 108, 55, 0.45); - body { - font-family: 'Inter', sans-serif; - background-color: var(--bg-dark); - color: var(--text-main); - height: 100vh; - display: flex; - overflow: hidden; - position: relative; - } + --accent-cyan: #00f2fe; + --accent-cyan-hover: #38f9d7; + --accent-cyan-alpha: rgba(0, 242, 254, 0.16); + --accent-cyan-glow: rgba(0, 242, 254, 0.40); - /* Sidebar */ - .sidebar { - width: var(--sidebar-width); - background: rgba(255, 255, 255, 0.05); - - border-right: 1px solid var(--border); - display: flex; - flex-direction: column; - padding: 24px; - transition: transform 0.3s ease; - position: relative; - z-index: 10; - box-shadow: 0 0 30px rgba(0, 0, 0, 0.3); - } + --accent-emerald: #10b981; + --accent-emerald-alpha: rgba(16, 185, 129, 0.18); + --accent-purple: #a855f7; + --accent-purple-alpha: rgba(168, 85, 247, 0.18); - .logo { - display: flex; - align-items: center; - gap: 12px; - font-size: 1.25rem; - font-weight: 700; - color: var(--primary); - margin-bottom: 40px; - padding-bottom: 24px; - border-bottom: 1px solid var(--border); - } + --text-1: #ffffff; + --text-2: #cbd5e1; + --text-3: #94a3b8; + --text-muted: #64748b; - .logo i { - font-size: 1.5rem; - color: var(--primary); - filter: drop-shadow(0 0 10px var(--primary)); - } + --border-1: rgba(255, 255, 255, 0.08); + --border-2: rgba(255, 255, 255, 0.15); + --border-3: rgba(255, 255, 255, 0.28); + --border-focus: rgba(255, 108, 55, 0.65); + --border-cyan: rgba(0, 242, 254, 0.50); - .nav-links { - display: flex; - flex-direction: column; - gap: 8px; - flex: 1; - } + --r-sm: 6px; + --r-md: 10px; + --r-lg: 16px; + --r-xl: 22px; + --r-full: 9999px; - .nav-item { - display: flex; - align-items: center; - gap: 12px; - padding: 12px 16px; - color: var(--text-secondary); - text-decoration: none; - border-radius: 12px; - transition: all 0.3s; - cursor: pointer; - font-weight: 500; - background: transparent; - } + /* Liquid Glass Shadow Tokens */ + --sh-liquid: + 0 1px 0 rgba(255, 255, 255, 0.38) inset, + 0 -1px 0 rgba(0, 0, 0, 0.70) inset, + 0 18px 48px rgba(0, 0, 0, 0.75); + --sh-liquid-hover: + 0 1.5px 0 rgba(255, 255, 255, 0.55) inset, + 0 -1px 0 rgba(0, 0, 0, 0.80) inset, + 0 24px 60px rgba(0, 0, 0, 0.85), + 0 0 30px var(--primary-glow); + --sh-glass: + 0 1px 0 rgba(255, 255, 255, 0.20) inset, + 0 -1px 0 rgba(0, 0, 0, 0.60) inset, + 0 8px 24px rgba(0, 0, 0, 0.55); - .nav-item:hover { - background: rgba(0, 245, 255, 0.1); - color: #fff; - transform: translateX(5px); - } - - .nav-item.active { - background: var(--primary); - color: #fff; - box-shadow: 0 4px 20px rgba(255, 108, 55, 0.4); - } - - .nav-item i { width: 24px; text-align: center; } - - .divider { - height: 1px; - background: linear-gradient(90deg, transparent, var(--border), transparent); - margin: 16px 0; - } - - .section-title { - font-size: 0.75rem; - text-transform: uppercase; - letter-spacing: 0.05em; - color: var(--primary); - margin-bottom: 12px; - padding-left: 12px; - font-weight: 600; - } - - /* Main Content */ - .main-content { - flex: 1; - overflow-y: auto; - padding: 40px; - position: relative; - z-index: 5; - } - - .header { - display: flex; - justify-content: space-between; - align-items: center; - margin-bottom: 32px; - background: var(--bg-card); - - border: 1px solid var(--border); - border-radius: 20px; - padding: 25px 30px; - box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2); - } - - .page-title h2 { - font-size: 1.875rem; - font-weight: 700; - margin-bottom: 8px; - color: #fff; - - - - } - .page-title p { color: var(--text-secondary); } - - /* Tools Container */ - .tool-view { display: none; animation: fadeIn 0.4s ease; } - .tool-view.active { display: block; } - - @keyframes fadeIn { - from { opacity: 0; transform: translateY(10px); } - to { opacity: 1; transform: translateY(0); } - } - - /* Upload Area */ - .upload-area { - border: 2px dashed var(--border); - border-radius: 20px; - padding: 20px; - min-height: 250px; - text-align: center; - background: rgba(255, 108, 55, 0.05); - - transition: all 0.3s; - cursor: pointer; - position: relative; - overflow: hidden; - margin-bottom: 32px; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; - } - - .upload-area:hover, .upload-area.dragover { - border-color: var(--primary); - background: rgba(255, 108, 55, 0.1); - transform: translateY(-5px); - box-shadow: 0 20px 60px rgba(255, 108, 55, 0.4); - } - - .upload-icon { - font-size: 48px; - color: var(--primary); - margin-bottom: 16px; - filter: drop-shadow(0 0 20px var(--primary)); - } - - /* Controls Panel */ - .controls-panel { - background: var(--bg-card); - - border: 1px solid var(--border); - border-radius: 20px; - padding: 24px; - margin-bottom: 32px; - box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4), inset 0 1px 0 rgba(255, 255, 255, 0.2); - } - - .input-group { margin-bottom: 20px; } - .input-group label { display: block; margin-bottom: 8px; font-weight: 500; color: var(--text-secondary); } - - input[type="text"], input[type="number"], select { - width: 100%; - padding: 12px 16px; - background: rgba(0, 0, 0, 0.3); - border: 2px solid var(--border); - border-radius: 12px; - color: #fff; - font-size: 1rem; - transition: all 0.2s; - } - - input[type="text"]:focus, input[type="number"]:focus, select:focus { - outline: none; - border-color: var(--primary); - box-shadow: 0 0 20px rgba(255, 108, 55, 0.4); - } - - .grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; } - .grid-4 { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; } - - /* Range Slider */ - input[type="range"] { - width: 100%; - height: 6px; - background: var(--border); - border-radius: 3px; - appearance: none; - } - - input[type="range"]::-webkit-slider-thumb { - appearance: none; - width: 20px; - height: 20px; - background: var(--primary); - border-radius: 50%; - cursor: pointer; - transition: transform 0.2s; - box-shadow: 0 0 15px rgba(0, 245, 255, 0.6); - } - - input[type="range"]::-webkit-slider-thumb:hover { - transform: scale(1.2); - } - - /* Buttons */ - .btn { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - padding: 12px 24px; - background: var(--primary); - color: white; - border: none; - border-radius: 12px; - font-weight: 700; - font-size: 1rem; - cursor: pointer; - transition: all 0.4s cubic-bezier(0.23, 1, 0.320, 1); - width: 100%; - box-shadow: 0 10px 30px rgba(255, 108, 55, 0.4); - - .btn::after { - content: ''; - position: absolute; - top: 50%; - left: 50%; - width: 0; - height: 0; - border-radius: 50%; - background: rgba(255, 255, 255, 0.5); - transform: translate(-50%, -50%); - transition: width 0.6s, height 0.6s; - } - - .btn:active::after { - width: 300px; - height: 300px; - } - - .btn-secondary { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.15), rgba(255, 255, 255, 0.05)); - box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3); - } - .btn-secondary:hover { - background: linear-gradient(135deg, rgba(255, 255, 255, 0.2), rgba(255, 255, 255, 0.1)); - } - - /* Results */ - .results-grid { - display: grid; - grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); - gap: 24px; - } - - .result-card { - background-color: var(--bg-card); - border: 1px solid var(--border); - border-radius: 12px; - overflow: hidden; - transition: transform 0.3s; - } - - .result-card:hover { transform: translateY(-4px); border-color: var(--primary); } - - .image-preview { - height: 200px; - background-color: #000; - display: flex; - align-items: center; - justify-content: center; - overflow: hidden; - } - - .image-preview img { - max-width: 100%; - max-height: 100%; - object-fit: contain; - } - - .card-body { padding: 16px; } - .file-name { font-weight: 600; margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } - .file-meta { font-size: 0.875rem; color: var(--text-secondary); margin-bottom: 16px; display: flex; justify-content: space-between; } - - .download-link { - display: flex; - align-items: center; - justify-content: center; - gap: 8px; - padding: 8px; - background-color: rgba(99, 102, 241, 0.1); - color: var(--primary); - text-decoration: none; - border-radius: 6px; - font-size: 0.875rem; - font-weight: 500; - transition: background 0.2s; - } - - .download-link:hover { background-color: rgba(99, 102, 241, 0.2); } - - /* Batch Console */ - .console { - background-color: #000; - border-radius: 8px; - padding: 16px; - font-family: 'Courier New', monospace; - font-size: 0.9rem; - color: #10b981; - height: 300px; - overflow-y: auto; - margin-top: 24px; - border: 1px solid var(--border); - } - - .console-line { margin-bottom: 4px; } - .console-error { color: #ef4444; } - - /* Toast Messages */ - .toast-container { - position: fixed; - bottom: 24px; - right: 24px; - z-index: 1000; - } - - .toast { - background-color: var(--bg-card); - border-left: 4px solid var(--primary); - padding: 16px 24px; - border-radius: 8px; - box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1); - margin-top: 12px; - display: flex; - align-items: center; - gap: 12px; - animation: slideIn 0.3s ease; - } - - .toast.error { border-left-color: #ef4444; } - .toast.success { border-left-color: #10b981; } - - @keyframes slideIn { - from { transform: translateX(100%); opacity: 0; } - to { transform: translateX(0); opacity: 1; } - } - - /* Loading */ - .loader { - display: none; - position: fixed; - top: 0; left: 0; width: 100%; height: 100%; - background: rgba(15, 23, 42, 0.8); - z-index: 999; - justify-content: center; - align-items: center; - flex-direction: column; - animation: glow 3s ease-in-out infinite; - } - - .loader.active { display: flex; } - - @keyframes glow { - 0%, 100% { filter: drop-shadow(0 0 20px #8b5cf6); } - 50% { filter: drop-shadow(0 0 35px #a78bfa); } - } - - /* Custom Animated Loader Spinner */ - .spinner { - width: 50px; - height: 50px; - border: 5px solid rgba(139, 92, 246, 0.3); - border-top-color: #8b5cf6; - border-radius: 50%; - animation: loaderSpin 1s cubic-bezier(0.68, -0.55, 0.265, 1.55) infinite; - } - - @keyframes loaderSpin { - 0% { transform: rotate(0deg) scale(1); } - 50% { transform: rotate(180deg) scale(1.2); } - 100% { transform: rotate(360deg) scale(1); } - } - - /* Text Shadow Pulse on Hover */ - h1, h2, h3 { - transition: all 0.3s ease; - } - - h1:hover, h2:hover, h3:hover { - text-shadow: 0 0 20px rgba(139, 92, 246, 0.8), - 0 0 40px rgba(139, 92, 246, 0.5), - 0 0 60px rgba(139, 92, 246, 0.3); - transform: translateY(-2px); - } - - /* Icon Float Animation */ - .icon-float { - animation: floatIcon 3s ease-in-out infinite; - } - - @keyframes floatIcon { - 0%, 100% { transform: translateY(0px); } - 50% { transform: translateY(-15px); } - } - - /* Input Focus Glow Effect */ - input[type="range"]:focus { - outline: none; - box-shadow: 0 0 0 3px rgba(255, 108, 55, 0.4); - } - - /* Tooltip Fade In */ - [title]:hover::after { - content: attr(title); - position: absolute; - bottom: 125%; - left: 50%; - transform: translateX(-50%); - padding: 8px 12px; - background: rgba(139, 92, 246, 0.95); - color: white; - border-radius: 6px; - font-size: 12px; - white-space: nowrap; - opacity: 0; - animation: tooltipFade 0.3s ease forwards; - pointer-events: none; - } - - @keyframes tooltipFade { - to { opacity: 1; transform: translateX(-50%) translateY(-5px); } - } - /* Scrollbar */ - ::-webkit-scrollbar { width: 12px; height: 12px; } - ::-webkit-scrollbar-track { background: rgba(0, 0, 0, 0.3); border-radius: 10px; } - ::-webkit-scrollbar-thumb { background: linear-gradient(135deg, #8b5cf6, #a78bfa); border-radius: 10px; } - -/* ─── Low-end device & responsiveness performance optimizations ─── */ -@media (prefers-reduced-motion: reduce) { - *, *::before, *::after { - animation-duration: 0.01ms !important; - animation-iteration-count: 1 !important; - transition-duration: 0.01ms !important; - } + --font-main: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; + --font-mono: 'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace; } -.sidebar { - contain: layout style; + +*, *::before, *::after { + box-sizing: border-box; + margin: 0; + padding: 0; } -.main-content { - contain: content; + +html, body { + width: 100%; + height: 100%; + overflow: hidden; + background-color: var(--bg-void); + color: var(--text-1); + font-family: var(--font-main); + font-size: 13px; + line-height: 1.45; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + user-select: none; +} + +/* Ambient Obsidian Caustics */ +.ambient-canvas { + position: fixed; + inset: 0; + pointer-events: none; + z-index: 0; + overflow: hidden; + background: + radial-gradient(circle at 10% 15%, rgba(255, 108, 55, 0.09) 0%, transparent 45%), + radial-gradient(circle at 90% 85%, rgba(0, 242, 254, 0.07) 0%, transparent 50%), + radial-gradient(circle at 50% 50%, rgba(168, 85, 247, 0.04) 0%, transparent 60%), + #000000; +} + +/* ═══════════════════════════════════════════════════════════════════ + APP ROOT LAYOUT +═══════════════════════════════════════════════════════════════════ */ +.ps-app-root { + display: flex; + flex-direction: column; + width: 100vw; + height: 100vh; + position: relative; + z-index: 1; + overflow: hidden; +} + +/* ═══════════════════════════════════════════════════════════════════ + TOP APPLICATION BAR & CONTEXTUAL OPTIONS STRIP +═══════════════════════════════════════════════════════════════════ */ +.ps-app-header { + height: 52px; + min-height: 52px; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(24px) saturate(190%); + -webkit-backdrop-filter: blur(24px) saturate(190%); + border-bottom: 1px solid var(--border-2); + display: flex; + align-items: center; + justify-content: space-between; + padding: 0 16px; + gap: 16px; + position: relative; + z-index: 50; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.6); +} + +.ps-header-left { + display: flex; + align-items: center; + gap: 12px; + flex-shrink: 0; +} + +.ps-brand-badge { + display: flex; + align-items: center; + gap: 8px; + cursor: pointer; +} + +.ps-logo-icon { + width: 32px; + height: 32px; + border-radius: var(--r-md); + background: linear-gradient(135deg, rgba(255, 108, 55, 0.35) 0%, rgba(0, 242, 254, 0.25) 100%); + border: 1px solid var(--border-cyan); + box-shadow: 0 0 16px var(--accent-cyan-alpha), 0 0 12px var(--primary-alpha); + display: flex; + align-items: center; + justify-content: center; + font-family: var(--font-mono); + font-weight: 800; + font-size: 15px; + color: #ffffff; + letter-spacing: -0.5px; +} + +.ps-brand-text { + display: flex; + flex-direction: column; +} + +.ps-brand-text h1 { + font-size: 13.5px; + font-weight: 700; + color: var(--text-1); + letter-spacing: -0.01em; + display: flex; + align-items: center; + gap: 6px; +} + +.ps-brand-text span { + font-size: 9.5px; + font-weight: 600; + color: var(--accent-cyan); + text-transform: uppercase; + letter-spacing: 0.08em; +} + +.ps-menu-divider { + width: 1px; + height: 22px; + background: var(--border-2); +} + +.ps-file-btns { + display: flex; + align-items: center; + gap: 6px; +} + +/* Contextual Tool Options Strip (Center Header) */ +.ps-tool-options-strip { + flex: 1; + display: flex; + align-items: center; + gap: 12px; + overflow-x: auto; + padding: 4px 0; + scrollbar-width: none; +} + +.ps-tool-options-strip::-webkit-scrollbar { + display: none; +} + +.ps-options-group { + display: flex; + align-items: center; + gap: 8px; + padding: 3px 10px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + white-space: nowrap; +} + +.ps-options-label { + font-size: 11px; + font-weight: 600; + color: var(--text-3); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.ps-header-right { + display: flex; + align-items: center; + gap: 10px; + flex-shrink: 0; +} + +.ps-counter-pill { + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; + color: var(--text-2); + padding: 5px 10px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid var(--border-1); + border-radius: var(--r-full); + display: flex; + align-items: center; + gap: 6px; +} + +.ps-counter-pill.has-files { + border-color: var(--primary-alpha2); + color: var(--primary); + background: var(--primary-alpha); + box-shadow: 0 0 12px var(--primary-alpha); +} + +/* ═══════════════════════════════════════════════════════════════════ + MAIN WORKSPACE LAYOUT (Tool Dock + Canvas Stage + Inspector) +═══════════════════════════════════════════════════════════════════ */ +.ps-main-body { + flex: 1; + display: flex; + position: relative; + overflow: hidden; + height: calc(100vh - 52px); +} + +/* ═══════════════════════════════════════════════════════════════════ + LEFT SLIM TOOL DOCK (Photoshop Iconic Palette) +═══════════════════════════════════════════════════════════════════ */ +.ps-tool-dock { + width: 58px; + height: 100%; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(28px) saturate(190%); + -webkit-backdrop-filter: blur(28px) saturate(190%); + border-right: 1px solid var(--border-1); + box-shadow: 6px 0 24px rgba(0, 0, 0, 0.65); + display: flex; + flex-direction: column; + align-items: center; + padding: 12px 0 16px; + gap: 5px; + position: relative; + z-index: 40; + flex-shrink: 0; +} + +.ps-tool-btn { + width: 42px; + height: 42px; + border-radius: var(--r-md); + border: 1px solid transparent; + background: transparent; + color: var(--text-3); + display: flex; + align-items: center; + justify-content: center; + cursor: pointer; + position: relative; + transition: all 0.18s cubic-bezier(0.16, 1, 0.3, 1); + font-size: 16px; + outline: none; +} + +.ps-tool-btn:hover { + background: rgba(255, 255, 255, 0.06); + color: var(--text-1); + border-color: var(--border-1); + transform: translateY(-1px); +} + +.ps-tool-btn.active { + background: linear-gradient(135deg, rgba(255, 108, 55, 0.28) 0%, rgba(255, 108, 55, 0.08) 100%); + color: #ffffff; + border-color: var(--primary-alpha2); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 0 16px var(--primary-alpha); +} + +.ps-tool-btn.active::before { + content: ''; + position: absolute; + left: -1px; + top: 10px; + bottom: 10px; + width: 3px; + border-radius: 0 var(--r-sm) var(--r-sm) 0; + background: var(--primary); + box-shadow: 0 0 8px var(--primary); +} + +.ps-tool-btn i { + transition: transform 0.18s ease; +} + +.ps-tool-btn:hover i { + transform: scale(1.15); +} + +.ps-tool-btn.active i { + color: var(--primary); + filter: drop-shadow(0 0 8px var(--primary-glow)); +} + +.ps-tool-shortcut { + position: absolute; + bottom: 3px; + right: 4px; + font-size: 8px; + font-family: var(--font-mono); + font-weight: 700; + color: var(--text-muted); + pointer-events: none; + opacity: 0.6; +} + +.ps-dock-divider { + width: 30px; + height: 1px; + background: var(--border-1); + margin: 6px 0; +} + +/* Tooltip on hover */ +[data-tooltip] { + position: relative; +} + +[data-tooltip]::after { + content: attr(data-tooltip); + position: absolute; + left: 68px; + top: 50%; + transform: translateY(-50%) scale(0.95); + background: rgba(14, 14, 20, 0.94); + backdrop-filter: blur(14px); + color: #ffffff; + border: 1px solid var(--border-2); + padding: 4px 9px; + border-radius: var(--r-sm); + font-size: 11px; + font-weight: 500; + white-space: nowrap; + pointer-events: none; + opacity: 0; + transition: opacity 0.15s ease, transform 0.15s ease; + z-index: 100; + box-shadow: 0 8px 24px rgba(0, 0, 0, 0.8); +} + +[data-tooltip]:hover::after { + opacity: 1; + transform: translateY(-50%) scale(1); +} + +/* ═══════════════════════════════════════════════════════════════════ + CENTER WORKSPACE & VIEWPORT (Photoshop Canvas Stage) +═══════════════════════════════════════════════════════════════════ */ +.ps-workspace { + flex: 1; + height: 100%; + display: flex; + flex-direction: column; + position: relative; + overflow: hidden; + background: radial-gradient(circle at center, #111116 0%, #050507 100%); +} + +.ps-viewport { + flex: 1; + position: relative; + overflow: hidden; + display: flex; + align-items: center; + justify-content: center; + background-image: + linear-gradient(45deg, #0e0e14 25%, transparent 25%), + linear-gradient(-45deg, #0e0e14 25%, transparent 25%), + linear-gradient(45deg, transparent 75%, #0e0e14 75%), + linear-gradient(-45deg, transparent 75%, #0e0e14 75%); + background-size: 24px 24px; + background-position: 0 0, 0 12px, 12px -12px, -12px 0px; +} + +/* Empty State Dropzone */ +.ps-dropzone-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + max-width: 580px; + width: 90%; + padding: 48px 36px; + background: var(--bg-smoke); + backdrop-filter: blur(28px) saturate(180%); + -webkit-backdrop-filter: blur(28px) saturate(180%); + border: 2px dashed var(--border-2); + border-radius: var(--r-xl); + box-shadow: var(--sh-liquid); + cursor: pointer; + transition: all 0.25s cubic-bezier(0.16, 1, 0.3, 1); + text-align: center; + position: relative; +} + +.ps-dropzone-empty:hover, .ps-dropzone-empty.dragover { + border-color: var(--primary); + background: rgba(255, 108, 55, 0.08); + box-shadow: var(--sh-liquid-hover); + transform: translateY(-2px); +} + +.ps-dropzone-icon { + width: 68px; + height: 68px; + border-radius: 50%; + background: var(--primary-alpha); + border: 1px solid var(--primary-alpha2); + display: flex; + align-items: center; + justify-content: center; + font-size: 30px; + color: var(--primary); + margin-bottom: 18px; + box-shadow: 0 0 28px var(--primary-glow); +} + +.ps-dropzone-empty h2 { + font-size: 18px; + font-weight: 700; + color: var(--text-1); +} + +.ps-dropzone-empty p { + font-size: 12.5px; + color: var(--text-3); + margin-top: 6px; +} + +.ps-dropzone-actions { + display: flex; + gap: 12px; + margin-top: 24px; +} + +/* Image Canvas Stage */ +.ps-stage-container { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + max-width: calc(100% - 48px); + max-height: calc(100% - 48px); + box-shadow: 0 16px 48px rgba(0, 0, 0, 0.85); + border-radius: var(--r-md); + overflow: visible; + transition: transform 0.1s ease-out; +} + +.ps-active-img { + max-width: 100%; + max-height: calc(100vh - 200px); + display: block; + object-fit: contain; + border-radius: var(--r-md); + border: 1px solid var(--border-2); + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.7); + user-select: none; + pointer-events: none; +} + +/* Zoom / Viewport HUD Controls */ +.ps-viewport-hud { + position: absolute; + bottom: 16px; + right: 18px; + display: flex; + align-items: center; + gap: 6px; + background: rgba(14, 14, 20, 0.88); + backdrop-filter: blur(16px); + border: 1px solid var(--border-2); + border-radius: var(--r-full); + padding: 4px 8px; + z-index: 30; + box-shadow: var(--sh-glass); +} + +.ps-hud-btn { + background: none; + border: none; + color: var(--text-2); + width: 26px; + height: 26px; + border-radius: 50%; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 11px; + transition: background 0.15s ease, color 0.15s ease; +} + +.ps-hud-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.ps-hud-val { + font-family: var(--font-mono); + font-size: 11px; + font-weight: 600; + color: var(--text-1); + min-width: 44px; + text-align: center; +} + +/* ═══════════════════════════════════════════════════════════════════ + VISUAL INTERACTIVE CROPPER OVERLAY (Photoshop Marquee Cropper) +═══════════════════════════════════════════════════════════════════ */ +.ps-crop-overlay { + position: absolute; + inset: 0; + pointer-events: auto; + z-index: 25; + user-select: none; + overflow: hidden; +} + +/* Darkened Scrims Outside the Active Crop Box */ +.crop-scrim { + position: absolute; + background: rgba(0, 0, 0, 0.65); + pointer-events: auto; + transition: background 0.15s ease; +} + +.crop-scrim-top { top: 0; left: 0; right: 0; } +.crop-scrim-bottom { bottom: 0; left: 0; right: 0; } +.crop-scrim-left { top: 0; bottom: 0; left: 0; } +.crop-scrim-right { top: 0; bottom: 0; right: 0; } + +/* The Crop Rectangle Box */ +.crop-box { + position: absolute; + border: 1.5px solid var(--accent-cyan); + box-shadow: + 0 0 0 1px rgba(0, 0, 0, 0.8), + 0 0 16px var(--accent-cyan-glow); + cursor: move; + pointer-events: auto; + z-index: 28; +} + +/* Rule of Thirds Grid Lines inside Crop Box */ +.crop-grid { + position: absolute; + inset: 0; + pointer-events: none; +} + +.crop-grid-h1, .crop-grid-h2 { + position: absolute; + left: 0; + right: 0; + height: 1px; + background: rgba(255, 255, 255, 0.35); + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); +} +.crop-grid-h1 { top: 33.333%; } +.crop-grid-h2 { top: 66.666%; } + +.crop-grid-v1, .crop-grid-v2 { + position: absolute; + top: 0; + bottom: 0; + width: 1px; + background: rgba(255, 255, 255, 0.35); + box-shadow: 0 0 2px rgba(0, 0, 0, 0.6); +} +.crop-grid-v1 { left: 33.333%; } +.crop-grid-v2 { left: 66.666%; } + +/* Live Dimension Tag Above Crop Box */ +.crop-dim-badge { + position: absolute; + top: -28px; + left: 50%; + transform: translateX(-50%); + background: rgba(10, 10, 16, 0.92); + border: 1px solid var(--accent-cyan); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.7); + padding: 3px 8px; + border-radius: var(--r-sm); + font-family: var(--font-mono); + font-size: 11px; + font-weight: 700; + color: var(--accent-cyan); + white-space: nowrap; + pointer-events: none; + z-index: 30; +} + +/* 8 Resizing Handles */ +.crop-handle { + position: absolute; + width: 10px; + height: 10px; + background: #ffffff; + border: 1.5px solid #000000; + box-shadow: 0 0 6px var(--accent-cyan); + border-radius: 2px; + z-index: 32; +} + +.crop-handle-nw { top: -5px; left: -5px; cursor: nwse-resize; } +.crop-handle-n { top: -5px; left: calc(50% - 5px); cursor: ns-resize; width: 14px; } +.crop-handle-ne { top: -5px; right: -5px; cursor: nesw-resize; } +.crop-handle-e { top: calc(50% - 5px); right: -5px; cursor: ew-resize; height: 14px; } +.crop-handle-se { bottom: -5px; right: -5px; cursor: nwse-resize; } +.crop-handle-s { bottom: -5px; left: calc(50% - 5px); cursor: ns-resize; width: 14px; } +.crop-handle-sw { bottom: -5px; left: -5px; cursor: nesw-resize; } +.crop-handle-w { top: calc(50% - 5px); left: -5px; cursor: ew-resize; height: 14px; } + +/* ═══════════════════════════════════════════════════════════════════ + MASK CANVAS OVERLAY & LIVE BRUSH CURSOR +═══════════════════════════════════════════════════════════════════ */ +.ps-mask-canvas { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + cursor: crosshair; + z-index: 26; + opacity: 0.35; + touch-action: none; +} + +#brush-cursor-ring { + position: fixed; + pointer-events: none; + border: 1.5px solid #ff3333; + border-radius: 50%; + transform: translate(-50%, -50%); + display: none; + z-index: 1000; + box-shadow: 0 0 8px rgba(255, 51, 51, 0.6); +} + +/* ═══════════════════════════════════════════════════════════════════ + BOTTOM FILMSTRIP / QUEUE TRAY (Multi-File Bar) +═══════════════════════════════════════════════════════════════════ */ +.ps-filmstrip { + height: 82px; + min-height: 82px; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(24px) saturate(190%); + -webkit-backdrop-filter: blur(24px) saturate(190%); + border-top: 1px solid var(--border-2); + display: flex; + align-items: center; + padding: 0 16px; + gap: 12px; + position: relative; + z-index: 35; + box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.5); +} + +.ps-filmstrip-left { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + border-right: 1px solid var(--border-1); + padding-right: 12px; +} + +.ps-filmstrip-scroll { + flex: 1; + display: flex; + align-items: center; + gap: 8px; + overflow-x: auto; + padding: 4px 0; + scrollbar-width: thin; + scrollbar-color: var(--border-2) transparent; +} + +.ps-filmstrip-scroll::-webkit-scrollbar { + height: 5px; +} +.ps-filmstrip-scroll::-webkit-scrollbar-thumb { + background: var(--border-2); + border-radius: var(--r-full); +} + +.ps-thumb-card { + height: 64px; + min-width: 140px; + max-width: 180px; + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px; + background: var(--bg-input); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + cursor: pointer; + position: relative; + transition: all 0.18s ease; + flex-shrink: 0; +} + +.ps-thumb-card:hover { + background: var(--bg-card-hover); + border-color: var(--border-2); + transform: translateY(-2px); +} + +.ps-thumb-card.active { + background: linear-gradient(135deg, rgba(255, 108, 55, 0.22) 0%, rgba(255, 108, 55, 0.06) 100%); + border-color: var(--primary); + box-shadow: 0 0 12px var(--primary-alpha); +} + +.ps-thumb-img { + width: 48px; + height: 48px; + border-radius: var(--r-sm); + object-fit: cover; + background: #000; + border: 1px solid var(--border-1); + flex-shrink: 0; +} + +.ps-thumb-meta { + display: flex; + flex-direction: column; + overflow: hidden; + gap: 2px; +} + +.ps-thumb-name { + font-size: 11px; + font-weight: 600; + color: var(--text-1); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.ps-thumb-size { + font-size: 10px; + font-family: var(--font-mono); + color: var(--text-3); +} + +.ps-thumb-close { + position: absolute; + top: 3px; + right: 4px; + width: 16px; + height: 16px; + border-radius: 50%; + background: rgba(0, 0, 0, 0.7); + border: 1px solid var(--border-1); + color: var(--text-3); + display: none; + align-items: center; + justify-content: center; + font-size: 9px; + cursor: pointer; +} + +.ps-thumb-card:hover .ps-thumb-close { + display: flex; +} + +.ps-thumb-close:hover { + background: #ef4444; + color: #fff; +} + +/* ═══════════════════════════════════════════════════════════════════ + RIGHT INSPECTOR PANEL (Photoshop Properties & Batch Hub) +═══════════════════════════════════════════════════════════════════ */ +.ps-inspector { + width: 320px; + height: 100%; + background: var(--bg-smoke-heavy); + backdrop-filter: blur(28px) saturate(190%); + -webkit-backdrop-filter: blur(28px) saturate(190%); + border-left: 1px solid var(--border-1); + box-shadow: -6px 0 24px rgba(0, 0, 0, 0.65); + display: flex; + flex-direction: column; + position: relative; + z-index: 40; + flex-shrink: 0; +} + +.ps-inspector-tabs { + display: flex; + border-bottom: 1px solid var(--border-1); + padding: 0 8px; + background: rgba(0, 0, 0, 0.2); +} + +.ps-inspector-tab { + flex: 1; + padding: 12px 6px; + text-align: center; + font-size: 11.5px; + font-weight: 600; + color: var(--text-3); + cursor: pointer; + border-bottom: 2px solid transparent; + transition: all 0.2s ease; + user-select: none; +} + +.ps-inspector-tab:hover { + color: var(--text-1); +} + +.ps-inspector-tab.active { + color: var(--primary); + border-bottom-color: var(--primary); +} + +.ps-inspector-content { + flex: 1; + overflow-y: auto; + padding: 18px 20px; + display: flex; + flex-direction: column; + gap: 16px; +} + +.ps-section-title { + font-size: 10.5px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.08em; + color: var(--text-muted); + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; +} + +.ps-action-footer { + padding: 16px 20px; + border-top: 1px solid var(--border-1); + background: rgba(0, 0, 0, 0.3); + display: flex; + flex-direction: column; + gap: 10px; +} + +/* ═══════════════════════════════════════════════════════════════════ + FORM CONTROLS & RANGE SLIDERS +═══════════════════════════════════════════════════════════════════ */ +.input-group { + display: flex; + flex-direction: column; + margin-bottom: 12px; +} + +.input-group label { + font-size: 11.5px; + font-weight: 600; + color: var(--text-2); + margin-bottom: 6px; + display: flex; + align-items: center; + justify-content: space-between; +} + +.label-val { + font-family: var(--font-mono); + font-size: 11px; + color: var(--primary); + font-weight: 700; +} + +input[type="text"], +input[type="number"], +input[type="color"], +select, +textarea { + width: 100%; + height: 36px; + padding: 0 12px; + background: var(--bg-input); + border: 1px solid var(--border-2); + border-radius: var(--r-md); + color: var(--text-1); + font-family: var(--font-main); + font-size: 12.5px; + outline: none; + transition: all 0.2s ease; + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.5); +} + +input[type="text"]:focus, +input[type="number"]:focus, +select:focus, +textarea:focus { + border-color: var(--border-focus); + background: var(--bg-input-focus); + box-shadow: 0 0 0 1px var(--primary-alpha2), 0 0 16px var(--primary-alpha); +} + +select { + cursor: pointer; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 24 24' fill='none' stroke='rgba(255,255,255,0.6)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3E%3Cpolyline points='6 9 12 15 18 9'%3E%3C/polyline%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 12px center; + padding-right: 32px; + appearance: none; + -webkit-appearance: none; +} + +select option { + background: #121218; + color: var(--text-1); +} + +/* Custom Range Sliders */ +input[type="range"] { + -webkit-appearance: none; + width: 100%; + height: 5px; + border-radius: var(--r-full); + background: rgba(255, 255, 255, 0.12); + outline: none; + cursor: pointer; + margin: 8px 0; +} + +input[type="range"]::-webkit-slider-thumb { + -webkit-appearance: none; + width: 16px; + height: 16px; + border-radius: 50%; + background: var(--primary); + border: 2px solid #ffffff; + box-shadow: 0 0 10px var(--primary-glow); + cursor: pointer; + transition: transform 0.15s ease; +} + +input[type="range"]::-webkit-slider-thumb:hover { + transform: scale(1.25); +} + +/* Segment Pill Buttons */ +.seg-pills-row { + display: flex; + gap: 6px; + flex-wrap: wrap; + margin-top: 4px; +} + +.seg-pill { + padding: 5px 10px; + background: var(--bg-input); + border: 1px solid var(--border-2); + border-radius: var(--r-md); + font-size: 11px; + font-weight: 600; + color: var(--text-2); + cursor: pointer; + transition: all 0.18s ease; + user-select: none; +} + +.seg-pill:hover { + background: rgba(255, 255, 255, 0.08); + color: var(--text-1); + border-color: var(--border-3); +} + +.seg-pill.active { + background: var(--primary-alpha); + border-color: var(--primary-alpha2); + color: var(--primary); + box-shadow: 0 0 12px var(--primary-alpha); +} + +/* Color Swatches */ +.color-swatches-row { + display: flex; + gap: 8px; + align-items: center; + margin-top: 6px; +} + +.color-swatch { + width: 24px; + height: 24px; + border-radius: 50%; + border: 2px solid rgba(255, 255, 255, 0.2); + cursor: pointer; + transition: transform 0.15s ease, border-color 0.15s ease; +} + +.color-swatch:hover { + transform: scale(1.2); + border-color: #ffffff; +} + +/* ═══════════════════════════════════════════════════════════════════ + BUTTONS +═══════════════════════════════════════════════════════════════════ */ +.btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + height: 38px; + padding: 0 16px; + background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%); + color: #ffffff; + font-family: var(--font-main); + font-size: 12.5px; + font-weight: 600; + border-radius: var(--r-md); + border: 1px solid rgba(255, 255, 255, 0.25); + cursor: pointer; + transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 -1px 0 rgba(0, 0, 0, 0.50) inset, + 0 8px 20px var(--primary-glow); + text-decoration: none; + user-select: none; + white-space: nowrap; +} + +.btn:hover { + transform: translateY(-2px); + box-shadow: + 0 1.5px 0 rgba(255, 255, 255, 0.60) inset, + 0 12px 28px var(--primary-glow); + filter: brightness(1.08); +} + +.btn:active { + transform: translateY(0); +} + +.btn-secondary { + background: var(--bg-card); + border: 1px solid var(--border-2); + color: var(--text-2); + box-shadow: var(--sh-glass); +} + +.btn-secondary:hover { + background: var(--bg-card-hover); + color: var(--text-1); + border-color: var(--border-3); + box-shadow: 0 6px 18px rgba(0, 0, 0, 0.45); +} + +.btn-cyan { + background: linear-gradient(135deg, var(--accent-cyan) 0%, #0072ff 100%); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.40) inset, + 0 8px 20px var(--accent-cyan-glow); + color: #000000; + font-weight: 700; +} + +.btn-cyan:hover { + box-shadow: + 0 1.5px 0 rgba(255, 255, 255, 0.60) inset, + 0 12px 28px var(--accent-cyan-glow); + filter: brightness(1.1); +} + +.btn-sm { + height: 30px; + padding: 0 10px; + font-size: 11.5px; +} + +.btn-icon-only { + width: 32px; + height: 32px; + padding: 0; + border-radius: var(--r-md); +} + +/* ═══════════════════════════════════════════════════════════════════ + BATCH PROGRESS MODAL & GLASS HUD +═══════════════════════════════════════════════════════════════════ */ +.ps-modal-backdrop { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.82); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + z-index: 2000; + display: flex; + align-items: center; + justify-content: center; +} + +.ps-modal-card { + width: 90%; + max-width: 540px; + background: var(--bg-smoke-heavy); + border: 1px solid var(--border-3); + border-radius: var(--r-xl); + padding: 28px 32px; + box-shadow: var(--sh-liquid-hover); + display: flex; + flex-direction: column; + gap: 18px; + position: relative; +} + +.ps-progress-header { + display: flex; + align-items: center; + justify-content: space-between; +} + +.ps-progress-header h3 { + font-size: 16px; + font-weight: 700; + color: var(--text-1); + display: flex; + align-items: center; + gap: 8px; +} + +.ps-progress-pct { + font-family: var(--font-mono); + font-size: 18px; + font-weight: 800; + color: var(--primary); +} + +.ps-progress-track { + width: 100%; + height: 8px; + background: rgba(255, 255, 255, 0.08); + border-radius: var(--r-full); + overflow: hidden; + position: relative; +} + +.ps-progress-fill { + height: 100%; + width: 0%; + background: linear-gradient(90deg, var(--primary) 0%, var(--accent-cyan) 100%); + border-radius: var(--r-full); + transition: width 0.2s ease; + box-shadow: 0 0 16px var(--primary-glow); +} + +.ps-progress-stats { + display: flex; + align-items: center; + justify-content: space-between; + font-family: var(--font-mono); + font-size: 11.5px; + color: var(--text-3); +} + +.ps-progress-speed { + color: var(--accent-cyan); + font-weight: 600; +} + +.ps-console-box { + max-height: 140px; + overflow-y: auto; + background: rgba(0, 0, 0, 0.6); + border: 1px solid var(--border-1); + border-radius: var(--r-md); + padding: 10px 14px; + font-family: var(--font-mono); + font-size: 11px; + color: var(--text-3); + display: flex; + flex-direction: column; + gap: 4px; +} + +.ps-console-line { + white-space: pre-wrap; + word-break: break-all; +} + +.ps-console-line.error { + color: #ef4444; +} + +.ps-console-line.success { + color: var(--accent-emerald); +} + +/* ═══════════════════════════════════════════════════════════════════ + TOAST NOTIFICATIONS +═══════════════════════════════════════════════════════════════════ */ +.toast-container { + position: fixed; + bottom: 24px; + right: 24px; + z-index: 9999; + display: flex; + flex-direction: column; + gap: 10px; + pointer-events: none; +} + +.toast { + pointer-events: auto; + padding: 12px 18px; + background: rgba(14, 14, 20, 0.95); + backdrop-filter: blur(20px); + -webkit-backdrop-filter: blur(20px); + border: 1px solid var(--border-2); + border-radius: var(--r-lg); + box-shadow: var(--sh-liquid); + display: flex; + align-items: center; + gap: 10px; + font-size: 12.5px; + font-weight: 500; + color: var(--text-1); + transform: translateY(20px); + opacity: 0; + animation: toastIn 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +@keyframes toastIn { + to { + transform: translateY(0); + opacity: 1; + } +} + +.toast.success { + border-color: rgba(16, 185, 129, 0.4); +} +.toast.success i { + color: var(--accent-emerald); +} + +.toast.error { + border-color: rgba(239, 68, 68, 0.4); +} +.toast.error i { + color: #ef4444; }