heystreamer/views/redeems.ejs
Bashy b3caac7a31 Video Power-ups: Custom Power-ups, ?parts=video overlay, new redeems editor
- Custom Power-ups (bits) are redeem triggers: channel.custom_power_up_redemption.add
  -> redeems.handle('custom_power_up', ...) with the bits amount; listed live from
  Helix /bits/custom_power_ups on the Redeems page; labels/replay in Recent activity.
- Variations can show a video (reward_variations.video): style 'video' plays only on
  the opt-in ?parts=video overlay (public/alerts/video.js), full-screen, one at a time,
  with a yellow camcorder box ("TRIGGERED <name>", viewer, bits, POWER-UP) in the alert
  corner. Any source size; 2560x1440 like HUDFX gives sharper video.
- Redeems page rewritten as one editor: Display (Cassette / Sound only / Video),
  volume slider, sticker thumbnails, live % chances, one Save button + Ctrl+S
  (POST /redeems/save), tests/add/delete save first, unsaved edits kept as a browser
  draft with an inline restore bar (no dialogs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:10:56 +02:00

329 lines
20 KiB
Text

<style>
/* save bar */
.savebar { position:sticky; top:0; z-index:20; display:flex; align-items:center; gap:.8rem; flex-wrap:wrap;
padding:.55rem .9rem; margin:0 0 1rem; border-radius:10px; background:var(--pico-card-background-color);
border:1px solid var(--pico-muted-border-color); box-shadow:0 4px 14px rgba(0,0,0,.25); }
.savebar .state { font-size:.9rem; }
.savebar .state.dirty { color:#e6b800; font-weight:600; }
.savebar .state.ok { color:#3fb950; }
.savebar .state.err { color:#f88; }
.savebar button { margin:0; width:auto; padding:.35rem 1.1rem; }
.savebar kbd { font-size:.7rem; }
.draftbar { display:flex; gap:.6rem; align-items:center; flex-wrap:wrap; padding:.5rem .9rem; margin:-.4rem 0 1rem;
border:1px dashed #e6b800; border-radius:10px; font-size:.9rem; }
.draftbar button { margin:0; width:auto; padding:.25rem .8rem; font-size:.85rem; }
/* triggers */
.group-h { margin:1.6rem 0 .6rem; }
.trig { border:1px solid var(--pico-muted-border-color); border-radius:12px; padding:.45rem .9rem; margin-bottom:.6rem; }
.trig[open] { padding-bottom:.8rem; }
.trig > summary { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; cursor:pointer; }
.trig > summary img { width:24px; height:24px; border-radius:4px; }
.meta { color:var(--pico-muted-color); font-size:.85rem; }
.pill { font-size:.75rem; padding:.05rem .5rem; border-radius:99px; border:1px solid var(--pico-muted-border-color); color:var(--pico-muted-color); }
.pill.bits { border-color:#a970ff; color:#c9a8ff; }
.pill.pts { border-color:#3fb950; color:#7ee08f; }
.btn-sm { margin:0; padding:.25rem .7rem; font-size:.8rem; width:auto; }
.danger { color:#f88; border-color:#f88; }
.warn { color:#e6b800; }
/* variation cards */
.vcard { border:1px solid var(--pico-muted-border-color); border-left:4px solid var(--pico-muted-border-color);
border-radius:10px; padding:.6rem .8rem; margin:.6rem 0; }
.vcard.dirty { border-left-color:#e6b800; }
.vcard.off { opacity:.55; }
.vrow { display:flex; align-items:center; gap:.6rem; flex-wrap:wrap; }
.vrow + .vrow { margin-top:.55rem; }
.vcard input, .vcard select { margin:0; padding:.3rem .5rem; font-size:.85rem; height:auto; }
.vcard input[type=checkbox] { margin:0; }
.vcard input[type=range] { padding:0; width:110px; }
.vname { flex:1 1 180px; font-weight:600; }
.chance { font-size:.8rem; color:var(--pico-muted-color); min-width:5.5em; }
.field { display:flex; align-items:center; gap:.4rem; }
.field > span:first-child { font-size:.75rem; color:var(--pico-muted-color); }
.grow { flex:1 1 220px; }
.grow > input, .grow > select { width:100%; }
.seg { display:inline-flex; border:1px solid var(--pico-muted-border-color); border-radius:8px; overflow:hidden; }
.seg label { margin:0; padding:.25rem .8rem; font-size:.8rem; cursor:pointer; user-select:none; }
.seg input { display:none; }
.seg label:has(input:checked) { background:var(--pico-primary-background); color:var(--pico-primary-inverse); }
.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; }
[data-show] { display:none !important; }
.vcard[data-display="cassette"] [data-show~="cassette"],
.vcard[data-display="sound"] [data-show~="sound"],
.vcard[data-display="video"] [data-show~="video"] { display:flex !important; }
</style>
<h2>Redeems</h2>
<div class="savebar">
<button type="button" id="save-all" title="Save every change on this page (Ctrl+S)">Save</button>
<span class="state ok" id="save-state">All saved</span>
<span class="meta" style="margin-left:auto;" title="Each redeem plays ONE of its enabled variations, picked at random by rarity (relative weights). Sounds: built-in library or uploads on the Media page. Videos: uploads on the Media page (transparent WebM looks best); they play on the overlay URL with ?parts=video.">
How it works ⓘ · <kbd>Ctrl</kbd>+<kbd>S</kbd> saves
</span>
</div>
<div class="draftbar" id="draftbar" hidden>
<span>Unsaved changes from <strong id="draft-when"></strong> were kept in this browser.</span>
<button type="button" id="draft-restore">Restore them</button>
<button type="button" class="outline" id="draft-discard">Discard</button>
</div>
<% if (!twitchOk) { %><p class="warn">Could not load your channel point rewards from Twitch right now, so only rewards that already have variations are listed.</p><% } %>
<% for (const g of groups) { %>
<h3 class="group-h" <%= g.id ? `id=${g.id}` : '' %>><%= g.name %></h3>
<% if (!g.items.length && g.empty) { %><p class="meta"><%= g.empty %></p><% } %>
<% for (const t of g.items) {
const on = t.variations.filter(v => v.enabled);
const anchor = `t-${t.kind}-${t.key}`; %>
<details class="trig" id="<%= anchor %>" data-trigger>
<summary>
<% if (t.image) { %><img src="<%= t.image %>" alt=""><% } %>
<strong><%= t.title %></strong>
<% if (t.cost != null) { %><span class="pill pts"><%= t.cost %> pts</span><% } %>
<% if (t.bits != null) { %><span class="pill bits"><%= t.bits %> bits</span><% } %>
<% if (t.missing) { %><span class="badge badge-red">not on Twitch anymore</span><% } %>
<% if (t.live === false) { %><span class="badge badge-grey">paused on Twitch</span><% } %>
<% if (t.variations.some(v => v.video)) { %><span class="pill" title="At least one variation plays a full-screen video (?parts=video overlay)">video</span><% } %>
<% if (t.variations.some(v => v.tts_voice_id)) { %><span class="pill" title="At least one variation reads the viewer's text aloud">TTS</span><% } %>
<span class="meta" data-count><%= t.variations.length ? `${on.length}/${t.variations.length} on` : 'no alert yet' %></span>
<% if (on.length) { %>
<button type="button" class="outline btn-sm" data-test-trigger data-kind="<%= t.kind %>" data-key="<%= t.key %>" title="Play a random enabled variation on the overlay (saves first)">Test random</button>
<% } %>
</summary>
<% for (const v of t.variations) {
const display = v.video ? 'video' : v.polaroid ? 'cassette' : 'sound'; %>
<div class="vcard<%= v.enabled ? '' : ' off' %>" data-id="<%= v.id %>" data-display="<%= display %>">
<div class="vrow">
<input type="checkbox" role="switch" data-f="enabled" <%= v.enabled ? 'checked' : '' %> title="On: this variation can play">
<input class="vname" data-f="name" value="<%= v.name %>" title="Variation name (shown on the cassette / video box)">
<select data-f="rarity" style="width:auto;" title="Rarity: how often it is picked compared to the other enabled variations">
<% for (const [k, r] of Object.entries(rarity)) { %><option value="<%= k %>" <%= v.rarity === k ? 'selected' : '' %>><%= r.label %></option><% } %>
</select>
<span class="chance" data-chance></span>
<button type="button" class="outline btn-sm" data-test title="Show it on the overlay (saves first)">Test</button>
<button type="button" class="outline btn-sm danger" data-del title="Delete this variation">Delete</button>
<button type="button" class="btn-sm danger" data-del-confirm hidden>Really delete</button>
</div>
<div class="vrow">
<span class="seg" title="Cassette: tape alert with sound. Sound only: just the sound. Video: full-screen video on the ?parts=video overlay">
<% for (const [val, lbl] of [['cassette', 'Cassette'], ['sound', 'Sound only'], ['video', 'Video']]) { %>
<label><input type="radio" name="display-<%= v.id %>" data-f="display" value="<%= val %>" <%= display === val ? 'checked' : '' %>><%= lbl %></label>
<% } %>
</span>
<span class="field" title="Volume of the sound / video">
<input type="range" min="0" max="1" step="0.05" data-f="volume" value="<%= v.volume %>"><span class="vol-out" data-vol></span>
</span>
</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>
<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>
<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>
</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>
<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>
<video class="preview" data-preview hidden controls playsinline></video>
</div>
<% } %>
<form method="POST" action="/redeems/variation" data-add style="margin:.6rem 0 0;">
<input type="hidden" name="kind" value="<%= t.kind %>">
<input type="hidden" name="key" value="<%= t.key %>">
<input type="hidden" name="title" value="<%= t.title %>">
<button type="submit" class="outline btn-sm" title="Add a variation (saves your changes first)">+ Add variation</button>
</form>
</details>
<% } %>
<% } %>
<script>
(() => {
const RARITY = <%- JSON.stringify(rarity) %>;
const DRAFT_KEY = 'redeemsDraft', OPEN_KEY = 'redeemsOpen';
const stateEl = document.getElementById('save-state');
const dirty = new Set();
const cards = () => [...document.querySelectorAll('.vcard')];
const card = id => document.querySelector(`.vcard[data-id="${id}"]`);
const store = { get(k) { try { return JSON.parse(localStorage.getItem(k)); } catch { return null; } },
set(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
del(k) { try { localStorage.removeItem(k); } catch {} } };
function state(text, cls) { stateEl.textContent = text; stateEl.className = 'state ' + cls; }
function refreshState() { dirty.size ? state(`${dirty.size} unsaved change${dirty.size === 1 ? '' : 's'}`, 'dirty') : state('All saved', 'ok'); }
// read one card's values
function collect(c) {
const o = { id: c.dataset.id };
c.querySelectorAll('[data-f]').forEach(el => {
const f = el.dataset.f;
if (el.type === 'radio') { if (el.checked) o[f] = el.value; }
else if (el.type === 'checkbox') o[f] = el.checked;
else o[f] = el.value;
});
return o;
}
function apply(c, o) {
c.querySelectorAll('[data-f]').forEach(el => {
const f = el.dataset.f; if (!(f in o)) return;
if (el.type === 'radio') el.checked = el.value === o[f];
else if (el.type === 'checkbox') el.checked = !!o[f];
else el.value = o[f];
});
sync(c);
}
// card look: display mode, off, volume, sticker thumbnail; chances for the whole trigger
function sync(c) {
const o = collect(c);
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';
chances(c.closest('[data-trigger]'));
}
function chances(t) {
const cs = [...t.querySelectorAll('.vcard')].map(c => [c, collect(c)]);
const total = cs.filter(([, o]) => o.enabled).reduce((s, [, o]) => s + (RARITY[o.rarity]?.weight || 1), 0);
for (const [c, o] of cs) c.querySelector('[data-chance]').textContent = o.enabled && total ? Math.round(100 * (RARITY[o.rarity]?.weight || 1) / total) + '% chance' : 'off';
const n = cs.filter(([, o]) => o.enabled).length, el = t.querySelector('[data-count]');
if (el && cs.length) el.textContent = `${n}/${cs.length} on`;
}
function markDirty(c) {
dirty.add(c.dataset.id); c.classList.add('dirty');
const d = store.get(DRAFT_KEY) || { at: Date.now(), cards: {} };
d.at = Date.now(); d.cards[c.dataset.id] = collect(c); store.set(DRAFT_KEY, d);
refreshState();
}
cards().forEach(c => {
sync(c);
c.addEventListener('input', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
c.addEventListener('change', e => { if (e.target.dataset.f) { sync(c); markDirty(c); } });
});
// --- save (button, Ctrl+S, and before anything that reloads the page) ---
let saving = null;
async function save() {
if (saving) return saving;
if (!dirty.size) return true;
const ids = [...dirty];
state('Saving…', 'dirty');
saving = (async () => {
try {
const r = await fetch('/redeems/save', { method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ variations: ids.map(id => collect(card(id))) }) });
const j = await r.json().catch(() => ({}));
if (!r.ok || !j.ok) throw new Error(j.error || r.status);
ids.forEach(id => { dirty.delete(id); card(id)?.classList.remove('dirty'); });
if (!dirty.size) store.del(DRAFT_KEY);
state(`Saved ✓ ${new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}`, 'ok');
return true;
} catch (e) { state('Save failed: ' + e.message + ' (your changes are kept)', 'err'); return false; }
finally { saving = null; }
})();
return saving;
}
document.getElementById('save-all').addEventListener('click', save);
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { e.preventDefault(); save(); }
});
// add variation: save first, then the normal form post (reloads the page)
document.querySelectorAll('[data-add]').forEach(f => f.addEventListener('submit', async e => {
e.preventDefault(); if (await save()) { rememberOpen(f.closest('[data-trigger]').id, true); f.submit(); }
}));
// delete: two steps, no browser dialog; saves other changes first
document.querySelectorAll('[data-del]').forEach(b => b.addEventListener('click', () => {
const c = b.parentElement.querySelector('[data-del-confirm]');
b.hidden = true; c.hidden = false;
setTimeout(() => { b.hidden = false; c.hidden = true; }, 4000);
}));
document.querySelectorAll('[data-del-confirm]').forEach(b => b.addEventListener('click', async () => {
const c = b.closest('.vcard'); dirty.delete(c.dataset.id);
const d = store.get(DRAFT_KEY); if (d) { delete d.cards[c.dataset.id]; store.set(DRAFT_KEY, d); }
if (!(await save())) return;
const f = document.createElement('form'); f.method = 'POST'; f.action = `/redeems/variation/${c.dataset.id}/delete`;
document.body.appendChild(f); f.submit();
}));
// tests: save first so the overlay shows what you see
const post = async (url, body) => {
if (!(await save())) return;
try {
const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
state(r.ok ? 'Sent to the overlay' : `Test failed (${r.status})`, r.ok ? 'ok' : 'err');
} catch (e) { state('Test failed: ' + e.message, 'err'); }
};
document.querySelectorAll('[data-test]').forEach(b => b.addEventListener('click', () => post(`/redeems/variation/${b.closest('.vcard').dataset.id}/test`)));
document.querySelectorAll('[data-test-trigger]').forEach(b => b.addEventListener('click', e => {
e.preventDefault(); post('/redeems/trigger/test', { kind: b.dataset.kind, key: b.dataset.key });
}));
// previews in the browser
let player = null;
document.querySelectorAll('[data-play-sound]').forEach(b => b.addEventListener('click', () => {
const c = b.closest('.vcard'), o = collect(c);
if (player) player.pause();
if (!o.sound) return state('No sound selected', 'err');
player = new Audio(o.sound); player.volume = parseFloat(o.volume) || 0.8;
player.play().catch(e => state('Could not play: ' + e.message, 'err'));
}));
document.querySelectorAll('[data-play-video]').forEach(b => b.addEventListener('click', () => {
const c = b.closest('.vcard'), o = collect(c), v = c.querySelector('[data-preview]');
if (!o.video) return state('No video selected', 'err');
if (!v.hidden && v.getAttribute('src') === o.video) { v.pause(); v.hidden = true; return; }
v.src = o.video; v.volume = parseFloat(o.volume) || 0.8; v.hidden = false; v.play().catch(() => {});
}));
// remember which triggers are open (survives the reload after add/delete)
function rememberOpen(id, open) { const s = new Set(store.get(OPEN_KEY) || []); open ? s.add(id) : s.delete(id); store.set(OPEN_KEY, [...s]); }
for (const id of store.get(OPEN_KEY) || []) { const d = document.getElementById(id); if (d) d.open = true; }
if (location.hash) { const d = document.getElementById(decodeURIComponent(location.hash.slice(1))); if (d) d.open = true; }
document.querySelectorAll('[data-trigger]').forEach(d => d.addEventListener('toggle', () => rememberOpen(d.id, d.open)));
// unsaved changes from a closed tab / crash: offer to restore (inline, no dialog)
const draft = store.get(DRAFT_KEY);
if (draft && draft.cards && Object.keys(draft.cards).some(id => card(id) && JSON.stringify(collect(card(id))) !== JSON.stringify(draft.cards[id]))) {
const bar = document.getElementById('draftbar');
document.getElementById('draft-when').textContent = new Date(draft.at).toLocaleString();
bar.hidden = false;
document.getElementById('draft-restore').onclick = () => {
for (const [id, o] of Object.entries(draft.cards)) { const c = card(id); if (c) { apply(c, o); markDirty(c); c.closest('[data-trigger]').open = true; } }
bar.hidden = true; state(`${dirty.size} restored change${dirty.size === 1 ? '' : 's'}: Save to keep them`, 'dirty');
};
document.getElementById('draft-discard').onclick = () => { store.del(DRAFT_KEY); bar.hidden = true; };
} else store.del(DRAFT_KEY);
})();
</script>