Overlay - public/alerts/polaroid.js + .css: animated polaroid (photo drops in, tape and heart stick on, caption writes in), randomized angles, per-event art, caption, tape colour, badge and sound, fanned photo stack for multi-month subs / community gifts / raids, and a queue so alerts never overlap. - Bits: no alert under 5; sound tiers at 5/50/75/100/150/250. - Watch streaks are read from chat (USERNOTICE viewermilestone) and reported to the server over the overlay WebSocket. Server - Subscribe to channel.chat.notification instead of channel.subscribe / subscription.message / subscription.gift / channel.raid: one event with Prime, months bought at once, gift recipient, resub message and community gift totals. Per-recipient gift notices of a gift bomb are skipped, so a bomb is one alert (was N+1). Needs the user:read:chat scope (log in again). - src/alerts.js maps Twitch events to alerts, broadcasts them and still runs them through dispatch (activity log + existing actions). - EventSub starts on boot from the stored login (alerts survive restarts), validates the token hourly and refreshes it on expiry or 401, follows session_reconnect without dropping events, and reconnects when keepalives stop. - The overlay WebSocket only accepts chat_notice messages from connections that pass the overlay UUID; streak notices are deduped by message id. Dashboard - Twitch connection status and a test button per alert (POST /alerts/test/:key). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
260 lines
13 KiB
JavaScript
260 lines
13 KiB
JavaScript
/*
|
||
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
|
||
|
||
Alert shapes come from src/alerts.js:
|
||
{ type:'follow', user }
|
||
{ type:'sub', user, tier, prime, months, duration, message }
|
||
{ type:'gift', user|null, total, recipient, tier }
|
||
{ type:'streak', user, streak }
|
||
{ type:'raid', user, viewers }
|
||
{ type:'bits', user|null, bits, message }
|
||
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 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: under BITS_MIN = no alert; otherwise the highest matching tier wins
|
||
const BITS_MIN = 5;
|
||
const BITS_TIERS = [
|
||
{ min:250, sound:'TomDaTankLoud.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:3 },
|
||
{ min:150, sound:'run-vine-sound-effect.mp3', art:'CharacterHype2.png', badge:'#e0457b', hearts:2 },
|
||
{ min:100, sound:'windows-xp-startup_1ph012N.mp3', art:'CharacterHype2.png', badge:'#9b6bdc', hearts:1 },
|
||
{ min:75, sound:'we-do-a-little-trolling_80cJgd9.mp3', art:'CharacterCool.png', badge:'#9b6bdc', hearts:0 },
|
||
{ min:50, sound:'opatski.mp3', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 },
|
||
{ min:5, sound:'correct-answer.wav', art:'CharacterCool.png', badge:'#8a8aa8', hearts:0 },
|
||
];
|
||
|
||
// sound lengths in ms (ffprobe), so the alert stays up for the whole sound
|
||
const SOUND_MS = {
|
||
'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,
|
||
};
|
||
|
||
const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png',
|
||
'CharacterLynx.png','CharacterCool.png','CharacterSelfie.png'];
|
||
|
||
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 GAP = 600; // ms between queued alerts
|
||
|
||
// Event -> what the polaroid shows. null = no alert.
|
||
function describe(e) {
|
||
const who = e.user || (e.type === 'gift' ? 'An anonymous gifter' : 'Someone');
|
||
switch (e.type) {
|
||
case 'follow':
|
||
return { art:'CharacterSelfie.png', name:who, line:'just followed! ♡', tape:TAPE.follow, sound:'duck-toy-sound.mp3' };
|
||
case 'sub': {
|
||
const months = e.months || 1, dur = e.duration || 1, multi = dur > 1;
|
||
const tier = e.prime ? '' : ({ '2000':'Tier 2', '3000':'Tier 3' }[e.tier] || '');
|
||
const atTier = tier ? ` at ${tier}` : '';
|
||
let line;
|
||
if (multi) line = `subscribed${atTier} for ${dur} months at once! ♡`;
|
||
else if (e.prime) line = months > 1 ? `resubscribed with Prime for ${months} months! ♛` : 'subscribed with Prime! ♛';
|
||
else if (months > 1) line = `resubscribed${atTier} for ${months} months! ♡`;
|
||
else line = `just subscribed${atTier}! ♡`;
|
||
const art = e.prime ? 'CharacterQueen_Main.png' : (months > 1 || multi ? 'CharacterInLove.png' : 'CharacterHeart.png');
|
||
return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:'wow.mp3',
|
||
stack: multi ? Math.min(dur - 1, 5) : 0,
|
||
badge: multi ? { big:`${dur}×`, small:'months' } : months > 1 ? { big:months, small:'months' } : null,
|
||
phbg: e.prime ? 'linear-gradient(#e3f2ff,#bcdcf5)' : null };
|
||
}
|
||
case 'gift': {
|
||
const n = e.total || 1;
|
||
return { art:'CharacterGift.png', name:who,
|
||
line: n > 1 ? `gifted ${n} subs to the community! ♡`
|
||
: (e.recipient ? `gifted a sub to ${e.recipient}! ♡` : 'gifted a sub! ♡'),
|
||
tape:TAPE.gift, sound:'wow.mp3', stack: n > 1 ? Math.min(n - 1, 3) : 0,
|
||
badge: n > 1 ? { big:`×${n}`, small:'subs' } : null, phbg:'linear-gradient(#e2f6ea,#bfe6cf)' };
|
||
}
|
||
case 'streak':
|
||
return { art:'CharacterTime.png', name:who, line:`is on a ${e.streak}-stream watch streak!`,
|
||
tape:TAPE.streak, sound:'huh.mp3', badge:{ big:e.streak, small:'streams' }, phbg:'linear-gradient(#fff4d6,#f7deb0)' };
|
||
case 'raid':
|
||
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 'bits': {
|
||
if (!(e.bits >= BITS_MIN)) return null;
|
||
const t = BITS_TIERS.find(t => e.bits >= t.min);
|
||
return { art:t.art, name:who, line:`cheered ${e.bits} bits!`, msg:e.message, tape:TAPE.bits, sound:t.sound,
|
||
badge:{ big:e.bits, small:'bits', color:t.badge }, hearts:t.hearts, phbg:'linear-gradient(#efe6ff,#d7c6f5)' };
|
||
}
|
||
}
|
||
return null;
|
||
}
|
||
|
||
// ===================== ENGINE =====================
|
||
const rnd = Math.random;
|
||
const between = ([a, b]) => a + rnd() * (b - a);
|
||
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[c]));
|
||
|
||
let el = null;
|
||
function root() {
|
||
if (!el) { el = document.createElement('div'); el.id = 'polaroid-alert'; document.body.appendChild(el); }
|
||
return el;
|
||
}
|
||
|
||
// preload images and sounds so the first alert of the stream is not blank or late
|
||
function preload() {
|
||
const imgs = new Set([...BACK_ART, 'Heart.png', 'CharacterSelfie.png', 'CharacterHeart.png',
|
||
'CharacterQueen_Main.png', 'CharacterInLove.png', 'CharacterGift.png', 'CharacterTime.png',
|
||
'CharacterPolice.png', 'CharacterHype2.png']);
|
||
imgs.forEach(n => { new Image().src = ART(n); });
|
||
Object.keys(SOUND_MS).forEach(n => { const a = new Audio(); a.preload = 'auto'; a.src = SND(n); });
|
||
}
|
||
|
||
const queue = [];
|
||
let busy = false, current = null, gen = 0;
|
||
|
||
function play(alert) {
|
||
const d = describe(alert);
|
||
if (!d) { console.log('[alerts] skipped', alert); return; }
|
||
queue.push(d);
|
||
if (!busy) next();
|
||
}
|
||
|
||
function reset() {
|
||
gen++;
|
||
queue.length = 0;
|
||
if (current) {
|
||
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';
|
||
busy = false;
|
||
}
|
||
|
||
async function next() {
|
||
const d = queue.shift();
|
||
if (!d) { busy = false; return; }
|
||
busy = true;
|
||
const my = gen;
|
||
await show(d);
|
||
if (my !== gen) return;
|
||
setTimeout(() => { if (my === gen) next(); }, GAP);
|
||
}
|
||
|
||
function photoHTML(cls, art, inner) {
|
||
return `<div class="photo ${cls}"><div class="ph"><img src="${ART(art)}" alt=""></div>${inner}</div>`;
|
||
}
|
||
|
||
function show(d) {
|
||
const el = root();
|
||
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('');
|
||
const extraHearts = Array.from({ length: d.hearts || 0 }, () =>
|
||
`<img class="heart extra sticker" src="${ART('Heart.png')}" alt="">`).join('');
|
||
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="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}
|
||
${d.badge ? `<div class="badge" style="${d.badge.color ? '--badge:' + d.badge.color : ''}">${esc(d.badge.big)}<small>${esc(d.badge.small)}</small></div>` : ''}
|
||
</div>`;
|
||
el.style.visibility = 'visible';
|
||
|
||
const q = s => el.querySelector(s);
|
||
const main = q('.photo.main');
|
||
const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1);
|
||
const rot = dd => `rotate(${tilt + dd}deg)`;
|
||
const 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)
|
||
const backEls = [...el.querySelectorAll('.photo.back')];
|
||
const t0 = backEls.length ? 120 * backEls.length + 150 : 0;
|
||
backEls.forEach((b, i) => {
|
||
const ang = 4 + i * 4 + between([-2, 2]), dx = 24 + i * 26 + between([-4, 4]), dy = i * 5 + between([-4, 4]);
|
||
A(b, [
|
||
{ transform:`translate(${dx}px,${dy - 150}px) rotate(${ang * 2}deg)`, opacity:0 },
|
||
{ transform:`translate(${dx}px,${dy}px) rotate(${ang}deg)`, opacity:1 },
|
||
], { delay:i * 120, duration:450, easing:'cubic-bezier(.2,.8,.3,1)' });
|
||
});
|
||
|
||
// 1. photo drops in
|
||
A(main, [
|
||
{ transform:`translateY(-160px) rotate(${tilt * -2.5}deg) scale(1.15)`, opacity:0 },
|
||
{ transform:`translateY(10px) ${rot(tilt > 0 ? 1.5 : -1.5)} scale(.99)`, opacity:1, offset:.7 },
|
||
{ transform:`translateY(0) ${rot(0)} scale(1)`, opacity:1 },
|
||
], { delay:t0, duration:750, easing:'cubic-bezier(.2,.8,.3,1)' });
|
||
|
||
const nudge = (at, dx) => A(main, [
|
||
{ transform:`translateY(0) ${rot(0)}` }, { transform:`translateY(3px) ${rot(dx)}` }, { transform:`translateY(0) ${rot(0)}` },
|
||
], { delay:at, duration:220, easing:'ease-out', fill:'none' });
|
||
|
||
// 2. tapes press on
|
||
const tapeT = (x, y, a, s) => `translate(${x}px,${y}px) rotate(${a}deg) scale(${s})`;
|
||
const stick = (node, a, at) => {
|
||
const x = between(RANGES.tapeX), y = between(RANGES.tapeY);
|
||
A(node, [
|
||
{ transform:tapeT(x, y - 30, a - 8, 1.35), opacity:0 },
|
||
{ transform:tapeT(x, y, a, .94), opacity:1, offset:.75 },
|
||
{ transform:tapeT(x, y, a, 1), opacity:1 },
|
||
], { delay:at, duration:260, easing:'cubic-bezier(.3,.7,.4,1)' });
|
||
};
|
||
stick(q('.t1'), between(RANGES.tape1), t0 + 800); nudge(t0 + 1000, -.6);
|
||
stick(q('.t2'), between(RANGES.tape2), t0 + 1080); nudge(t0 + 1280, .6);
|
||
|
||
// 3. stickers slap on
|
||
const slap = (node, at, x, y, a) => A(node, [
|
||
{ transform:`translate(${x}px,${y}px) rotate(${a - 40}deg) scale(0)`, opacity:0 },
|
||
{ transform:`translate(${x}px,${y}px) rotate(${a + 6}deg) scale(1.25)`, opacity:1, offset:.6 },
|
||
{ transform:`translate(${x}px,${y}px) rotate(${a - 2}deg) scale(.92)`, opacity:1, offset:.82 },
|
||
{ transform:`translate(${x}px,${y}px) rotate(${a}deg) scale(1)`, opacity:1 },
|
||
], { delay:at, duration:420, easing:'ease-out' });
|
||
slap(q('.heart:not(.extra)'), t0 + 1450, between(RANGES.heartX), between(RANGES.heartY), between(RANGES.heart));
|
||
nudge(t0 + 1650, tilt > 0 ? .8 : -.8);
|
||
[...el.querySelectorAll('.heart.extra')].forEach((h, i) =>
|
||
slap(h, t0 + 1600 + i * 160, between([-20, 10]), -110 - i * 95 + between([-15, 15]), between([-25, 25])));
|
||
const badge = q('.badge');
|
||
if (badge) slap(badge, t0 + 1250, 0, 0, between(RANGES.badge));
|
||
|
||
// 4. caption writes in
|
||
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);
|
||
}
|
||
|
||
// 5. exit: lift and drop away
|
||
const exitAt = t0 + 2400 + hold;
|
||
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 },
|
||
{ transform:`translateY(140px) rotate(${tilt > 0 ? 14 : -14}deg) scale(.9)`, opacity:0 },
|
||
], { delay:exitAt, duration:650, easing:'ease-in' });
|
||
|
||
return exit.finished
|
||
.then(() => { el.style.visibility = 'hidden'; anims.forEach(a => a.cancel()); if (current === cur) current = null; })
|
||
.catch(() => {}); // cancelled by reset()
|
||
}
|
||
|
||
window.PolaroidAlerts = { play, reset, describe };
|
||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
|
||
})();
|