Overlay: cassette redeems, emote effects, poll card, Hype Train bar, raid card

New overlay modules (taped-paper look, shared with the polaroid alerts):
- cassette.js: redeems as a cassette tape; rarity = shell colour (Ultra Rare gold
  with glow, foil and sparkles), reels spin for the sound's length, sticker corner.
- fx.js: Gigantify (viewer's emote grows giant), On-Screen Celebration (emote
  copies bounce around the screen), highlight / Message Effect (tall taped note).
- poll.js: live poll card with bars, countdown and a WINNER stamp.
- hypebar.js: persistent Hype Train strip (level, progress, time left).
- raidcard.js: silent raid send-off card that stays during the raid countdown.
- nowplaying.js: Feishin now-playing slip (not loaded yet, see overlay).

polaroid.js: shared queue now also drives cassettes/effects; test alerts replace
only other tests and never cut off real alerts; alerts stay up for the animation
+ 3 s or the sound's length; sound lengths measured in the browser for UI-picked
sounds; tip and Hype Train alerts; optional ALERTS_BASE for offline test pages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-20 23:18:15 +02:00
parent 8c649c5bce
commit 1766e37336
14 changed files with 774 additions and 18 deletions

View file

@ -1,8 +1,11 @@
/*
Polaroid alerts for the OBS overlay.
window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
window.PolaroidAlerts.reset() stop the current alert and clear the queue
window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
window.PolaroidAlerts.playTest(alert) test alert: replaces a showing/queued TEST alert at once,
but never interrupts or drops a real one (it queues behind it).
A real alert cuts off a test that is showing.
window.PolaroidAlerts.reset() stop the current alert and clear the queue
Alert shapes come from src/alerts.js:
{ type:'follow', user }
@ -11,19 +14,25 @@
{ type:'streak', user, streak }
{ type:'raid', user, viewers }
{ type:'bits', user|null, bits, message }
{ type:'tip', user, amount, currency, message } (StreamElements)
{ type:'hype', phase:'begin'|'level'|'end', level, golden, treasure, top } (Hype Train v2)
{ type:'redeem', kind, key, user, reward, variation, rarity, input, caption, sound (URL), volume, polaroid, art }
channel point rewards / Power-ups, configured on the dashboard Redeems page; drawn as a
cassette tape by cassette.js (polaroid:false = sound only, art = sticker URL)
Everything per event (art, caption, tape colour, badge, sound) is in describe() below.
*/
(function () {
// ===================== CONFIG =====================
const BASE = '/alerts/';
const ART = n => `${BASE}art/${n}`;
const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages
const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u;
const ART = n => /^(https?:)?\/\//.test(n) ? n : `${BASE}art/${n}`; // full URLs (e.g. Twitch avatars) pass through
const SND = n => `${BASE}sounds/${n}`;
const VOLUME = 0.8;
const TAPE = {
follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)',
gift:'rgba(150,215,180,.88)', streak:'rgba(246,206,110,.9)', raid:'rgba(250,170,120,.88)',
bits:'rgba(190,160,240,.88)',
bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.88)',
};
// bits: under BITS_MIN = no alert; otherwise the highest matching tier wins
@ -42,6 +51,7 @@
'duck-toy-sound.mp3':960, 'wow.mp3':2325, 'huh.mp3':1123, 'correct-answer.wav':1960, 'opatski.mp3':1416,
'we-do-a-little-trolling_80cJgd9.mp3':2691, 'windows-xp-startup_1ph012N.mp3':4911,
'run-vine-sound-effect.mp3':8280, 'TomDaTankLoud.mp3':10057, 'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3':2038,
'emotional-damage-meme.mp3':3369,
};
const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png',
@ -49,8 +59,8 @@
const RANGES = { photoTilt:[2,7], tape1:[-42,-18], tape2:[18,42], tapeX:[-12,12], tapeY:[-6,6],
heart:[-8,26], heartX:[-10,6], heartY:[-14,8], badge:[-18,14] };
const MIN_HOLD = 6000; // ms fully visible, at least
const SOUND_PAD = 1500; // ms after the sound ends
const AFTER_ANIM = 3000; // ms the finished polaroid stays up after its entrance animation
const SOUND_LEAD = 400; // ms after the photo starts dropping that the sound starts
const GAP = 600; // ms between queued alerts
// Event -> what the polaroid shows. null = no alert.
@ -89,6 +99,36 @@
return { art:'CharacterPolice.png', name:who, line:`is raiding with ${e.viewers} viewers!`,
tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' },
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 };
case 'tip': {
// StreamElements tip: amount in its own currency, extra hearts for bigger tips
let money;
try { money = new Intl.NumberFormat('en', { style:'currency', currency:e.currency || 'USD', maximumFractionDigits: e.amount % 1 ? 2 : 0 }).format(e.amount); }
catch { money = `${e.amount} ${e.currency || ''}`.trim(); }
const hearts = e.amount >= 50 ? 3 : e.amount >= 25 ? 2 : e.amount >= 10 ? 1 : 0;
return { art:'CharacterLoveEyes_Glasses.png', name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:'emotional-damage-meme.mp3',
tape:'rgba(246,206,110,.9)', badge:{ big:money, small:'tip', color:'#e0a21b' }, hearts,
phbg:'linear-gradient(#fff6dc,#fbe0a8)' };
}
case 'hype': {
// Hype Train: start / level up / end, HYPE Streamer, sounds picked from the library
const name = e.golden ? 'Golden Kappa Train' : e.treasure ? 'Treasure Train' : 'Hype Train';
const line = e.phase === 'begin' ? 'is leaving the station! choo choo 🚂'
: e.phase === 'level' ? `reached level ${e.level}!` : `ended at level ${e.level}! ♡`;
const sound = { begin:'/alerts/sounds/redeems/pro-gamer.mp3', level:'/alerts/sounds/redeems/toad-ya-hoo.mp3',
end:'/alerts/sounds/redeems/tadaaa.mp3' }[e.phase];
return { art:'CharacterHype2.png', name, line, tape: e.golden ? 'rgba(246,206,110,.95)' : TAPE.raid, sound,
msg: e.phase === 'end' && e.top?.length ? `thank you ${e.top.join(', ')}!` : null,
badge:{ big:e.level, small:'level', color: e.golden ? '#d4a017' : '#e0457b' }, hearts: e.phase === 'end' ? 2 : 0,
stack: e.phase === 'end' ? 2 : 0, phbg: e.golden ? 'linear-gradient(#fff4d0,#f6d77a)' : 'linear-gradient(#ffe6d6,#f8c8a8)' };
}
case 'redeem': {
// shown as a cassette tape (cassette.js); polaroid:false = sound only
const fill = t => String(t || '').replace(/\{reward\}/g, e.reward || '').replace(/\{variation\}/g, e.variation || '');
return { cassette: true, style: e.style || 'cassette', emote: e.emote || null, sticker: rebase(e.art) || null,
name: e.user || 'Someone', line: fill(e.caption || 'redeemed it! ♡'), msg: e.input,
title: e.variation || e.reward, sub: e.reward, rarity: e.rarity,
sound: e.sound || null, volume: e.volume, soundOnly: e.polaroid === false };
}
case 'bits': {
if (!(e.bits >= BITS_MIN)) return null;
const t = BITS_TIERS.find(t => e.bits >= t.min);
@ -119,16 +159,58 @@
Object.keys(SOUND_MS).forEach(n => { const a = new Audio(); a.preload = 'auto'; a.src = SND(n); });
}
// built-in sounds are file names, redeem sounds are URLs
const soundUrl = s => !s ? null : (s.startsWith('/') ? rebase(s) : SND(s));
const lengths = {};
// sound length in ms: known table, else measured once in the browser (max 3 s wait)
function soundLength(url) {
const base = decodeURIComponent(url.split('/').pop());
if (SOUND_MS[base]) return Promise.resolve(SOUND_MS[base]);
if (lengths[url] != null) return Promise.resolve(lengths[url]);
return new Promise(res => {
const a = new Audio(); a.preload = 'metadata';
const done = ms => { clearTimeout(t); res(lengths[url] = ms); };
const t = setTimeout(() => done(0), 3000);
a.addEventListener('loadedmetadata', () => done(isFinite(a.duration) ? a.duration * 1000 : 0), { once:true });
a.addEventListener('error', () => done(0), { once:true });
a.src = url;
});
}
const queue = [];
let busy = false, current = null, gen = 0;
function play(alert) {
const d = describe(alert);
if (!d) { console.log('[alerts] skipped', alert); return; }
d.test = !!alert.test;
if (!d.test) {
// a real alert is never delayed by tests: drop queued tests, cut a test that is on screen
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1);
if (current && current.test) skipCurrent();
}
queue.push(d);
if (!busy) next();
}
// stop what is on screen and carry on with the queue
function skipCurrent() {
gen++;
clearTimeout(current.timer);
if (current.audio) { current.audio.pause(); current.audio.currentTime = 0; }
current.anims.forEach(a => a.cancel());
current = null;
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide();
busy = false;
}
function playTest(alert) {
for (let i = queue.length - 1; i >= 0; i--) if (queue[i].test) queue.splice(i, 1); // older tests: gone
if (current && current.test) skipCurrent(); // a test on screen: cut it
play({ ...alert, test: true }); // a real one on screen: wait
}
function reset() {
gen++;
queue.length = 0;
@ -139,6 +221,7 @@
current = null;
}
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide();
busy = false;
}
@ -156,8 +239,32 @@
return `<div class="photo ${cls}"><div class="ph"><img src="${ART(art)}" alt=""></div>${inner}</div>`;
}
function show(d) {
async function show(d) {
const el = root();
const cur = current = { anims:[], timer:null, audio:null, test:!!d.test };
const url = soundUrl(d.sound);
const len = url ? await soundLength(url) : 0;
if (cur !== current) return; // skipped while measuring the sound
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message' }[d.style];
if (fx && !d.soundOnly && window.FxAlert) {
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? VOLUME })
.then(() => { if (current === cur) current = null; });
}
if (d.cassette && !d.soundOnly && window.CassetteAlert) {
return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? VOLUME })
.then(() => { if (current === cur) current = null; });
}
if (d.soundOnly) { // no picture: play the sound, hold the queue for its length
if (!url) return;
const a = cur.audio = new Audio(url); a.volume = d.volume ?? VOLUME;
a.play().catch(err => console.warn('[alerts] sound blocked:', err.message));
const wait = el.animate([{}, {}], { duration: Math.max(len, 500) });
cur.anims.push(wait);
return wait.finished.then(() => { if (current === cur) current = null; }).catch(() => {});
}
const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
const backs = Array.from({ length: d.stack || 0 }, (_, i) =>
photoHTML('back', BACK_ART[i % BACK_ART.length], '<div class="blank"></div>')).join('');
@ -166,7 +273,7 @@
el.innerHTML = backs + `
<div class="photo main" style="--tape:${d.tape}${d.phbg ? ';--phbg:' + d.phbg : ''}">
<div class="tape t1"></div><div class="tape t2"></div>
<div class="ph"><img src="${ART(d.art)}" alt=""></div>
<div class="ph${d.avatar ? ' avatar' : ''}"><img src="${ART(d.art)}" alt="">${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
<div class="cap"><span class="u" style="font-size:${nameSize}px">${esc(d.name)}</span>${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>
<img class="heart sticker" src="${ART('Heart.png')}" alt="">
${extraHearts}
@ -178,7 +285,7 @@
const main = q('.photo.main');
const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1);
const rot = dd => `rotate(${tilt + dd}deg)`;
const anims = [];
const anims = cur.anims;
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); anims.push(a); return a; };
// fanned stack behind the main photo (multi-month subs, community gifts, raids)
@ -234,16 +341,16 @@
A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
{ delay:t0 + 1700, duration:700, easing:'ease-in-out' });
// sound as the photo lands; hold covers the whole sound
const hold = Math.max(MIN_HOLD, (SOUND_MS[d.sound] || 0) + SOUND_PAD);
const cur = current = { anims, timer:null, audio:null };
if (d.sound) {
const a = new Audio(SND(d.sound)); a.volume = VOLUME;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + 400);
// stays up: entrance animation + 3 s, or until the sound has finished if that is later
const animEnd = t0 + 2400; // caption done writing
const soundEnd = url ? t0 + SOUND_LEAD + len : 0;
if (url) {
const a = new Audio(url); a.volume = d.volume ?? VOLUME;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD);
}
// 5. exit: lift and drop away
const exitAt = t0 + 2400 + hold;
const exitAt = Math.max(animEnd + AFTER_ANIM, soundEnd);
const exit = A(el, [
{ transform:'translateY(0) rotate(0) scale(1)', opacity:1 },
{ transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 },
@ -255,6 +362,6 @@
.catch(() => {}); // cancelled by reset()
}
window.PolaroidAlerts = { play, reset, describe };
window.PolaroidAlerts = { play, playTest, reset, describe };
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
})();