- 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>
403 lines
25 KiB
Text
403 lines
25 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; }
|
||
/* 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"],
|
||
.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">
|
||
<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">
|
||
<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>
|
||
<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">
|
||
<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>
|
||
<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) %>;
|
||
// 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();
|
||
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 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) {
|
||
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`;
|
||
}
|
||
|
||
// --- pickers ---
|
||
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[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: {} };
|
||
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>
|