Files

425 lines
16 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
(function () {
const $ = (id) => document.getElementById(id);
const el = (tag, cls, text) => {
const e = document.createElement(tag);
if (cls) e.className = cls;
if (text != null) e.textContent = text;
return e;
};
const state = { cfg: null, me: null, items: [], counts: {}, total: 0, q: '', kat: null, loaded: false, pending: [], current: null };
// ---------- hjelpere
const fmtDate = (iso) => (iso ? new Date(iso).toLocaleDateString('nb-NO', { day: 'numeric', month: 'short', year: 'numeric' }) : '');
const fmtSize = (b) => (b > 1048576 ? (b / 1048576).toFixed(1).replace('.', ',') + ' MB' : Math.max(1, Math.round(b / 1024)) + ' kB');
const mediaUrl = (id) => '/media/' + encodeURIComponent(id);
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.hidden = false;
clearTimeout(toast._t);
toast._t = setTimeout(() => (t.hidden = true), 2800);
}
function mediaSummary(media) {
const c = { image: 0, video: 0, audio: 0 };
(media || []).forEach((m) => { if (c[m.kind] != null) c[m.kind]++; });
const p = [];
if (c.image) p.push(c.image + (c.image === 1 ? ' bilde' : ' bilder'));
if (c.video) p.push(c.video + (c.video === 1 ? ' video' : ' videoer'));
if (c.audio) p.push(c.audio + (c.audio === 1 ? ' lydfil' : ' lydfiler'));
return p.join(' · ');
}
async function api(url, opts) {
const r = await fetch(url, Object.assign({ credentials: 'same-origin' }, opts));
if (r.status === 401) { showLogin(); throw new Error('401'); }
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.error || 'Noe gikk galt. Prøv igjen.');
return body;
}
// ---------- visninger
function show(view) {
['view-loading', 'view-login', 'view-main'].forEach((v) => ($(v).hidden = v !== view));
$('band-actions').hidden = view !== 'view-main';
}
function showLogin() {
const first = $('view-login').hidden;
show('view-login');
if (first) $('l-user').focus();
}
async function login(e) {
e.preventDefault();
const err = $('login-error');
const btn = $('btn-login');
const username = $('l-user').value.trim();
const password = $('l-pass').value;
if (!username || !password) { err.textContent = 'Skriv inn brukernavn og passord.'; return; }
err.textContent = '';
btn.disabled = true;
btn.textContent = 'Logger inn …';
try {
const r = await fetch('/auth/login', {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json', 'X-Requested-With': 'museumsblikk' },
body: JSON.stringify({ username, password }),
});
const body = await r.json().catch(() => ({}));
if (!r.ok) throw new Error(body.error || 'Innloggingen feilet. Prøv igjen.');
$('l-pass').value = '';
await enter();
} catch (ex) {
err.textContent = ex instanceof TypeError ? 'Får ikke kontakt med serveren. Sjekk nettverket og prøv igjen.' : ex.message;
$('l-pass').value = '';
$('l-pass').focus();
} finally {
btn.disabled = false;
btn.textContent = 'Logg inn';
}
}
// ---------- data
let ctrl = null;
async function load() {
if (ctrl) ctrl.abort();
ctrl = new AbortController();
const p = new URLSearchParams();
if (state.q.trim()) p.set('q', state.q.trim());
if (state.kat) p.set('kategori', state.kat);
try {
const d = await api('/api/innspill?' + p.toString(), { signal: ctrl.signal });
state.items = d.items;
state.counts = d.counts;
state.total = d.total;
state.loaded = true;
$('sync').textContent = '';
render();
} catch (e) {
if (e.name === 'AbortError' || e.message === '401') return;
$('sync').textContent = e.message;
}
}
// ---------- rendering
function renderChips() {
const box = $('chips');
box.textContent = '';
const sum = Object.values(state.counts).reduce((a, b) => a + b, 0);
const mk = (label, val, n) => {
const b = el('button', 'chip');
b.type = 'button';
b.setAttribute('aria-pressed', String(state.kat === val));
b.append(el('span', null, label), el('span', 'n', String(n)));
b.onclick = () => {
state.kat = state.kat === val ? null : val;
load();
};
box.append(b);
};
mk('Alle', null, sum);
state.cfg.kategorier.forEach((k) => mk(k, k, state.counts[k] || 0));
}
function renderGrid() {
const grid = $('grid');
grid.textContent = '';
const count = $('count');
count.textContent = '';
if (!state.loaded) {
grid.append(el('div', 'empty', 'Henter innspill …'));
return;
}
const n = state.items.length;
count.append(el('strong', null, String(n)), document.createTextNode(' innspill'));
if (n !== state.total) count.append(document.createTextNode(' av ' + state.total));
if (!state.total) {
const e = el('div', 'empty');
e.append(el('h2', null, 'Ingen innspill ennå'), el('p', null, 'Her vises det kollegaer har sett på andre museer: montere, lyssetting, tekster, scenografi og mer. Hvert innspill kan ha bilder, video eller lyd.'));
const b = el('button', 'btn btn-primary', 'Legg inn det første innspillet');
b.type = 'button';
b.onclick = openForm;
e.append(b);
grid.append(e);
return;
}
if (!n) {
const e = el('div', 'empty');
e.append(el('h2', null, 'Ingen treff'), el('p', null, 'Prøv et annet søkeord eller en annen kategori.'));
const b = el('button', 'btn btn-ghost', 'Nullstill søk');
b.type = 'button';
b.onclick = () => { state.q = ''; state.kat = null; $('q').value = ''; load(); };
e.append(b);
grid.append(e);
return;
}
state.items.forEach((it) => {
const card = el('button', 'card');
card.type = 'button';
card.setAttribute('aria-label', it.museum + ', ' + it.kategori);
const th = el('div', 'thumb');
const media = it.media || [];
const img = media.find((m) => m.kind === 'image');
const vid = media.find((m) => m.kind === 'video');
if (img) {
const i = el('img');
i.loading = 'lazy';
i.alt = '';
i.src = mediaUrl(img.id);
i.onerror = () => { i.remove(); th.append(el('span', 'ph', it.kategori)); };
th.append(i);
} else if (vid) {
const v = el('video');
v.muted = true;
v.preload = 'metadata';
v.src = mediaUrl(vid.id) + '#t=0.5';
th.append(v);
} else {
th.append(el('span', 'ph', it.kategori));
}
if (media.length > 1 || (!img && media.length)) th.append(el('span', 'badge', mediaSummary(media)));
card.append(th);
const body = el('div', 'card-body');
body.append(el('span', 'tag', it.kategori), el('h3', null, it.museum), el('p', 'excerpt', it.tekst));
const meta = el('div', 'meta');
meta.append(el('span', null, it.navn), el('span', null, fmtDate(it.createdAt)));
body.append(meta);
card.append(body);
card.onclick = () => openDetail(it);
grid.append(card);
});
}
function render() {
renderChips();
renderGrid();
}
// ---------- detaljvisning
function openDetail(it) {
state.current = it;
$('d-kat').textContent = it.kategori;
$('d-title').textContent = it.museum;
const meta = $('d-meta');
meta.textContent = '';
const a = el('span');
a.append('Innmeldt av ', el('b', null, it.navn));
meta.append(a, el('span', null, fmtDate(it.createdAt)));
if (it.media.length) meta.append(el('span', null, mediaSummary(it.media)));
$('d-text').textContent = it.tekst;
const box = $('d-media');
box.textContent = '';
it.media.forEach((m) => {
let n;
if (m.kind === 'image') { n = el('img'); n.alt = m.name || ''; n.loading = 'lazy'; }
else if (m.kind === 'video') { n = el('video'); n.controls = true; n.preload = 'metadata'; n.playsInline = true; }
else { n = el('audio'); n.controls = true; n.preload = 'metadata'; }
n.onerror = () => n.replaceWith(el('div', 'missing', 'Filen «' + (m.name || 'uten navn') + '» kan ikke vises i nettleseren din.'));
n.src = mediaUrl(m.id);
box.append(n);
});
const act = $('d-actions');
act.textContent = '';
if (it.canDelete) {
const del = el('button', 'btn btn-danger', 'Slett innspill');
del.type = 'button';
let armed = false;
del.onclick = async () => {
if (!armed) {
armed = true;
del.textContent = 'Klikk igjen for å slette';
setTimeout(() => { armed = false; del.textContent = 'Slett innspill'; }, 4000);
return;
}
del.disabled = true;
try {
await api('/api/innspill/' + encodeURIComponent(it.id), { method: 'DELETE', headers: { 'X-Requested-With': 'museumsblikk' } });
$('dlg-detail').close();
toast('Innspillet er slettet');
load();
} catch (e) {
del.disabled = false;
del.textContent = e.message;
}
};
act.append(del);
}
$('dlg-detail').showModal();
}
// ---------- skjema
function openForm() {
$('formerr').textContent = '';
const dl = $('museer');
dl.textContent = '';
[...new Set(state.items.map((i) => i.museum))].sort((a, b) => a.localeCompare(b, 'nb')).forEach((m) => {
const o = el('option');
o.value = m;
dl.append(o);
});
$('dlg-form').showModal();
}
function fileError(f) {
const t = (f.type || '').toLowerCase();
const ext = (f.name.split('.').pop() || '').toLowerCase();
if (t === 'image/heic' || t === 'image/heif' || ext === 'heic' || ext === 'heif') {
return 'HEIC støttes ikke. Velg JPG, eller sett iPhone-kameraet til «Mest kompatibel».';
}
const ok = state.cfg.accept.includes(t) || ((!t || t === 'application/octet-stream') && state.cfg.acceptExt.includes(ext));
if (!ok) return 'Filtypen støttes ikke.';
if (f.size > state.cfg.maxUploadMb * 1048576) return 'For stor (maks ' + state.cfg.maxUploadMb + ' MB).';
return null;
}
function addFiles(list) {
for (const f of list) state.pending.push({ file: f, error: fileError(f) });
renderFiles();
}
function renderFiles() {
const ul = $('filelist');
ul.textContent = '';
state.pending.forEach((p, i) => {
const li = el('li');
if (!p.error && p.file.type.startsWith('image/')) {
const im = el('img');
im.alt = '';
im.src = URL.createObjectURL(p.file);
im.onload = () => URL.revokeObjectURL(im.src);
li.append(im);
}
li.append(el('span', 'fn', p.file.name), el('span', 'fs', fmtSize(p.file.size)));
if (p.error) li.append(el('span', 'st err', p.error));
const rm = el('button', 'x', '×');
rm.type = 'button';
rm.setAttribute('aria-label', 'Fjern ' + p.file.name);
rm.onclick = () => { state.pending.splice(i, 1); renderFiles(); };
li.append(rm);
ul.append(li);
});
}
function submit(e) {
e.preventDefault();
const navn = $('f-navn').value.trim();
const museum = $('f-museum').value.trim();
const tekst = $('f-tekst').value.trim();
const missing = [];
if (!navn) missing.push('navn');
if (!museum) missing.push('museum');
if (!tekst) missing.push('hvorfor det var inspirerende');
if (missing.length) { $('formerr').textContent = 'Fyll inn ' + missing.join(', ') + '.'; return; }
if (state.pending.some((p) => p.error)) { $('formerr').textContent = 'Fjern filene som er merket med feil først.'; return; }
if (state.pending.length > state.cfg.maxFiles) { $('formerr').textContent = 'Maks ' + state.cfg.maxFiles + ' filer per innspill.'; return; }
const fd = new FormData();
fd.append('navn', navn);
fd.append('museum', museum);
fd.append('kategori', $('f-kat').value);
fd.append('tekst', tekst);
state.pending.forEach((p) => fd.append('filer', p.file, p.file.name));
const btn = $('btn-submit');
const prog = $('progress');
btn.disabled = true;
btn.textContent = state.pending.length ? 'Laster opp …' : 'Lagrer …';
$('formerr').textContent = '';
prog.value = 0;
prog.hidden = !state.pending.length;
const xhr = new XMLHttpRequest();
xhr.open('POST', '/api/innspill');
xhr.setRequestHeader('X-Requested-With', 'museumsblikk');
xhr.upload.onprogress = (ev) => {
if (!ev.lengthComputable) return;
prog.value = Math.round((ev.loaded / ev.total) * 100);
if (ev.loaded === ev.total) btn.textContent = 'Lagrer …';
};
const done = () => { btn.disabled = false; btn.textContent = 'Lagre innspill'; prog.hidden = true; };
xhr.onload = () => {
done();
if (xhr.status === 401) { $('dlg-form').close(); showLogin(); return; }
let body = {};
try { body = JSON.parse(xhr.responseText); } catch (_) { /* ikke JSON */ }
if (xhr.status === 413) { $('formerr').textContent = 'Filene er for store for serveren.'; return; }
if (xhr.status < 200 || xhr.status >= 300) { $('formerr').textContent = body.error || 'Kunne ikke lagre innspillet. Prøv igjen.'; return; }
state.pending = [];
renderFiles();
$('f-museum').value = '';
$('f-tekst').value = '';
$('f-kat').value = 'Uspesifisert';
$('dlg-form').close();
toast('Innspillet er lagret');
load();
};
xhr.onerror = () => { done(); $('formerr').textContent = 'Mistet kontakten med serveren. Sjekk nettverket og prøv igjen.'; };
xhr.send(fd);
}
// ---------- oppkobling
function wire() {
const sel = $('f-kat');
state.cfg.kategorier.forEach((k) => { const o = el('option', null, k); o.value = k; sel.append(o); });
sel.value = 'Uspesifisert';
$('drop-hint').textContent = 'Bilder (JPG, PNG, WebP, GIF) · video (MP4, MOV, WebM) · lyd (MP3, M4A, WAV, OGG) · maks ' + state.cfg.maxUploadMb + ' MB per fil';
const finput = $('f-files');
finput.accept = state.cfg.accept.join(',') + ',' + state.cfg.acceptExt.map((x) => '.' + x).join(',');
$('login-form').onsubmit = login;
$('btn-new').onclick = openForm;
$('form').onsubmit = submit;
const drop = $('drop');
drop.onclick = () => finput.click();
drop.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); finput.click(); } };
finput.onchange = () => { addFiles(finput.files); finput.value = ''; };
drop.ondragover = (e) => { e.preventDefault(); drop.classList.add('over'); };
drop.ondragleave = () => drop.classList.remove('over');
drop.ondrop = (e) => { e.preventDefault(); drop.classList.remove('over'); addFiles(e.dataTransfer.files); };
document.querySelectorAll('[data-close]').forEach((b) => (b.onclick = () => b.closest('dialog').close()));
document.querySelectorAll('dialog').forEach((d) => d.addEventListener('click', (e) => { if (e.target === d) d.close(); }));
let qt;
$('q').oninput = (e) => {
clearTimeout(qt);
qt = setTimeout(() => { state.q = e.target.value; load(); }, 250);
};
}
// Henter innlogget bruker og viser hovedsiden, eller innloggingsskjemaet hvis ingen er logget inn.
async function enter() {
const r = await fetch('/api/me', { credentials: 'same-origin' });
if (r.status === 401) { showLogin(); return; }
if (!r.ok) throw new Error('Får ikke kontakt med serveren. Last inn siden på nytt.');
state.me = await r.json();
$('whoami').textContent = state.me.name || state.me.email;
if (state.me.name) $('f-navn').value = state.me.name;
show('view-main');
renderGrid();
load();
}
async function start() {
try {
state.cfg = await (await fetch('/api/config')).json();
} catch (e) {
$('view-loading').textContent = 'Får ikke kontakt med serveren. Last inn siden på nytt.';
return;
}
wire();
try {
await enter();
} catch (e) {
show('view-loading');
$('view-loading').textContent = e.message;
}
}
start();
})();