fixed implementation of UGC content uploader

This commit is contained in:
JakeBreath
2026-08-03 18:57:39 -05:00
parent 39e31d3980
commit 473b3c811b
40 changed files with 4137 additions and 87 deletions
+153
View File
@@ -0,0 +1,153 @@
// J621-style multi-upload for the gallery "add media" page. Files are
// uploaded one at a time to /api/uploads/ (kind=media) and previewed; on
// submit the pending uploads are moved into the project's gallery.
(function () {
const zone = document.querySelector('.upload-zone[data-upload="media"]');
if (!zone) return;
const csrf = getCookie('csrftoken');
const csrfHeader = csrf ? { 'X-CSRFToken': csrf } : {};
const preview = document.getElementById('media-preview');
const batch = document.getElementById('media-batch');
const input = document.getElementById('media-input');
const drop = zone.querySelector('.drop-zone');
const pending = JSON.parse(
(document.getElementById('packs-pending-uploads') || { textContent: '[]' }).textContent
);
pending.forEach(renderCard);
function renderCard(upload) {
const card = document.createElement('div');
card.className = 'file-preview-card';
card.dataset.uuid = upload.uuid;
if ((upload.content_type || '').startsWith('image/')) {
const img = document.createElement('img');
img.src = upload.url;
img.alt = upload.filename;
card.appendChild(img);
} else if ((upload.content_type || '').startsWith('video/')) {
const video = document.createElement('video');
video.src = upload.url;
video.muted = true;
video.autoplay = true;
video.loop = true;
card.appendChild(video);
} else {
const icon = document.createElement('div');
icon.className = 'file-preview-icon';
icon.innerHTML = '<i class="fas fa-file"></i>';
card.appendChild(icon);
}
const name = document.createElement('span');
name.className = 'file-preview-name';
name.textContent = upload.filename;
card.appendChild(name);
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'file-preview-remove';
remove.innerHTML = '<i class="fas fa-times"></i>';
remove.addEventListener('click', () => {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/uploads/' + upload.uuid + '/delete/');
for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
xhr.onload = () => { if (card.parentNode) card.parentNode.removeChild(card); };
xhr.onerror = () => alert('Network error.');
xhr.send();
});
card.appendChild(remove);
preview.appendChild(card);
}
function uploadFile(file) {
const fd = new FormData();
fd.append('file', file);
fd.append('kind', 'media');
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/uploads/');
for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
xhr.onload = function () {
if (xhr.status !== 200) {
try {
alert(JSON.parse(xhr.responseText).error || 'Upload failed.');
} catch (e) {
alert('Upload failed.');
}
} else {
renderCard(JSON.parse(xhr.responseText));
}
batchDone++;
updateBatch();
};
xhr.onerror = function () {
alert('Network error during upload.');
batchDone++;
updateBatch();
};
xhr.send(fd);
}
let batchTotal = 0;
let batchDone = 0;
function updateBatch() {
if (batchTotal === 0) { batch.hidden = true; return; }
batch.hidden = false;
document.getElementById('media-batch-status').textContent =
'Uploading ' + batchDone + ' of ' + batchTotal + ' files';
if (batchDone >= batchTotal && batchTotal > 0) {
setTimeout(() => { batch.hidden = true; batchTotal = 0; batchDone = 0; }, 2500);
}
}
function handleFiles(files) {
batchTotal += files.length;
updateBatch();
files.forEach((file) => uploadFile(file));
}
drop.addEventListener('click', () => input.click());
drop.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); input.click(); }
});
['dragenter', 'dragover'].forEach((evt) => drop.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
drop.classList.add('dragover');
}));
['dragleave', 'drop'].forEach((evt) => drop.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
drop.classList.remove('dragover');
}));
drop.addEventListener('drop', (e) => {
if (e.dataTransfer && e.dataTransfer.files.length) {
handleFiles(Array.from(e.dataTransfer.files));
}
});
input.addEventListener('change', () => {
handleFiles(Array.from(input.files));
input.value = '';
});
['dragover', 'drop'].forEach((evt) => window.addEventListener(evt, (e) => e.preventDefault()));
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
})();
+266
View File
@@ -0,0 +1,266 @@
// J621-style upload + real-time autosave for the "create project" form.
// Each selected file is uploaded individually (XHR + FormData) to /api/uploads/
// and stored under media/uploads/user_<id>/. Typed fields autosave to the
// ProjectDraft via /api/draft/ (debounced, no explicit Save Draft button).
(function () {
const form = document.getElementById('project-form');
if (!form) return;
const csrf = getCookie('csrftoken');
const csrfHeader = csrf ? { 'X-CSRFToken': csrf } : {};
const savedUploads = JSON.parse(
(document.getElementById('packs-draft-uploads') || { textContent: '[]' }).textContent
);
// ----- Multi-upload (per-file XHR, thumbnails) -----
const zones = {};
document.querySelectorAll('.upload-zone').forEach((zone) => {
const kind = zone.dataset.upload;
zones[kind] = {
zone,
drop: zone.querySelector('.drop-zone'),
input: zone.querySelector('input[type=file]'),
preview: zone.querySelector('.upload-preview, #media-preview'),
};
if (kind === 'media') zones[kind].batch = document.getElementById('media-batch');
});
// Re-render the pending uploads that survived from a previous session.
savedUploads.forEach((u) => {
const z = zones[u.kind];
if (z && !z.current) renderUpload(u, z);
});
function renderUpload(upload, z) {
if (z.kind === 'thumbnail' || z.kind === 'version') {
z.preview.innerHTML = '';
z.preview.appendChild(previewCard(upload));
z.current = upload;
} else {
z.preview.appendChild(previewCard(upload));
}
}
function previewCard(upload) {
const card = document.createElement('div');
card.className = 'file-preview-card';
card.dataset.uuid = upload.uuid;
if ((upload.content_type || '').startsWith('image/')) {
const img = document.createElement('img');
img.src = upload.url;
img.alt = upload.filename;
card.appendChild(img);
} else if ((upload.content_type || '').startsWith('video/')) {
const video = document.createElement('video');
video.src = upload.url;
video.muted = true;
video.autoplay = true;
video.loop = true;
card.appendChild(video);
} else {
const icon = document.createElement('div');
icon.className = 'file-preview-icon';
icon.innerHTML = '<i class="fas fa-file-archive"></i>';
card.appendChild(icon);
}
const name = document.createElement('span');
name.className = 'file-preview-name';
name.textContent = upload.filename;
card.appendChild(name);
const remove = document.createElement('button');
remove.type = 'button';
remove.className = 'file-preview-remove';
remove.innerHTML = '<i class="fas fa-times"></i>';
remove.addEventListener('click', () => deleteUpload(upload.uuid, card));
card.appendChild(remove);
return card;
}
function uploadFile(file, kind, z) {
const fd = new FormData();
fd.append('file', file);
fd.append('kind', kind);
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/uploads/');
for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
xhr.onload = function () {
z.busy = false;
if (xhr.status !== 200) {
try {
alert(JSON.parse(xhr.responseText).error || 'Upload failed.');
} catch (e) {
alert('Upload failed.');
}
return;
}
const data = JSON.parse(xhr.responseText);
renderUpload(data, z);
};
xhr.onerror = function () {
z.busy = false;
alert('Network error during upload.');
};
xhr.send(fd);
}
function deleteUpload(uuid, card) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/uploads/' + uuid + '/delete/');
for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
xhr.onload = function () {
if (card && card.parentNode) card.parentNode.removeChild(card);
};
xhr.onerror = function () {
alert('Network error.');
};
xhr.send();
}
Object.keys(zones).forEach((kind) => {
const z = zones[kind];
z.drop.addEventListener('click', () => z.input.click());
z.drop.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); z.input.click(); }
});
['dragenter', 'dragover'].forEach((evt) => z.drop.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
z.drop.classList.add('dragover');
}));
['dragleave', 'drop'].forEach((evt) => z.drop.addEventListener(evt, (e) => {
e.preventDefault();
e.stopPropagation();
z.drop.classList.remove('dragover');
}));
z.drop.addEventListener('drop', (e) => {
if (e.dataTransfer && e.dataTransfer.files.length) {
handleFiles(Array.from(e.dataTransfer.files), kind, z);
}
});
z.input.addEventListener('change', () => {
handleFiles(Array.from(z.input.files), kind, z);
z.input.value = '';
});
});
// Prevent the browser opening files dropped outside a zone.
['dragover', 'drop'].forEach((evt) => window.addEventListener(evt, (e) => e.preventDefault()));
let batchTotal = 0;
let batchDone = 0;
function handleFiles(files, kind, z) {
// Thumbnail/version are single slots: take one file, replace any
// current upload, and ignore further drops while one is in flight.
if (kind === 'thumbnail' || kind === 'version') {
if (z.busy) return;
const file = files[0];
if (z.current) deleteUpload(z.current.uuid, null);
z.busy = true;
uploadFile(file, kind, z);
return;
}
batchTotal += files.length;
updateBatch();
files.forEach((file) => uploadFile(file, kind, z));
}
function updateBatch() {
const z = zones.media;
if (!z || !z.batch) return;
if (batchTotal === 0) { z.batch.hidden = true; return; }
z.batch.hidden = false;
document.getElementById('media-batch-status').textContent =
'Uploading ' + batchDone + ' of ' + batchTotal + ' files';
if (batchDone >= batchTotal && batchTotal > 0) {
setTimeout(() => {
z.batch.hidden = true;
batchTotal = 0;
batchDone = 0;
}, 2500);
}
}
// ----- Real-time draft autosave -----
const autosaveStatus = document.getElementById('autosave-status');
const FIELDS = ['title', 'summary', 'category', 'description', 'caption', 'version_name', 'changelog'];
function setStatus(text, state) {
autosaveStatus.innerHTML = text;
autosaveStatus.className = 'autosave-status ' + (state || '');
}
let saveTimer = null;
let lastSavedAt = null;
function scheduleSave() {
setStatus('<i class="fas fa-circle-notch fa-spin"></i> Saving…', 'saving');
clearTimeout(saveTimer);
saveTimer = setTimeout(saveDraft, 600);
}
function saveDraft() {
const data = {};
FIELDS.forEach((name) => {
const el = document.getElementById('id_' + name);
if (el) data[name] = el.value;
});
const tags = document.getElementById('id_tags');
if (tags) data.tags = tags.value;
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/draft/');
xhr.setRequestHeader('Content-Type', 'application/json');
for (const k in csrfHeader) xhr.setRequestHeader(k, csrfHeader[k]);
xhr.onload = function () {
if (xhr.status === 200) {
const r = JSON.parse(xhr.responseText);
lastSavedAt = r.updated_at;
setStatus('<i class="fas fa-check"></i> Saved just now', 'saved');
} else {
setStatus('<i class="fas fa-exclamation-triangle"></i> Save failed', 'error');
}
};
xhr.onerror = function () {
setStatus('<i class="fas fa-exclamation-triangle"></i> Save failed', 'error');
};
xhr.send(JSON.stringify({ data }));
}
FIELDS.forEach((name) => {
const el = document.getElementById('id_' + name);
if (el) {
el.addEventListener('input', scheduleSave);
if (el.tagName === 'SELECT') el.addEventListener('change', scheduleSave);
}
});
document.addEventListener('tags-changed', scheduleSave);
// Autosave is always live; indicate it once the page settles.
setStatus('<i class="fas fa-cloud-upload-alt"></i> Autosave on', 'idle');
setTimeout(() => setStatus('<i class="fas fa-check"></i> Saved just now', 'saved'), 2000);
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
})();
+91
View File
@@ -0,0 +1,91 @@
// Tag editor shared between create/edit project pages.
// Autocompletes against /api/tags/autocomplete/ and lets users create new
// tags (unprefixed → general). Populates the hidden `tags` input as
// "category:name category:name …" on submit.
(function () {
const input = document.getElementById('tag-input');
if (!input) return;
const suggestions = document.getElementById('tag-suggestions');
const chips = document.getElementById('tag-chips');
const hidden = document.getElementById('id_tags');
const tags = new Map(); // "category:name" -> {category, name, color}
function render() {
chips.innerHTML = '';
tags.forEach((tag) => {
const chip = document.createElement('span');
chip.className = 'tag-chip';
chip.style.borderColor = tag.color;
chip.style.color = tag.color;
chip.textContent = tag.name;
const x = document.createElement('button');
x.type = 'button';
x.className = 'tag-chip-remove';
x.textContent = '×';
x.addEventListener('click', () => { tags.delete(tag.category + ':' + tag.name); render(); });
chip.appendChild(x);
chips.appendChild(chip);
});
hidden.value = Array.from(tags.values()).map(t => t.category + ':' + t.name).join(' ');
document.dispatchEvent(new CustomEvent('tags-changed', { detail: { tags: hidden.value } }));
}
function addTag(category, name, color) {
const canonical = category.toLowerCase();
tags.set(canonical + ':' + name, { category: canonical, name, color: color || '#666666' });
render();
}
(hidden.value || '').split(' ').filter(Boolean).forEach(raw => {
const [category, ...rest] = raw.split(':');
addTag(category, rest.join(':'));
});
let timer = null;
input.addEventListener('input', () => {
clearTimeout(timer);
const q = input.value.trim();
if (!q) { suggestions.hidden = true; return; }
timer = setTimeout(async () => {
try {
const resp = await fetch(
"/api/tags/autocomplete/?q=" + encodeURIComponent(q),
{ headers: { 'Accept': 'application/json' } }
);
const results = await resp.json();
suggestions.innerHTML = '';
for (const t of results.slice(0, 8)) {
const item = document.createElement('button');
item.type = 'button';
item.className = 'tag-suggestion';
item.innerHTML = '<span class="tag-dot" style="background:' + t.color + ';"></span> ' +
'<strong>' + t.name + '</strong> <small>(' + t.category_name + ')</small>';
item.addEventListener('click', () => { addTag(t.category, t.name, t.color); input.value = ''; suggestions.hidden = true; });
suggestions.appendChild(item);
}
suggestions.hidden = results.length === 0;
} catch (e) {
suggestions.hidden = true;
}
}, 200);
});
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const q = input.value.trim();
if (!q) return;
const [category, ...rest] = q.includes(':') ? q.split(':') : ['general', q];
const name = rest.join(':').trim();
if (name) addTag(category, name);
input.value = '';
suggestions.hidden = true;
}
if (e.key === 'Escape') suggestions.hidden = true;
});
document.addEventListener('click', (e) => {
if (!e.target.closest('.tag-editor')) suggestions.hidden = true;
});
})();