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

@ -22,7 +22,8 @@ app.use((req, res, next) => {
next(); next();
}); });
app.use(express.static(path.join(__dirname, '../public'))); // redirect:false: /media (the uploads folder) must not bounce to /media/ before the Media page route
app.use(express.static(path.join(__dirname, '../public'), { redirect: false }));
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true }));
app.use(express.json()); app.use(express.json());

58
src/library.js Normal file
View file

@ -0,0 +1,58 @@
// Every media file HeyStreamer can use, in one list: the built-in library under public/alerts (shipped with
// the code) and uploads from the Media page (public/media, kept only on the server, listed in media_files).
// Used by the Media page and by the Redeems pickers, so both always show the same files.
// { url, label, type: 'audio' | 'video' | 'image', source: 'library' | 'upload', id?, size, file }
const fs = require('fs');
const path = require('path');
const db = require('./db');
const PUBLIC = path.join(__dirname, '..', 'public');
const RE = { audio: /\.(mp3|wav|ogg|m4a)$/i, video: /\.(webm|mp4|mov)$/i, image: /\.(png|webp|gif|jpe?g)$/i };
// built-in folders, in the order they are listed
const DIRS = [
{ dir: 'alerts/videos', type: 'video' },
{ dir: 'alerts/sounds/redeems', type: 'audio', note: 'normalized' },
{ dir: 'alerts/sounds', type: 'audio' },
{ dir: 'alerts/stickers', type: 'image' },
{ dir: 'alerts/art', type: 'image' },
];
const pretty = f => f.replace(/\.\w+$/, '').replace(/_Contrast$/, '').replace(/[_]+/g, ' ');
function typeOf(mime, name) {
if (/^video\//.test(mime) || RE.video.test(name)) return 'video';
if (/^audio\//.test(mime) || RE.audio.test(name)) return 'audio';
if (/^image\/(png|webp|gif|jpeg)$/.test(mime) || RE.image.test(name)) return 'image';
return null;
}
function list() {
const out = [];
for (const d of DIRS) {
let files = [];
try { files = fs.readdirSync(path.join(PUBLIC, d.dir)).filter(f => RE[d.type].test(f)).sort(); } catch { /* folder missing */ }
for (const f of files) {
let size = 0;
try { size = fs.statSync(path.join(PUBLIC, d.dir, f)).size; } catch {}
out.push({ url: `/${d.dir}/${f}`, label: pretty(f), file: f, type: d.type, source: 'library', size, note: d.note || null });
}
}
for (const m of db.getAllMedia()) {
const type = m.media_type === 'image' ? 'image' : m.media_type === 'video' ? 'video' : 'audio';
out.push({ url: `/media/${m.filename}`, label: pretty(m.original_name), file: m.original_name, type, source: 'upload',
id: m.id, size: m.size_bytes, uploaded_at: m.uploaded_at });
}
return out;
}
const ofType = type => list().filter(i => i.type === type);
// how many redeem variations use each URL (as sound, video or sticker)
function usage() {
const n = new Map();
for (const v of db.getAllVariations()) for (const u of [v.sound, v.video, v.art]) if (u) n.set(u, (n.get(u) || 0) + 1);
return n;
}
module.exports = { list, ofType, usage, typeOf, PUBLIC };

View file

@ -5,27 +5,47 @@ const path = require('path');
const fs = require('fs'); const fs = require('fs');
const { v4: uuidv4 } = require('uuid'); const { v4: uuidv4 } = require('uuid');
const db = require('../db'); const db = require('../db');
const library = require('../library');
// uploads go to public/media (not in git, never touched by deploys); audio, video and images (stickers)
const storage = multer.diskStorage({ const storage = multer.diskStorage({
destination: path.join(__dirname, '../../public/media'), destination: path.join(__dirname, '../../public/media'),
filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname)), filename: (req, file, cb) => cb(null, uuidv4() + path.extname(file.originalname).toLowerCase()),
});
const upload = multer({
storage, limits: { fileSize: 50 * 1024 * 1024, files: 20 },
fileFilter: (req, file, cb) => cb(null, !!library.typeOf(file.mimetype, file.originalname)),
}); });
const upload = multer({ storage, limits: { fileSize: 50 * 1024 * 1024 } });
router.get('/', (req, res) => { router.get('/', (req, res) => {
res.render('media', { files: db.getAllMedia() }); const items = library.list();
const used = library.usage();
for (const i of items) i.used = used.get(i.url) || 0;
res.render('media', {
groups: [
{ type: 'video', name: 'Videos', items: items.filter(i => i.type === 'video') },
{ type: 'audio', name: 'Sounds', items: items.filter(i => i.type === 'audio') },
{ type: 'image', name: 'Stickers & art', items: items.filter(i => i.type === 'image') },
],
});
}); });
router.post('/upload', upload.single('file'), (req, res) => { // several files at once; answers JSON for the page's upload (progress bar), redirects for a plain form post
if (!req.file) return res.redirect('/media'); router.post('/upload', (req, res) => {
db.createMedia({ upload.array('files', 20)(req, res, err => {
filename: req.file.filename, const json = (req.get('Accept') || '').includes('application/json');
original_name: req.file.originalname, if (err) {
media_type: req.file.mimetype.startsWith('video') ? 'video' : 'audio', const msg = err.code === 'LIMIT_FILE_SIZE' ? 'File too big (max 50 MB)' : err.message;
size_bytes: req.file.size, return json ? res.status(400).json({ ok: false, error: msg }) : res.status(400).send(msg);
}); }
console.log(`[media] Uploaded: ${req.file.originalname} (${req.file.size} bytes)`); const files = req.files || [];
for (const f of files) {
db.createMedia({ filename: f.filename, original_name: f.originalname, media_type: library.typeOf(f.mimetype, f.originalname), size_bytes: f.size });
console.log(`[media] Uploaded: ${f.originalname} (${f.size} bytes)`);
}
if (json) return res.json({ ok: true, saved: files.length, skipped: Math.max(0, (req.headers['x-file-count'] | 0) - files.length) });
res.redirect('/media'); res.redirect('/media');
});
}); });
router.post('/:id/delete', (req, res) => { router.post('/:id/delete', (req, res) => {

View file

@ -1,32 +1,15 @@
const express = require('express'); const express = require('express');
const fs = require('fs');
const path = require('path');
const router = express.Router(); const router = express.Router();
const db = require('../db'); const db = require('../db');
const twitch = require('../twitch'); const twitch = require('../twitch');
const redeems = require('../redeems'); const redeems = require('../redeems');
const PUBLIC = path.join(__dirname, '../../public');
const listDir = (dir, re) => { try { return fs.readdirSync(path.join(PUBLIC, dir)).filter(f => re.test(f)).sort(); } catch { return []; } };
function soundOptions() { // pickers: the same files the Media page lists (src/library.js)
const re = /\.(mp3|wav|ogg|m4a)$/i; const library = require('../library');
const lib = [ const soundOptions = () => library.ofType('audio').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : i.note }));
...listDir('alerts/sounds/redeems', re).map(f => ({ url: `/alerts/sounds/redeems/${f}`, label: `${f} (normalized)` })), const videoOptions = () => library.ofType('video').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : null }));
...listDir('alerts/sounds', re).map(f => ({ url: `/alerts/sounds/${f}`, label: f })), const stickerOptions = () => library.ofType('image').map(i => ({ url: i.url, label: i.label, note: i.source === 'upload' ? 'uploaded' : null }));
];
const uploads = db.getAllMedia().filter(m => m.media_type === 'audio')
.map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` }));
return [...lib, ...uploads];
}
// videos for 'Video' variations: files in public/alerts/videos + videos uploaded on the Media page
function videoOptions() {
const lib = listDir('alerts/videos', /\.(webm|mp4|mov)$/i).map(f => ({ url: `/alerts/videos/${f}`, label: f }));
const uploads = db.getAllMedia().filter(m => m.media_type === 'video')
.map(m => ({ url: `/media/${m.filename}`, label: `${m.original_name} (uploaded)` }));
return [...lib, ...uploads];
}
// live list of the channel's Custom Power-ups (bits); null when Twitch is not reachable // live list of the channel's Custom Power-ups (bits); null when Twitch is not reachable
let loggedPowerUps = false; let loggedPowerUps = false;
@ -98,10 +81,7 @@ router.get('/', async (req, res) => {
sounds: soundOptions(), sounds: soundOptions(),
videos: videoOptions(), videos: videoOptions(),
ttsVoices: db.getAllTtsVoices(), ttsVoices: db.getAllTtsVoices(),
stickers: [ stickers: stickerOptions(),
...listDir('alerts/stickers', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/stickers/${f}`, label: f.replace(/\.\w+$/, '') })),
...listDir('alerts/art', /\.(png|webp|gif)$/i).map(f => ({ url: `/alerts/art/${f}`, label: f.replace('_Contrast', '').replace(/\.\w+$/, '') })),
],
}); });
}); });

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> <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 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.">
<div style="display:flex; gap:1rem; align-items:flex-end;"> <strong>Drop files here, or click to choose</strong>
<label style="flex:1;"> <span class="meta">sounds, videos or sticker images · several at once</span>
File <input type="file" id="files" multiple accept="audio/*,video/*,image/png,image/webp,image/gif,image/jpeg">
<input type="file" name="file" accept="audio/*,video/*" required> </div>
</label> <div id="up" hidden><div class="upbar"><div id="upfill"></div></div><span class="meta" id="upmsg"></span></div>
<button type="submit">Upload</button>
<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>
</form> <div class="name" title="<%= i.url %>"><%= i.label %></div>
<% if (i.type === 'audio') { %><audio controls preload="none" src="<%= i.url %>"></audio><% } %>
<% if (files.length === 0) { %> <div class="row">
<p><em>No files uploaded yet.</em></p> <span class="pill <%= i.source === 'upload' ? 'up' : '' %>"><%= i.source === 'upload' ? 'uploaded' : 'built-in' %></span>
<% } else { %> <% if (i.note) { %><span class="pill" title="Loudness-matched sound"><%= i.note %></span><% } %>
<figure> <% if (i.used) { %><span class="pill used" title="Used by <%= i.used %> redeem variation<%= i.used === 1 ? '' : 's' %>">used by <%= i.used %></span><% } %>
<table> <span><%= i.size > 1048576 ? (i.size / 1048576).toFixed(1) + ' MB' : Math.max(1, Math.round(i.size / 1024)) + ' KB' %></span>
<thead> <% if (i.source === 'upload') { %>
<tr> <form method="POST" action="/media/<%= i.id %>/delete">
<th>Name</th> <button type="button" data-confirm class="outline btn-sm" style="color:#f88; border-color:#f88;"
<th>Type</th> title="<%= i.used ? `Used by ${i.used} variation(s): they will play nothing until you pick another file` : 'Delete this upload' %>">Delete</button>
<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> </form>
</td>
</tr>
<% } %> <% } %>
</tbody> </div>
</table> </div>
</figure> <% } %>
</div>
<% } %> <% } %>
<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; } .thumb { width:34px; height:34px; object-fit:contain; }
.vol-out { font-size:.75rem; color:var(--pico-muted-color); width:2.6em; } .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; } .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; } [data-show] { display:none !important; }
.vcard[data-display="cassette"] [data-show~="cassette"], .vcard[data-display="cassette"] [data-show~="cassette"],
.vcard[data-display="sound"] [data-show~="sound"], .vcard[data-display="sound"] [data-show~="sound"],
@ -121,31 +140,22 @@
</div> </div>
<div class="vrow" data-show="cassette sound"> <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)"> <input type="hidden" data-f="sound" value="<%= v.sound || '' %>">
<option value="">— silent —</option> <span class="pick" data-pick="sound" title="Sound that plays (TTS on: the voice replaces it)"></span>
<% for (const s of sounds) { %><option value="<%= s.url %>" <%= v.sound === s.url ? 'selected' : '' %>><%= s.label %></option><% } %>
</select></span>
<button type="button" class="outline btn-sm" data-play-sound title="Play the sound here in the browser">▶</button> <button type="button" class="outline btn-sm" data-play-sound title="Play the sound here in the browser">▶</button>
</div> </div>
<div class="vrow" data-show="cassette"> <div class="vrow" data-show="cassette">
<span class="field"><img class="thumb" data-thumb alt=""> <input type="hidden" data-f="art" value="<%= v.art || '' %>">
<select data-f="art" style="width:auto;" title="Sticker in the cassette's corner"> <span class="pick" data-pick="art" title="Sticker in the cassette's corner"></span>
<option value="">headset Streamer</option>
<% for (const st of stickers) { %><option value="<%= st.url %>" <%= v.art === st.url ? 'selected' : '' %>><%= st.label %></option><% } %>
</select></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> <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."> <input type="hidden" data-f="tts_voice_id" value="<%= v.tts_voice_id || '' %>">
<option value="">TTS: off</option> <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>
<% for (const tv of ttsVoices) { %><option value="<%= tv.id %>" <%= v.tts_voice_id === tv.id ? 'selected' : '' %>>TTS: <%= tv.name %></option><% } %>
</select>
</div> </div>
<div class="vrow" data-show="video"> <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)"> <input type="hidden" data-f="video" value="<%= v.video || '' %>">
<option value="">— pick a video —</option> <span class="pick" data-pick="video" title="Video file: built-in or uploaded on the Media page (transparent WebM looks best)"></span>
<% for (const o of videos) { %><option value="<%= o.url %>" <%= v.video === o.url ? 'selected' : '' %>><%= o.label %></option><% } %>
</select></span>
<button type="button" class="outline btn-sm" data-play-video title="Preview the video here">▶</button> <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><% } %> <% if (!videos.length) { %><a href="/media" class="meta">upload a video on Media</a><% } %>
</div> </div>
@ -166,6 +176,15 @@
<script> <script>
(() => { (() => {
const RARITY = <%- JSON.stringify(rarity) %>; 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 DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen';
const stateEl = document.getElementById('save-state'); const stateEl = document.getElementById('save-state');
const dirty = new Set(); const dirty = new Set();
@ -205,10 +224,9 @@
c.dataset.display = o.display; c.dataset.display = o.display;
c.classList.toggle('off', !o.enabled); c.classList.toggle('off', !o.enabled);
c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%'; c.querySelector('[data-vol]').textContent = Math.round(o.volume * 100) + '%';
const art = c.querySelector('[data-f="art"]'), th = c.querySelector('[data-thumb]'); const ttsOn = !!o.tts_voice_id && o.display === 'cassette';
th.src = art.value || '/alerts/stickers/default-sticker.png'; // cassette.js DEFAULT_STICKER c.querySelector('[data-pick="sound"]').classList.toggle('disabled', ttsOn);
const snd = c.querySelector('[data-f="sound"]'); c.querySelectorAll('[data-pick]').forEach(renderPick);
snd.disabled = !!o.tts_voice_id && o.display === 'cassette';
chances(c.closest('[data-trigger]')); chances(c.closest('[data-trigger]'));
} }
function chances(t) { function chances(t) {
@ -219,6 +237,62 @@
if (el && cs.length) el.textContent = `${n}/${cs.length} on`; 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) { function markDirty(c) {
dirty.add(c.dataset.id); c.classList.add('dirty'); dirty.add(c.dataset.id); c.classList.add('dirty');
const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} }; const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} };