Media page shows the whole library, multi-file upload; pill pickers on Redeems

- src/library.js: one list of every media file (built-in public/alerts + uploads),
  shared by the Media page and the Redeems pickers.
- Media page rebuilt: drag & drop / multi-file upload with progress (audio, video,
  images for stickers), Videos / Sounds / Stickers & art with previews, size,
  'used by N' and a filter; only uploads can be deleted.
- Fix: /media no longer 301-redirects to /media/ (express.static redirect:false).
- Redeems: sound / video / sticker / TTS voice are pills (click to change, x to
  clear) with a type-to-search list (arrows, Enter, Esc) instead of dropdowns.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-22 16:24:18 +02:00
parent 8ac8fe024c
commit a32a55c264
6 changed files with 313 additions and 109 deletions

View file

@ -1,53 +1,124 @@
<style>
.drop { border:2px dashed var(--pico-muted-border-color); border-radius:12px; padding:1.2rem; text-align:center; cursor:pointer;
transition:border-color .15s, background .15s; margin-bottom:.6rem; }
.drop.over { border-color:var(--pico-primary); background:rgba(1, 114, 173, .12); }
.drop strong { display:block; margin-bottom:.2rem; }
.drop input { display:none; }
.upbar { height:6px; border-radius:3px; background:var(--pico-muted-border-color); overflow:hidden; margin:.4rem 0; }
.upbar > div { height:100%; width:0; background:var(--pico-primary); transition:width .1s; }
.tools { display:flex; gap:.8rem; align-items:center; flex-wrap:wrap; margin:1rem 0 .4rem; }
.tools input { margin:0; max-width:320px; }
.tools .meta, .meta { color:var(--pico-muted-color); font-size:.85rem; }
.lib-h { margin:1.4rem 0 .5rem; display:flex; align-items:baseline; gap:.6rem; }
.grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(210px, 1fr)); gap:.6rem; }
.item { border:1px solid var(--pico-muted-border-color); border-radius:10px; padding:.5rem; display:flex; flex-direction:column; gap:.35rem; }
.item .pv { height:110px; border-radius:6px; background:#0004; display:flex; align-items:center; justify-content:center; overflow:hidden; }
.item .pv img { max-width:100%; max-height:100%; object-fit:contain; }
.item .pv video { max-width:100%; max-height:100%; }
.item .name { font-weight:600; font-size:.88rem; overflow-wrap:anywhere; }
.item .row { display:flex; gap:.35rem; align-items:center; flex-wrap:wrap; font-size:.75rem; color:var(--pico-muted-color); }
.pill { font-size:.7rem; padding:.02rem .45rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); }
.pill.up { border-color:#3fb950; color:#7ee08f; }
.pill.used { border-color:#a970ff; color:#c9a8ff; }
.item button, .item audio { margin:0; }
.item audio { width:100%; height:30px; }
.btn-sm { margin:0; padding:.2rem .6rem; font-size:.75rem; width:auto; }
.item form { margin:0 0 0 auto; }
.hidden-by-filter { display:none !important; }
</style>
<h2>Media library</h2>
<p><small>Upload audio (MP3, WAV, OGG) or video (MP4, WebM) files to use in actions. Max 50 MB.</small></p>
<form method="POST" action="/media/upload" enctype="multipart/form-data">
<div style="display:flex; gap:1rem; align-items:flex-end;">
<label style="flex:1;">
File
<input type="file" name="file" accept="audio/*,video/*" required>
</label>
<button type="submit">Upload</button>
<div class="drop" id="drop" title="Audio: MP3, WAV, OGG, M4A. Video: WebM (transparent looks best over the game), MP4. Images (stickers): PNG, WebP, GIF, JPG. Max 50 MB per file, up to 20 at once.">
<strong>Drop files here, or click to choose</strong>
<span class="meta">sounds, videos or sticker images · several at once</span>
<input type="file" id="files" multiple accept="audio/*,video/*,image/png,image/webp,image/gif,image/jpeg">
</div>
<div id="up" hidden><div class="upbar"><div id="upfill"></div></div><span class="meta" id="upmsg"></span></div>
<div class="tools">
<input type="search" id="filter" placeholder="Filter by name…">
<span class="meta" title="Built-in files ship with HeyStreamer (public/alerts) and are changed in the code. Uploads live only on the server and can be deleted here.">
<span class="pill">built-in</span> <span class="pill up">uploaded</span> <span class="pill used">used by N</span> ⓘ
</span>
</div>
<% for (const g of groups) { %>
<h3 class="lib-h" data-group><%= g.name %> <span class="meta"><%= g.items.length %></span></h3>
<% if (!g.items.length) { %><p class="meta"><%= g.type === 'video' ? 'No videos yet: drop some above.' : 'Nothing here yet.' %></p><% } %>
<div class="grid">
<% for (const i of g.items) { %>
<div class="item" data-name="<%= (i.label + ' ' + i.file).toLowerCase() %>">
<div class="pv">
<% if (i.type === 'image') { %><img src="<%= i.url %>" alt="" loading="lazy">
<% } else if (i.type === 'video') { %><video src="<%= i.url %>#t=0.5" preload="metadata" muted playsinline data-hoverplay title="Hover to play (muted). Click for sound."></video>
<% } else { %><span style="font-size:2rem;">🔊</span><% } %>
</div>
<div class="name" title="<%= i.url %>"><%= i.label %></div>
<% if (i.type === 'audio') { %><audio controls preload="none" src="<%= i.url %>"></audio><% } %>
<div class="row">
<span class="pill <%= i.source === 'upload' ? 'up' : '' %>"><%= i.source === 'upload' ? 'uploaded' : 'built-in' %></span>
<% if (i.note) { %><span class="pill" title="Loudness-matched sound"><%= i.note %></span><% } %>
<% if (i.used) { %><span class="pill used" title="Used by <%= i.used %> redeem variation<%= i.used === 1 ? '' : 's' %>">used by <%= i.used %></span><% } %>
<span><%= i.size > 1048576 ? (i.size / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(i.size / 1024)) + ' KB' %></span>
<% if (i.source === 'upload') { %>
<form method="POST" action="/media/<%= i.id %>/delete">
<button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;"
title="<%= i.used ? `Used by ${i.used} variation(s): they will play nothing until you pick another file` : 'Delete this upload' %>">Delete</button>
</form>
<% } %>
</div>
</div>
<% } %>
</div>
</form>
<% if (files.length === 0) { %>
<p><em>No files uploaded yet.</em></p>
<% } else { %>
<figure>
<table>
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Size</th>
<th>Uploaded</th>
<th>Preview</th>
<th></th>
</tr>
</thead>
<tbody>
<% for (const f of files) { %>
<tr>
<td><%= f.original_name %></td>
<td><code><%= f.media_type %></code></td>
<td><%= (f.size_bytes / 1024).toFixed(0) %> KB</td>
<td><small><%= f.uploaded_at %></small></td>
<td>
<% if (f.media_type === 'audio') { %>
<audio controls src="/media/<%= f.filename %>" style="height:28px; width:160px;"></audio>
<% } else { %>
<video controls src="/media/<%= f.filename %>" style="height:40px; width:80px;"></video>
<% } %>
</td>
<td>
<form method="POST" action="/media/<%= f.id %>/delete">
<button type="button" data-confirm class="outline" style="padding:0.2rem 0.6rem; font-size:0.8rem; color:#f88;">Delete</button>
</form>
</td>
</tr>
<% } %>
</tbody>
</table>
</figure>
<% } %>
<script>
(() => {
// upload: drag & drop or click, several files, progress bar, then reload the list
const drop = document.getElementById('drop'), input = document.getElementById('files');
const up = document.getElementById('up'), fill = document.getElementById('upfill'), msg = document.getElementById('upmsg');
drop.addEventListener('click', () => input.click());
['dragenter', 'dragover'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.add('over'); }));
['dragleave', 'drop'].forEach(t => drop.addEventListener(t, e => { e.preventDefault(); drop.classList.remove('over'); }));
drop.addEventListener('drop', e => send(e.dataTransfer.files));
input.addEventListener('change', () => send(input.files));
function send(files) {
if (!files || !files.length) return;
const fd = new FormData(); for (const f of files) fd.append('files', f);
const x = new XMLHttpRequest();
x.open('POST', '/media/upload'); x.setRequestHeader('Accept', 'application/json'); x.setRequestHeader('X-File-Count', files.length);
up.hidden = false; fill.style.width = '0'; msg.textContent = `Uploading ${files.length} file${files.length === 1 ? '' : 's'}…`;
x.upload.onprogress = e => { if (e.lengthComputable) fill.style.width = (100 * e.loaded / e.total) + '%'; };
x.onload = () => {
let j = {}; try { j = JSON.parse(x.responseText); } catch {}
if (x.status === 200 && j.ok) {
msg.textContent = `Uploaded ${j.saved}` + (j.skipped ? ` · skipped ${j.skipped} (not audio, video or image)` : '') + ' · refreshing…';
setTimeout(() => location.reload(), 600);
} else msg.textContent = 'Upload failed: ' + (j.error || x.status);
};
x.onerror = () => { msg.textContent = 'Upload failed (connection)'; };
x.send(fd);
}
// filter
document.getElementById('filter').addEventListener('input', e => {
const q = e.target.value.trim().toLowerCase();
document.querySelectorAll('.item').forEach(i => i.classList.toggle('hidden-by-filter', !!q && !i.dataset.name.includes(q)));
// hide sections with nothing left
document.querySelectorAll('h3[data-group]').forEach(h => {
const grid = h.nextElementSibling?.classList.contains('grid') ? h.nextElementSibling : h.nextElementSibling?.nextElementSibling;
const any = !!grid?.querySelector('.item:not(.hidden-by-filter)');
h.classList.toggle('hidden-by-filter', !!q && !any);
});
});
// videos: play muted on hover, with sound on click
document.querySelectorAll('[data-hoverplay]').forEach(v => {
v.addEventListener('mouseenter', () => { v.play().catch(() => {}); });
v.addEventListener('mouseleave', () => { v.pause(); v.currentTime = 0.5; v.muted = true; });
v.addEventListener('click', () => { v.muted = false; v.currentTime = 0; v.play().catch(() => {}); });
});
})();
</script>

View file

@ -50,6 +50,25 @@
.thumb { width:34px; height:34px; object-fit:contain; }
.vol-out { font-size:.75rem; color:var(--pico-muted-color); width:2.6em; }
.preview { margin-top:.5rem; max-width:320px; border-radius:8px; background:#0006; }
/* pickers: a pill with the current choice (click to change, x to clear) or "+ …"; typing filters */
.pick { position:relative; display:inline-flex; align-items:center; }
.chip { display:inline-flex; align-items:center; gap:.35rem; padding:.18rem .3rem .18rem .6rem; border-radius:99px; font-size:.82rem;
background:rgba(1,114,173,.18); border:1px solid rgba(1,114,173,.55); cursor:pointer; max-width:340px; }
.chip .lbl { overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.chip img { width:22px; height:22px; object-fit:contain; }
.chip .x { border:0; background:none; color:inherit; padding:0 .3rem; margin:0; width:auto; font-size:.95rem; line-height:1; opacity:.7; cursor:pointer; }
.chip .x:hover { opacity:1; }
.chip .tag { font-size:.65rem; opacity:.7; }
.chip.add { background:none; border-style:dashed; color:var(--pico-muted-color); padding-right:.6rem; }
.pick.disabled .chip { opacity:.45; }
.pick input.q { margin:0; padding:.25rem .6rem; font-size:.82rem; height:auto; width:260px; border-radius:99px; }
.pick ul.opts { position:absolute; top:100%; left:0; z-index:30; list-style:none; margin:.2rem 0 0; padding:.25rem; min-width:260px; max-height:260px; overflow:auto;
background:var(--pico-card-background-color); border:1px solid var(--pico-muted-border-color); border-radius:10px; box-shadow:0 8px 20px rgba(0,0,0,.4); }
.pick ul.opts li { list-style:none; padding:.25rem .5rem; border-radius:6px; font-size:.82rem; cursor:pointer; display:flex; align-items:center; gap:.4rem; }
.pick ul.opts li img { width:22px; height:22px; object-fit:contain; }
.pick ul.opts li .tag { margin-left:auto; font-size:.68rem; color:var(--pico-muted-color); }
.pick ul.opts li.on { background:rgba(1,114,173,.3); }
.pick ul.opts li.none { color:var(--pico-muted-color); cursor:default; }
[data-show] { display:none !important; }
.vcard[data-display="cassette"] [data-show~="cassette"],
.vcard[data-display="sound"] [data-show~="sound"],
@ -121,31 +140,22 @@
</div>
<div class="vrow" data-show="cassette sound">
<span class="field grow"><select data-f="sound" title="Sound that plays (TTS on: the voice replaces it)">
<option value="">— silent —</option>
<% for (const s of sounds) { %><option value="<%= s.url %>" <%= v.sound === s.url ? 'selected' : '' %>><%= s.label %></option><% } %>
</select></span>
<input type="hidden" data-f="sound" value="<%= v.sound || '' %>">
<span class="pick" data-pick="sound" title="Sound that plays (TTS on: the voice replaces it)"></span>
<button type="button" class="outline btn-sm" data-play-sound title="Play the sound here in the browser">▶</button>
</div>
<div class="vrow" data-show="cassette">
<span class="field"><img class="thumb" data-thumb alt="">
<select data-f="art" style="width:auto;" title="Sticker in the cassette's corner">
<option value="">headset Streamer</option>
<% for (const st of stickers) { %><option value="<%= st.url %>" <%= v.art === st.url ? 'selected' : '' %>><%= st.label %></option><% } %>
</select></span>
<input type="hidden" data-f="art" value="<%= v.art || '' %>">
<span class="pick" data-pick="art" title="Sticker in the cassette's corner"></span>
<span class="field grow"><input data-f="caption" value="<%= v.caption %>" title="Text after the viewer's name on the paper strip. {reward} = reward name, {variation} = this variation's name. The viewer's typed message is added automatically."></span>
<select data-f="tts_voice_id" style="width:auto;" title="Read the viewer's typed text aloud (voice from the TTS page), shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch.">
<option value="">TTS: off</option>
<% for (const tv of ttsVoices) { %><option value="<%= tv.id %>" <%= v.tts_voice_id === tv.id ? 'selected' : '' %>>TTS: <%= tv.name %></option><% } %>
</select>
<input type="hidden" data-f="tts_voice_id" value="<%= v.tts_voice_id || '' %>">
<span class="pick" data-pick="tts_voice_id" title="Read the viewer's typed text aloud (voice from the TTS page), shown as a big paper note. The voice replaces the sound. The reward needs 'Require Viewer to Enter Text' on Twitch."></span>
</div>
<div class="vrow" data-show="video">
<span class="field grow"><select data-f="video" title="Video file: uploads on the Media page (transparent WebM looks best)">
<option value="">— pick a video —</option>
<% for (const o of videos) { %><option value="<%= o.url %>" <%= v.video === o.url ? 'selected' : '' %>><%= o.label %></option><% } %>
</select></span>
<input type="hidden" data-f="video" value="<%= v.video || '' %>">
<span class="pick" data-pick="video" title="Video file: built-in or uploaded on the Media page (transparent WebM looks best)"></span>
<button type="button" class="outline btn-sm" data-play-video title="Preview the video here">▶</button>
<% if (!videos.length) { %><a href="/media" class="meta">upload a video on Media</a><% } %>
</div>
@ -166,6 +176,15 @@
<script>
(() => {
const RARITY = <%- JSON.stringify(rarity) %>;
// picker options (same files as the Media page)
const OPTS = {
sound: <%- JSON.stringify(sounds) %>,
video: <%- JSON.stringify(videos) %>,
art: <%- JSON.stringify(stickers) %>,
tts_voice_id: <%- JSON.stringify(ttsVoices.map(t => ({ url: String(t.id), label: t.name }))) %>,
};
const ADD = { sound: '+ sound', video: '+ video', art: '+ sticker', tts_voice_id: '+ TTS voice' };
const DEFAULT_STICKER = { url: '', label: 'headset Streamer (default)', img: '/alerts/stickers/default-sticker.png' };
const DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen';
const stateEl = document.getElementById('save-state');
const dirty = new Set();
@ -205,10 +224,9 @@
c.dataset.display = o.display;
c.classList.toggle('off', !o.enabled);
c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%';
const art = c.querySelector('[data-f="art"]'), th = c.querySelector('[data-thumb]');
th.src = art.value || '/alerts/stickers/default-sticker.png'; // cassette.js DEFAULT_STICKER
const snd = c.querySelector('[data-f="sound"]');
snd.disabled = !!o.tts_voice_id && o.display === 'cassette';
const ttsOn = !!o.tts_voice_id && o.display === 'cassette';
c.querySelector('[data-pick="sound"]').classList.toggle('disabled', ttsOn);
c.querySelectorAll('[data-pick]').forEach(renderPick);
chances(c.closest('[data-trigger]'));
}
function chances(t) {
@ -219,6 +237,62 @@
if (el && cs.length) el.textContent = `${n}/${cs.length} on`;
}
// --- pickers ---
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[ch]));
const field = el => el.closest('.vcard').querySelector(`[data-f="${el.dataset.pick}"]`);
function setVal(el, val) {
const h = field(el); h.value = val;
h.dispatchEvent(new Event('change', { bubbles: true })); // -> sync + unsaved change
}
function renderPick(el) {
if (el.querySelector('input.q')) return; // editing right now
const f = el.dataset.pick, val = field(el).value;
let o = OPTS[f].find(x => String(x.url) === String(val));
if (!o && val) o = { url: val, label: val.split('/').pop() + ' (missing)' };
if (!o && f === 'art') o = DEFAULT_STICKER;
if (!o) { el.innerHTML = `<span class="chip add" tabindex="0">${ADD[f]}</span>`; return; }
const img = f === 'art' ? `<img src="${esc(o.img || o.url)}" alt="">` : '';
const clear = val ? '<button type="button" class="x" title="Remove">×</button>' : '';
el.innerHTML = `<span class="chip" tabindex="0" title="Click to change">${img}<span class="lbl">${esc(o.label)}</span>${o.note ? `<span class="tag">${esc(o.note)}</span>` : ''}${clear}</span>`;
}
function openPick(el) {
if (el.querySelector('input.q')) return;
const f = el.dataset.pick, list = OPTS[f];
el.innerHTML = '<input class="q" placeholder="type to search…" autocomplete="off"><ul class="opts"></ul>';
const q = el.querySelector('input.q'), ul = el.querySelector('ul.opts');
let hits = [], at = 0;
const draw = () => {
const s = q.value.trim().toLowerCase();
hits = list.filter(o => !s || o.label.toLowerCase().includes(s) || String(o.url).toLowerCase().includes(s)).slice(0, 80);
at = Math.min(at, Math.max(0, hits.length - 1));
ul.innerHTML = hits.length ? hits.map((o, i) => `<li data-i="${i}" class="${i === at ? 'on' : ''}">${f === 'art' ? `<img src="${esc(o.url)}" alt="">` : ''}${esc(o.label)}${o.note ? `<span class="tag">${esc(o.note)}</span>` : ''}</li>`).join('')
: '<li class="none">nothing matches</li>';
ul.querySelector('li.on')?.scrollIntoView({ block: 'nearest' });
};
const close = () => { el.innerHTML = ''; renderPick(el); };
const choose = i => { const o = hits[i]; if (!o) return; el.innerHTML = ''; setVal(el, String(o.url)); renderPick(el); };
q.addEventListener('input', () => { at = 0; draw(); });
q.addEventListener('keydown', e => {
if (e.key === 'ArrowDown') { e.preventDefault(); at = Math.min(at + 1, hits.length - 1); draw(); }
else if (e.key === 'ArrowUp') { e.preventDefault(); at = Math.max(at - 1, 0); draw(); }
else if (e.key === 'Enter') { e.preventDefault(); choose(at); }
else if (e.key === 'Escape') { e.preventDefault(); close(); }
});
ul.addEventListener('mousedown', e => { const li = e.target.closest('li[data-i]'); if (li) { e.preventDefault(); choose(+li.dataset.i); } });
q.addEventListener('blur', () => setTimeout(() => { if (el.contains(q)) close(); }, 120));
draw(); q.focus();
}
document.addEventListener('click', e => {
const x = e.target.closest('.pick .x');
if (x) { e.stopPropagation(); const el = x.closest('.pick'); setVal(el, ''); renderPick(el); return; }
const chip = e.target.closest('.pick .chip');
if (chip) openPick(chip.closest('.pick'));
});
document.addEventListener('keydown', e => {
const chip = e.target.closest?.('.pick .chip');
if (chip && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); openPick(chip.closest('.pick')); }
});
function markDirty(c) {
dirty.add(c.dataset.id); c.classList.add('dirty');
const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} };