/*
* Gallery bulk uploader.
*
* Per file, one request:
* 1. draw a small JPEG thumbnail on a canvas (browser-side)
* 2. POST the original + thumbnail to admin/api.php as multipart/form-data
* 3. the webhost streams both to S3 and registers the image
*
* One file per request keeps each PHP process small, so the size of the whole
* gallery upload never matters — only the largest single image. The browser
* never sees an S3 URL or credential for writing.
*/
(function () {
'use strict';
var zone = document.getElementById('dropzone');
if (!zone) return;
var input = document.getElementById('file-input');
var list = document.getElementById('upload-list');
var countEl = document.getElementById('img-count');
var api = zone.dataset.api;
var slug = zone.dataset.slug;
var csrf = zone.dataset.csrf;
// Guest upload links pass a per-gallery key; the admin edit page sets none.
var uploadKey = zone.dataset.key || '';
var thumbSize = parseInt(zone.dataset.thumbSize, 10) || 600;
var thumbQuality = parseFloat(zone.dataset.thumbQuality) || 0.8;
var queue = [];
var busy = false;
zone.addEventListener('click', function () { input.click(); });
input.addEventListener('change', function () { enqueue(input.files); input.value = ''; });
['dragenter', 'dragover'].forEach(function (ev) {
zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.add('drag'); });
});
['dragleave', 'drop'].forEach(function (ev) {
zone.addEventListener(ev, function (e) { e.preventDefault(); zone.classList.remove('drag'); });
});
zone.addEventListener('drop', function (e) { enqueue(e.dataTransfer.files); });
window.addEventListener('beforeunload', function (e) {
if (busy || queue.length) { e.preventDefault(); e.returnValue = ''; }
});
function enqueue(files) {
Array.prototype.forEach.call(files, function (file) {
var row = document.createElement('div');
row.className = 'upload-item';
row.innerHTML = 'queued';
row.querySelector('.name').textContent = file.name;
list.appendChild(row);
queue.push({ file: file, row: row });
});
pump();
}
function pump() {
if (busy || !queue.length) return;
busy = true;
var job = queue.shift();
uploadOne(job.file, job.row)
.then(function () { setState(job.row, 'done', 'done'); bumpCount(); })
.catch(function (err) {
setState(job.row, 'failed', 'error');
job.row.title = String(err);
var retry = document.createElement('a');
retry.href = '#';
retry.textContent = ' retry';
retry.addEventListener('click', function (e) {
e.preventDefault();
retry.remove();
setState(job.row, 'queued', '');
queue.push(job);
pump();
});
job.row.appendChild(retry);
})
.finally(function () { busy = false; pump(); });
}
function setState(row, text, cls) {
var el = row.querySelector('.state');
el.textContent = text;
el.className = 'state ' + (cls || '');
}
function bumpCount() {
if (countEl) countEl.textContent = String(parseInt(countEl.textContent, 10) + 1);
}
/* POST multipart to the webhost with upload progress (fetch has none → XHR). */
function sendForm(form, onProgress) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('POST', api);
xhr.setRequestHeader('X-CSRF-Token', csrf);
// Let the browser set Content-Type (with the multipart boundary).
xhr.upload.addEventListener('progress', function (e) {
if (e.lengthComputable && onProgress) onProgress(e.loaded / e.total);
});
xhr.addEventListener('load', function () {
var data = {};
try { data = JSON.parse(xhr.responseText); } catch (err) {}
if (xhr.status >= 200 && xhr.status < 300 && data.ok) resolve(data);
else reject(new Error((data && data.error) || ('Upload failed (' + xhr.status + ')')));
});
xhr.addEventListener('error', function () { reject(new Error('Network error during upload')); });
xhr.send(form);
});
}
/* Thumbnail as JPEG blob; null when the browser cannot decode the file
(e.g. RAW) — the original still uploads untouched. */
function makeThumb(file) {
var decode = window.createImageBitmap
? createImageBitmap(file, { imageOrientation: 'from-image' })
: new Promise(function (resolve, reject) {
var img = new Image();
img.onload = function () { resolve(img); };
img.onerror = reject;
img.src = URL.createObjectURL(file);
});
return decode.then(function (src) {
var w = src.width, h = src.height;
var scale = Math.min(1, thumbSize / Math.max(w, h));
var canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round(w * scale));
canvas.height = Math.max(1, Math.round(h * scale));
canvas.getContext('2d').drawImage(src, 0, 0, canvas.width, canvas.height);
if (src.close) src.close();
return new Promise(function (resolve) {
canvas.toBlob(function (blob) { resolve(blob); }, 'image/jpeg', thumbQuality);
});
}).catch(function () { return null; });
}
function uploadOne(file, row) {
var bar = row.querySelector('.bar i');
setState(row, 'thumbnail');
return makeThumb(file).then(function (thumbBlob) {
setState(row, 'uploading');
var form = new FormData();
form.append('slug', slug);
if (uploadKey) form.append('key', uploadKey);
form.append('original', file, file.name);
if (thumbBlob) form.append('thumb', thumbBlob, 'thumb.jpg');
return sendForm(form, function (f) {
bar.style.width = Math.round(f * 100) + '%';
});
});
}
})();