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

@ -0,0 +1,40 @@
/* Cassette tape alert for redeems (see cassette.js). Same corner as the polaroid; they share one queue. */
#cassette-alert { --ink:#3a2a20; --red:#b74347; position:fixed; left:85px; top:110px; width:440px; visibility:hidden; z-index:50; }
#cassette-alert * { box-sizing:border-box; }
#cassette-alert.r-common { --shell:#f3ead9; --shell2:#e6dac3; --edge:#8a7558; --band:#f4a0a8; --bandtxt:#7a2f3a; }
#cassette-alert.r-uncommon { --shell:#cdeedd; --shell2:#b5e2cb; --edge:#4f8a6b; --band:#7fcfa6; --bandtxt:#1f5a3c; }
#cassette-alert.r-rare { --shell:#ddd0f4; --shell2:#cbb9ee; --edge:#6b54a8; --band:#a88be0; --bandtxt:#ffffff; }
#cassette-alert.r-ultra { --shell:#f6d77a; --shell2:#eec456; --edge:#9a6a10; --band:#3c2006; --bandtxt:#f6d77a; }
#cassette-alert .tape-wrap { position:relative; width:440px; height:282px; filter:drop-shadow(0 14px 22px rgba(0,0,0,.45)); }
#cassette-alert.r-ultra .tape-wrap { filter:drop-shadow(0 0 16px #ffd76a) drop-shadow(0 0 4px #fff2c0) drop-shadow(0 14px 22px rgba(0,0,0,.45)); }
#cassette-alert svg { position:absolute; inset:0; width:100%; height:100%; overflow:visible; }
#cassette-alert .reel-hub, #cassette-alert .wound { transform-box:fill-box; transform-origin:center; }
#cassette-alert .band { position:absolute; left:34px; right:34px; top:24px; height:32px; display:flex; align-items:center;
justify-content:space-between; padding:0 14px; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:var(--bandtxt); }
#cassette-alert .title { position:absolute; left:40px; right:40px; top:58px; text-align:center; font:700 40px/1 'Caveat', cursive;
color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#cassette-alert .sub { position:absolute; left:40px; right:40px; top:156px; text-align:center; font:700 22px/1 'Caveat', cursive;
color:#7a6656; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
/* per-redeem sticker, bottom-right corner; any shape fits inside 150x125 */
#cassette-alert .stk { position:absolute; right:-50px; top:150px; width:175px; height:150px; display:flex; align-items:center; justify-content:center; }
#cassette-alert .stk img { max-width:175px; max-height:150px; transform:rotate(10deg);
filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 5px 8px rgba(0,0,0,.35)); }
#cassette-alert .foil { position:absolute; inset:0; border-radius:20px; pointer-events:none; opacity:0;
background:linear-gradient(115deg,#0000 35%,#fff9 48%,#fff3 52%,#0000 62%); mix-blend-mode:screen; }
#cassette-alert .spark { position:absolute; width:44px; height:44px; opacity:0; pointer-events:none; background:#fffbe6;
clip-path:polygon(50% 0,60% 40%,100% 50%,60% 60%,50% 100%,40% 60%,0 50%,40% 40%); filter:drop-shadow(0 0 6px #fff4b0); }
#cassette-alert .strip { position:relative; margin:-6px 0 0 30px; display:inline-block; max-width:400px; padding:8px 22px 10px;
background:#fffdf7; transform:rotate(-2deg); box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); }
#cassette-alert .strip .u { color:var(--red); }
#cassette-alert .strip .msg { display:block; font-size:22px; color:#7a6656; margin-top:4px;
overflow:hidden; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; }
#cassette-alert .strip:before, #cassette-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px;
background:rgba(201,182,228,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); }
#cassette-alert .strip:before { left:-22px; transform:rotate(-28deg); }
#cassette-alert .strip:after { right:-22px; transform:rotate(24deg); }

123
public/alerts/cassette.js Normal file
View file

@ -0,0 +1,123 @@
/*
Cassette tape renderer for redeem alerts. Called by polaroid.js (shared queue):
window.CassetteAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when ejected)
d: { title (variation), sub (reward), rarity, sticker (URL), name (user), line (strip text), msg (viewer input) }
cur: { anims, timer, audio } from polaroid.js, so reset/skip can stop it.
Timeline: slides in (0.7 s), sticker + strip pop on, reels spin and tape winds over the sound's length,
stays animation + 3 s or until the sound ends, then ejects upward.
*/
(function () {
const AFTER_ANIM = 3000, SOUND_LEAD = 600, ANIM_END = 1200;
const DEFAULT_STICKER = (window.ALERTS_BASE || '/alerts/') + 'stickers/default-sticker.png';
const RAR = { common:['r-common','COMMON'], uncommon:['r-uncommon','UNCOMMON'], rare:['r-rare','★ RARE'], ultra_rare:['r-ultra','★ ULTRA RARE ★'] };
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
const between = (a, b) => a + Math.random() * (b - a);
let el = null;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'cassette-alert'; document.body.appendChild(el); }
return el;
}
function reel(cx, id) {
const teeth = Array.from({ length: 6 }, (_, i) =>
`<rect x="${cx - 3}" y="109" width="6" height="8" rx="1.5" fill="#cfc6bb" transform="rotate(${i * 60} ${cx} 126)"/>`).join('');
return `<circle class="wound" data-id="${id}-tape" cx="${cx}" cy="126" r="44" fill="#4a3426"/>
<g class="reel-hub" data-id="${id}"><circle cx="${cx}" cy="126" r="19" fill="#fffdf7" stroke="#bdb3a6" stroke-width="2"/>${teeth}
<circle cx="${cx}" cy="126" r="5" fill="#bdb3a6"/></g>`;
}
function svg() {
const uid = 'c' + Math.random().toString(36).slice(2, 8);
return `<svg viewBox="0 0 440 282" xmlns="http://www.w3.org/2000/svg">
<defs><clipPath id="${uid}w"><rect x="112" y="98" width="216" height="56" rx="28"/></clipPath>
<pattern id="${uid}l" width="10" height="16" patternUnits="userSpaceOnUse"><rect y="15" width="10" height="1" fill="#0000001a"/></pattern></defs>
<rect x="3" y="3" width="434" height="276" rx="20" fill="var(--shell)" stroke="var(--edge)" stroke-width="3"/>
<rect x="14" y="14" width="412" height="200" rx="12" fill="none" stroke="var(--edge)" stroke-opacity=".25" stroke-width="2"/>
${[[22,22],[418,22],[22,260],[418,260]].map(([x, y]) => `<circle cx="${x}" cy="${y}" r="6" fill="var(--shell2)" stroke="var(--edge)" stroke-width="1.5"/><path d="M${x-3} ${y}h6M${x} ${y-3}v6" stroke="var(--edge)" stroke-width="1.4"/>`).join('')}
<rect x="30" y="22" width="380" height="166" rx="8" fill="#fffdf7"/>
<rect x="30" y="22" width="380" height="166" rx="8" fill="url(#${uid}l)"/>
<rect x="30" y="22" width="380" height="36" rx="8" fill="var(--band)"/><rect x="30" y="46" width="380" height="12" fill="var(--band)"/>
<rect x="108" y="94" width="224" height="64" rx="32" fill="#2b2230" stroke="var(--edge)" stroke-width="2"/>
<g clip-path="url(#${uid}w)"><rect x="112" y="98" width="216" height="56" fill="#3a2f40"/>
${reel(160, 'reelL')}${reel(280, 'reelR')}
<rect x="150" y="150" width="140" height="4" fill="#4a3426"/><rect x="112" y="98" width="216" height="20" fill="#ffffff10"/></g>
<path d="M96 279 L118 220 H322 L344 279 Z" fill="var(--shell2)" stroke="var(--edge)" stroke-width="2.5" stroke-linejoin="round"/>
${[148,180,260,292].map(x => `<circle cx="${x}" cy="252" r="7" fill="#2b2230"/>`).join('')}
<rect x="206" y="240" width="28" height="22" rx="4" fill="#2b2230"/>
</svg>`;
}
function show(d, cur, { url, len, volume }) {
const el = root();
const [cls, label] = RAR[d.rarity] || RAR.common;
const ultra = d.rarity === 'ultra_rare';
el.className = cls;
el.innerHTML = `
<div class="tape-wrap">${svg()}
<div class="band"><span>SIDE A</span><span>${label}</span></div>
<div class="title">${esc(d.title)}</div>
<div class="sub">${d.sub && d.sub !== d.title ? esc(d.sub) : ''}</div>
<div class="stk"><img src="${esc(d.sticker || DEFAULT_STICKER)}" alt=""></div>
${ultra ? '<div class="foil"></div>' + '<div class="spark"></div>'.repeat(6) : ''}
</div>
<div class="strip"><span class="u">${esc(d.name)}</span> ${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>`;
el.style.visibility = 'visible';
const q = s => el.querySelector(s);
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; };
const tilt = between(-4, 4);
A(q('.tape-wrap'), [
{ transform:'translateX(-620px) rotate(-14deg)', opacity:0 },
{ transform:`translateX(18px) rotate(${tilt + 2}deg)`, opacity:1, offset:.72 },
{ transform:`translateX(-4px) rotate(${tilt - .6}deg)`, offset:.88 },
{ transform:`translateX(0) rotate(${tilt}deg)`, opacity:1 },
], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)' });
A(q('.stk'), [
{ transform:'rotate(-30deg) scale(0)', opacity:0 },
{ transform:'rotate(8deg) scale(1.2)', opacity:1, offset:.6 },
{ transform:'rotate(0deg) scale(1)', opacity:1 },
], { delay:650, duration:380, easing:'ease-out' });
A(q('.strip'), [
{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 },
{ transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 },
], { delay:850, duration:320, easing:'cubic-bezier(.3,.7,.4,1)' });
// reels spin and tape winds while the sound plays
const playMs = Math.max(len, 600);
const turns = Math.round(playMs / 1000 * 540);
['reelL', 'reelR'].forEach(id => A(q(`[data-id="${id}"]`), [{ transform:'rotate(0deg)' }, { transform:`rotate(${turns}deg)` }],
{ delay:SOUND_LEAD, duration:playMs, easing:'linear', fill:'none' }));
A(q('[data-id="reelL-tape"]'), [{ transform:'scale(1)' }, { transform:'scale(.55)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' });
A(q('[data-id="reelR-tape"]'), [{ transform:'scale(.55)' }, { transform:'scale(1)' }], { delay:SOUND_LEAD, duration:playMs, easing:'linear' });
A(q('.tape-wrap'), [{ translate:'0 0' }, { translate:'0 -2px' }, { translate:'0 0' }],
{ delay:SOUND_LEAD, duration:420, iterations:Math.ceil(playMs / 420), easing:'ease-in-out', fill:'none', composite:'add' });
if (ultra) {
A(q('.foil'), [{ opacity:0 }, { opacity:1, offset:.2 }, { opacity:1, offset:.8 }, { opacity:0 }],
{ delay:700, duration:1400, iterations:3, easing:'ease-in-out', fill:'none' });
el.querySelectorAll('.spark').forEach((s, i) => {
s.style.left = `${between(10, 410)}px`; s.style.top = `${between(-10, 250)}px`;
A(s, [{ opacity:0, transform:'scale(0) rotate(0deg)' }, { opacity:1, transform:'scale(1) rotate(45deg)', offset:.5 }, { opacity:0, transform:'scale(0) rotate(90deg)' }],
{ delay:800 + i * 230, duration:900, iterations:4, fill:'none' });
});
}
if (url) {
const a = new Audio(url); a.volume = volume;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
}
const exitAt = Math.max(ANIM_END + AFTER_ANIM, url ? SOUND_LEAD + len : 0);
const exit = A(el, [
{ transform:'translateY(0)', opacity:1 },
{ transform:'translateY(14px)', opacity:1, offset:.2 },
{ transform:'translateY(-420px) rotate(-8deg)', opacity:0 },
], { delay:exitAt, duration:600, easing:'cubic-bezier(.5,0,.8,.4)' });
return exit.finished.then(() => { el.style.visibility = 'hidden'; cur.anims.forEach(a => a.cancel()); }).catch(() => {});
}
function hide() { if (el) el.style.visibility = 'hidden'; }
window.CassetteAlert = { show, hide };
})();

33
public/alerts/fx.css Normal file
View file

@ -0,0 +1,33 @@
/* Special redeem visuals (see fx.js): giant emote, bouncing emote celebration, highlighted message. */
#fx-alert { --ink:#3a2a20; --red:#b74347; position:fixed; inset:0; pointer-events:none; visibility:hidden; z-index:55; }
#fx-alert * { box-sizing:border-box; }
/* name strip, same paper + tape look as the cassette */
#fx-alert .strip { position:absolute; display:inline-block; max-width:520px; padding:8px 22px 10px; background:#fffdf7;
box-shadow:0 6px 14px rgba(0,0,0,.35); font:700 30px/1.05 'Caveat', cursive; color:var(--ink); }
#fx-alert .strip .u { color:var(--red); }
#fx-alert .strip:before, #fx-alert .strip:after { content:''; position:absolute; top:-10px; width:70px; height:24px;
background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); }
#fx-alert .strip:before { left:-22px; transform:rotate(-28deg); }
#fx-alert .strip:after { right:-22px; transform:rotate(24deg); }
/* gigantify */
#fx-alert .giant { position:absolute; left:85px; top:70px; width:380px; height:380px; display:flex; align-items:center; justify-content:center; }
#fx-alert .giant img { width:100%; height:100%; object-fit:contain; filter:drop-shadow(0 12px 24px rgba(0,0,0,.5)); }
/* celebration */
#fx-alert .bounce { position:absolute; left:0; top:0; will-change:transform; filter:drop-shadow(0 6px 10px rgba(0,0,0,.4)); }
/* highlighted message / message effect: big taped paper note, tall rather than wide */
#fx-alert .note { position:absolute; left:90px; top:90px; width:440px; min-height:300px; padding:30px 32px 34px; background:#fffdf7;
box-shadow:0 14px 30px rgba(0,0,0,.45); transform-origin:50% 0;
background-image:repeating-linear-gradient(#0000 0 51px, #0000001a 51px 52px); background-position:0 79px; }
#fx-alert .note:before, #fx-alert .note:after { content:''; position:absolute; top:-14px; width:120px; height:34px;
background:rgba(190,160,240,.85); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px);
box-shadow:0 1px 2px rgba(0,0,0,.15); }
#fx-alert .note:before { left:-34px; transform:rotate(-32deg); }
#fx-alert .note:after { right:-34px; transform:rotate(28deg); }
#fx-alert .note .who { font:700 34px/1.1 'Caveat', cursive; color:var(--ink); margin-bottom:10px; }
#fx-alert .note .who .u { color:var(--red); }
#fx-alert .note .text { font:700 46px/52px 'Caveat', cursive; color:var(--ink); word-wrap:break-word;
overflow:hidden; display:-webkit-box; -webkit-line-clamp:9; -webkit-box-orient:vertical; }

127
public/alerts/fx.js Normal file
View file

@ -0,0 +1,127 @@
/*
Special redeem visuals, called by polaroid.js (shared queue). Each returns a Promise that resolves when done.
FxAlert.giant(d, cur, snd) Gigantify Power-up: the viewer's emote grows huge, pulses while the sound plays
FxAlert.rain(d, cur, snd) On-Screen Celebration Power-up: copies of the emote bounce around the screen
FxAlert.message(d, cur, snd) Highlight my message / Message Effect: big taped paper note with the message
d: { name (user), line, msg, emote (image URL or null) }; snd: { url, len, volume }
cur: { anims, timer, audio } so reset/skip can stop it (anything with cancel() can go in anims).
*/
(function () {
const AFTER_ANIM = 3000, SOUND_LEAD = 300;
const FALLBACK = window.FX_FALLBACK || (window.ALERTS_BASE || '/alerts/') + 'art/Heart.png'; // when Twitch sends no emote
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
const between = (a, b) => a + Math.random() * (b - a);
let el = null;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'fx-alert'; document.body.appendChild(el); }
return el;
}
function hide() { if (el) { el.style.visibility = 'hidden'; el.innerHTML = ''; } }
function playSound(cur, { url, volume }) {
if (!url) return;
const a = new Audio(url); a.volume = volume;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
}
const imgTag = (src, cls = '') => `<img class="${cls}" src="${esc(src || FALLBACK)}" alt="" onerror="this.onerror=null;this.src='${FALLBACK}'">`;
const A = (cur, node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; };
const done = (cur, anim) => anim.finished.then(() => hide()).catch(() => {});
// ---- Gigantify: emote grows huge ----
function giant(d, cur, snd) {
const el = root();
el.innerHTML = `<div class="giant">${imgTag(d.emote)}</div>
<div class="strip" style="left:110px; top:470px; transform:rotate(-2deg)"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>`;
el.style.visibility = 'visible';
const g = el.querySelector('.giant'), strip = el.querySelector('.strip');
A(cur, g, [
{ transform:'scale(.12) rotate(-20deg)', opacity:0 },
{ transform:'scale(.3) rotate(-8deg)', opacity:1, offset:.25 },
{ transform:'scale(1.18) rotate(6deg)', offset:.7 },
{ transform:'scale(.95) rotate(-2deg)', offset:.85 },
{ transform:'scale(1) rotate(0deg)', opacity:1 },
], { duration:900, easing:'cubic-bezier(.2,.8,.3,1)' });
A(cur, strip, [{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 }, { transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 }],
{ delay:700, duration:320 });
const playMs = Math.max(snd.len, 600);
A(cur, g, [{ scale:'1' }, { scale:'1.06' }, { scale:'1' }], { delay:900, duration:600, iterations:Math.ceil(playMs / 600), fill:'none', composite:'add' });
playSound(cur, snd);
const exitAt = Math.max(1000 + AFTER_ANIM, SOUND_LEAD + snd.len);
return done(cur, A(cur, el, [{ opacity:1, transform:'scale(1)' }, { opacity:0, transform:'scale(.6)' }],
{ delay:exitAt, duration:450, easing:'ease-in' }));
}
// ---- Celebration: emotes bounce around the screen ----
function rain(d, cur, snd) {
const el = root(), N = 14, Wd = 1920, Ht = 1080;
el.innerHTML = Array.from({ length: N }, () => imgTag(d.emote, 'bounce')).join('') +
`<div class="strip" style="left:110px; top:90px; transform:rotate(-2deg)"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>`;
el.style.visibility = 'visible';
const strip = el.querySelector('.strip');
A(cur, strip, [{ transform:'translateY(-20px) rotate(-6deg) scale(1.1)', opacity:0 }, { transform:'translateY(0) rotate(-2deg) scale(1)', opacity:1 }],
{ delay:200, duration:320 });
const items = [...el.querySelectorAll('.bounce')].map(img => {
const s = between(90, 170);
img.style.width = img.style.height = `${s}px`;
// enter from a random screen edge
const side = Math.floor(Math.random() * 4);
const x = side === 0 ? -s : side === 1 ? Wd : between(0, Wd - s), y = side === 2 ? -s : side === 3 ? Ht : between(0, Ht - s);
const sp = between(420, 760), dir = Math.atan2(Ht / 2 - y, Wd / 2 - x) + between(-.7, .7);
return { img, s, x, y, vx: Math.cos(dir) * sp, vy: Math.sin(dir) * sp, r: between(0, 360), vr: between(-220, 220), inside: false };
});
const life = Math.max(1000 + AFTER_ANIM, SOUND_LEAD + snd.len);
let raf = 0, last = performance.now(), start = last, stopped = false, resolve;
const finished = new Promise(r => { resolve = r; });
function frame(now) {
if (stopped) return;
const dt = Math.min((now - last) / 1000, .05), t = now - start; last = now;
const leaving = t > life;
for (const o of items) {
if (leaving) { o.vy -= 1800 * dt; } // float away upward at the end
o.x += o.vx * dt; o.y += o.vy * dt; o.r += o.vr * dt;
if (!leaving) {
if (!o.inside && o.x > 0 && o.y > 0 && o.x < Wd - o.s && o.y < Ht - o.s) o.inside = true;
if (o.inside) {
if (o.x < 0 || o.x > Wd - o.s) { o.vx *= -1; o.x = Math.max(0, Math.min(Wd - o.s, o.x)); o.vr *= -1; }
if (o.y < 0 || o.y > Ht - o.s) { o.vy *= -1; o.y = Math.max(0, Math.min(Ht - o.s, o.y)); }
}
}
o.img.style.transform = `translate(${o.x}px,${o.y}px) rotate(${o.r}deg)`;
}
if (leaving && items.every(o => o.y < -o.s - 50)) { end(); return; }
if (leaving) strip.style.opacity = Math.max(0, 1 - (t - life) / 400);
raf = requestAnimationFrame(frame);
}
function end() { stopped = true; cancelAnimationFrame(raf); hide(); resolve(); }
cur.anims.push({ cancel() { stopped = true; cancelAnimationFrame(raf); resolve(); } });
raf = requestAnimationFrame(frame);
playSound(cur, snd);
return finished;
}
// ---- Highlight my message / Message Effect: big taped paper note ----
function message(d, cur, snd) {
const el = root();
const text = d.msg || '';
const tilt = between(-3, 3);
el.innerHTML = `<div class="note"><div class="who"><span class="u">${esc(d.name)}</span> ${esc(d.line)}</div>
<div class="text">${esc(text)}</div></div>`;
el.style.visibility = 'visible';
const n = el.querySelector('.note');
A(cur, n, [
{ transform:`translateY(-140px) rotate(${tilt * -3}deg) scale(1.12)`, opacity:0 },
{ transform:`translateY(8px) rotate(${tilt + 1}deg) scale(.99)`, opacity:1, offset:.7 },
{ transform:`translateY(0) rotate(${tilt}deg) scale(1)`, opacity:1 },
], { duration:650, easing:'cubic-bezier(.2,.8,.3,1)' });
A(cur, n.querySelector('.text'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
{ delay:550, duration:Math.min(1600, 300 + 18 * text.length), easing:'ease-in-out' });
playSound(cur, snd);
const read = 2000 + 70 * text.length; // time to read it
const exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len);
return done(cur, A(cur, el, [{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(140px) rotate(8deg)', opacity:0 }],
{ delay:exitAt, duration:500, easing:'ease-in' }));
}
window.FxAlert = { giant, rain, message, hide };
})();

14
public/alerts/hypebar.css Normal file
View file

@ -0,0 +1,14 @@
/* Hype Train progress strip (see hypebar.js): slim taped paper, top-left above the alert corner. */
#hype-bar { --ink:#3a2a20; --red:#b74347; --fill:#f8a070; position:fixed; left:85px; top:14px; width:440px; z-index:60; visibility:hidden;
padding:8px 16px 10px; background:#fffdf7; box-shadow:0 8px 18px rgba(0,0,0,.4); transform-origin:50% 0; }
#hype-bar.golden { --fill:#f2c040; background:#fff8e2; }
#hype-bar * { box-sizing:border-box; }
#hype-bar:before { content:''; position:absolute; left:50%; top:-12px; width:90px; height:26px; margin-left:-45px; transform:rotate(-2deg);
background:rgba(250,170,120,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 7px,#0000 7px 14px); }
#hype-bar.golden:before { background-color:rgba(246,206,110,.95); }
#hype-bar .top { display:flex; justify-content:space-between; align-items:baseline; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:var(--ink); }
#hype-bar .lv { color:var(--red); }
#hype-bar .time { font:700 22px 'Caveat', cursive; letter-spacing:0; color:#7a6656; }
#hype-bar .track { margin-top:5px; height:16px; border:3px solid var(--ink); border-radius:10px; background:#fff; overflow:hidden; }
#hype-bar .fill { height:100%; width:0; background-color:var(--fill); transition:width .7s cubic-bezier(.3,.7,.4,1);
background-image:repeating-linear-gradient(45deg,#fff5 0 6px,#0000 6px 12px); }

43
public/alerts/hypebar.js Normal file
View file

@ -0,0 +1,43 @@
/*
Hype Train progress strip. Persistent while a train runs; not part of the alert queue.
HypeBar.update(phase, train) phase: begin | progress | end
train: { id, level, progress, goal, total, expires_at, golden, treasure }
*/
(function () {
let el = null, timer = null, hideTimer = null, expires = 0, shownId = null;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'hype-bar'; document.body.appendChild(el);
el.innerHTML = '<div class="top"><span class="name"></span><span class="time"></span></div><div class="track"><div class="fill"></div></div>'; }
return el;
}
function tick() {
const s = Math.max(0, Math.round((expires - Date.now()) / 1000));
el.querySelector('.time').textContent = s ? `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} left` : '';
}
function update(phase, t) {
const el = root();
clearTimeout(hideTimer);
el.classList.toggle('golden', !!t.golden);
const kind = t.golden ? 'GOLDEN KAPPA TRAIN' : t.treasure ? 'TREASURE TRAIN' : 'HYPE TRAIN';
if (phase === 'end') {
clearInterval(timer);
el.querySelector('.name').innerHTML = `${kind} · <span class="lv">ENDED AT LV ${t.level}</span> ♡`;
el.querySelector('.time').textContent = '';
el.querySelector('.fill').style.width = '100%';
hideTimer = setTimeout(() => el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(-90px)', opacity:0 }],
{ duration:500, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; shownId = null; }).catch(() => {}), 5000);
return;
}
if (shownId !== t.id || el.style.visibility !== 'visible') {
el.getAnimations().forEach(a => a.cancel());
el.style.visibility = 'visible'; shownId = t.id;
el.animate([{ transform:'translateY(-90px) rotate(-3deg)', opacity:0 }, { transform:'translateY(4px) rotate(1deg)', opacity:1, offset:.75 },
{ transform:'translateY(0) rotate(0)', opacity:1 }], { duration:550, easing:'cubic-bezier(.2,.8,.3,1)' });
}
el.querySelector('.name').innerHTML = `${kind} · <span class="lv">LV ${t.level}</span>`;
const pct = t.goal ? Math.min(100, Math.round(100 * (t.progress || 0) / t.goal)) : 0;
el.querySelector('.fill').style.width = `${Math.max(2, pct)}%`;
if (t.expires_at) { expires = Date.parse(t.expires_at); clearInterval(timer); timer = setInterval(tick, 500); tick(); }
}
window.HypeBar = { update };
})();

View file

@ -0,0 +1,16 @@
/* "Now playing" strip (see nowplaying.js): small, top-right corner, visible only while music plays. */
#now-playing { --ink:#3a2a20; --red:#b74347; position:fixed; right:24px; top:18px; height:84px; z-index:40; visibility:hidden;
display:flex; align-items:center; gap:0; }
#now-playing * { box-sizing:border-box; }
/* paper slip with the song, taped on */
#now-playing .slip { position:relative; display:flex; align-items:center; gap:10px; max-width:340px; padding:6px 13px 6px 8px;
background:#fffdf7; box-shadow:0 6px 12px rgba(0,0,0,.4); transform:rotate(-1.5deg); }
#now-playing .slip:before { content:''; position:absolute; left:40%; top:-9px; width:58px; height:18px; transform:rotate(-4deg);
background:rgba(201,182,228,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 6px,#0000 6px 12px); }
#now-playing .cover { width:50px; height:50px; flex:none; background:#e8dcc8 center/cover; box-shadow:0 2px 4px rgba(0,0,0,.3);
border:2px solid #fff; transform:rotate(3deg); }
#now-playing .txt { min-width:0; }
#now-playing .t { font:700 23px/1.05 'Caveat', cursive; color:var(--ink); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#now-playing .t:before { content:'♪ '; color:var(--red); }
#now-playing .a { font:700 17px/1.1 'Caveat', cursive; color:#7a6656; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }

View file

@ -0,0 +1,53 @@
/*
"Now playing" slip, top-right: taped paper with cover, title and artist. Visible exactly while a song is playing; hides on pause/stop.
NowPlaying.update(np) np: { playing, title, artist, album, cover (data URL or null) }
Small grace period on hide so skipping to the next song does not make it flicker.
*/
(function () {
const HIDE_GRACE_MS = 1500;
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
let el = null, shown = false, hideTimer = null, key = '';
function root() {
if (!el) {
el = document.createElement('div'); el.id = 'now-playing';
el.innerHTML = `<div class="slip"><div class="cover"></div><div class="txt"><div class="t"></div><div class="a"></div></div></div>`;
document.body.appendChild(el);
}
return el;
}
function show() {
clearTimeout(hideTimer);
if (shown) return;
shown = true; el.style.visibility = 'visible';
el.getAnimations().forEach(a => a.cancel());
el.animate([{ transform:'translateY(-140px)', opacity:0 }, { transform:'translateY(6px)', opacity:1, offset:.75 }, { transform:'translateY(0)', opacity:1 }],
{ duration:550, easing:'cubic-bezier(.2,.8,.3,1)' });
}
function hide() {
clearTimeout(hideTimer);
hideTimer = setTimeout(() => {
if (!shown) return;
shown = false;
el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(-140px)', opacity:0 }], { duration:450, easing:'ease-in', fill:'forwards' })
.finished.then(() => { if (!shown) el.style.visibility = 'hidden'; }).catch(() => {});
}, HIDE_GRACE_MS);
}
function update(np) {
root();
if (!np || !np.title) { hide(); return; }
const k = `${np.title}|${np.artist}`;
if (k !== key) {
key = k;
el.querySelector('.t').textContent = np.title;
el.querySelector('.a').textContent = np.artist || np.album || '';
el.querySelector('.cover').style.backgroundImage = np.cover ? `url("${np.cover}")` : '';
if (shown) el.querySelector('.slip').animate([{ opacity:.2, transform:'rotate(-1.5deg) translateX(14px)' }, { opacity:1, transform:'rotate(-1.5deg)' }], { duration:350 });
}
np.playing ? show() : hide();
}
window.NowPlaying = { update };
})();

View file

@ -31,3 +31,11 @@
display:flex; flex-direction:column; align-items:center; justify-content:center; opacity:0; display:flex; flex-direction:column; align-items:center; justify-content:center; opacity:0;
font:700 40px/0.9 'Caveat', cursive; color:#fff; text-shadow:0 2px 0 rgba(0,0,0,.25); } font:700 40px/0.9 'Caveat', cursive; color:#fff; text-shadow:0 2px 0 rgba(0,0,0,.25); }
#polaroid-alert .badge small { font-size:19px; line-height:1; } #polaroid-alert .badge small { font-size:19px; line-height:1; }
/* variation name on a paper label (redeems) */
#polaroid-alert .tag { position:absolute; left:10px; bottom:10px; max-width:85%; padding:2px 12px; background:#fffdf7;
font:700 26px/1.2 'Caveat', cursive; color:var(--ink); transform:rotate(-3deg); box-shadow:0 2px 4px rgba(0,0,0,.25);
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; box-sizing:border-box; }
/* raid send-off: square Twitch avatar fills the photo instead of standing on the bottom edge */
#polaroid-alert .ph.avatar img { width:100%; height:100%; bottom:0; object-fit:cover; }

View file

@ -1,8 +1,11 @@
/* /*
Polaroid alerts for the OBS overlay. Polaroid alerts for the OBS overlay.
window.PolaroidAlerts.play(alert) queue an alert (never overlaps) window.PolaroidAlerts.play(alert) queue an alert (never overlaps)
window.PolaroidAlerts.reset() stop the current alert and clear the queue 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: Alert shapes come from src/alerts.js:
{ type:'follow', user } { type:'follow', user }
@ -11,19 +14,25 @@
{ type:'streak', user, streak } { type:'streak', user, streak }
{ type:'raid', user, viewers } { type:'raid', user, viewers }
{ type:'bits', user|null, bits, message } { 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. Everything per event (art, caption, tape colour, badge, sound) is in describe() below.
*/ */
(function () { (function () {
// ===================== CONFIG ===================== // ===================== CONFIG =====================
const BASE = '/alerts/'; const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages
const ART = n => `${BASE}art/${n}`; 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 SND = n => `${BASE}sounds/${n}`;
const VOLUME = 0.8; const VOLUME = 0.8;
const TAPE = { const TAPE = {
follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)', 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)', 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 // 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, '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, '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, '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', 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], 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] }; heart:[-8,26], heartX:[-10,6], heartY:[-14,8], badge:[-18,14] };
const MIN_HOLD = 6000; // ms fully visible, at least const AFTER_ANIM = 3000; // ms the finished polaroid stays up after its entrance animation
const SOUND_PAD = 1500; // ms after the sound ends const SOUND_LEAD = 400; // ms after the photo starts dropping that the sound starts
const GAP = 600; // ms between queued alerts const GAP = 600; // ms between queued alerts
// Event -> what the polaroid shows. null = no alert. // 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!`, 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' }, tape:TAPE.raid, sound:'fbi-open-up-sfx_ongglvo_y2ppwcm.mp3', badge:{ big:e.viewers, small:'raiders' },
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 }; 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': { case 'bits': {
if (!(e.bits >= BITS_MIN)) return null; if (!(e.bits >= BITS_MIN)) return null;
const t = BITS_TIERS.find(t => e.bits >= t.min); 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); }); 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 = []; const queue = [];
let busy = false, current = null, gen = 0; let busy = false, current = null, gen = 0;
function play(alert) { function play(alert) {
const d = describe(alert); const d = describe(alert);
if (!d) { console.log('[alerts] skipped', alert); return; } 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); queue.push(d);
if (!busy) next(); 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() { function reset() {
gen++; gen++;
queue.length = 0; queue.length = 0;
@ -139,6 +221,7 @@
current = null; current = null;
} }
if (el) el.style.visibility = 'hidden'; if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide();
busy = false; busy = false;
} }
@ -156,8 +239,32 @@
return `<div class="photo ${cls}"><div class="ph"><img src="${ART(art)}" alt=""></div>${inner}</div>`; 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 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 nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
const backs = Array.from({ length: d.stack || 0 }, (_, i) => const backs = Array.from({ length: d.stack || 0 }, (_, i) =>
photoHTML('back', BACK_ART[i % BACK_ART.length], '<div class="blank"></div>')).join(''); photoHTML('back', BACK_ART[i % BACK_ART.length], '<div class="blank"></div>')).join('');
@ -166,7 +273,7 @@
el.innerHTML = backs + ` el.innerHTML = backs + `
<div class="photo main" style="--tape:${d.tape}${d.phbg ? ';--phbg:' + d.phbg : ''}"> <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="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> <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=""> <img class="heart sticker" src="${ART('Heart.png')}" alt="">
${extraHearts} ${extraHearts}
@ -178,7 +285,7 @@
const main = q('.photo.main'); const main = q('.photo.main');
const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1); const tilt = between(RANGES.photoTilt) * (rnd() < .5 ? -1 : 1);
const rot = dd => `rotate(${tilt + dd}deg)`; 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; }; 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) // 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)' }], A(q('.cap'), [{ clipPath:'inset(0 100% 0 0)' }, { clipPath:'inset(0 0 0 0)' }],
{ delay:t0 + 1700, duration:700, easing:'ease-in-out' }); { delay:t0 + 1700, duration:700, easing:'ease-in-out' });
// sound as the photo lands; hold covers the whole sound // stays up: entrance animation + 3 s, or until the sound has finished if that is later
const hold = Math.max(MIN_HOLD, (SOUND_MS[d.sound] || 0) + SOUND_PAD); const animEnd = t0 + 2400; // caption done writing
const cur = current = { anims, timer:null, audio:null }; const soundEnd = url ? t0 + SOUND_LEAD + len : 0;
if (d.sound) { if (url) {
const a = new Audio(SND(d.sound)); a.volume = VOLUME; 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 + 400); 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 // 5. exit: lift and drop away
const exitAt = t0 + 2400 + hold; const exitAt = Math.max(animEnd + AFTER_ANIM, soundEnd);
const exit = A(el, [ const exit = A(el, [
{ transform:'translateY(0) rotate(0) scale(1)', opacity:1 }, { transform:'translateY(0) rotate(0) scale(1)', opacity:1 },
{ transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 }, { transform:'translateY(-20px) rotate(0deg) scale(1.04)', opacity:1, offset:.25 },
@ -255,6 +362,6 @@
.catch(() => {}); // cancelled by reset() .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(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', preload); else preload();
})(); })();

23
public/alerts/poll.css Normal file
View file

@ -0,0 +1,23 @@
/* Live poll card (see poll.js): taped paper, left side below the alert corner. */
#poll-card { --ink:#3a2a20; --red:#b74347; position:fixed; left:85px; top:650px; width:460px; z-index:45; visibility:hidden;
padding:24px 26px 22px; background:#fffdf7; box-shadow:0 14px 30px rgba(0,0,0,.45); }
#poll-card * { box-sizing:border-box; }
#poll-card:before, #poll-card:after { content:''; position:absolute; top:-14px; width:110px; height:32px;
background:rgba(140,215,215,.88); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); }
#poll-card:before { left:-30px; transform:rotate(-30deg); }
#poll-card:after { right:-30px; transform:rotate(26deg); }
#poll-card .head { display:flex; justify-content:space-between; align-items:baseline; font:900 15px 'Nunito', sans-serif; letter-spacing:2px; color:#7a6656; }
#poll-card .timer { font:700 26px 'Caveat', cursive; letter-spacing:0; color:var(--red); }
#poll-card .q { font:700 38px/1.05 'Caveat', cursive; color:var(--ink); margin:4px 0 12px; }
#poll-card .c { position:relative; margin:8px 0; }
#poll-card .row { display:flex; justify-content:space-between; font:700 28px/1 'Caveat', cursive; color:var(--ink); margin-bottom:3px; }
#poll-card .row .n { font-size:24px; color:#7a6656; }
#poll-card .track { height:18px; border:3px solid var(--ink); border-radius:10px; background:#fff; overflow:hidden; }
#poll-card .fill { height:100%; width:0; border-radius:6px; transition:width .6s cubic-bezier(.3,.7,.4,1);
background-image:repeating-linear-gradient(45deg,#fff5 0 6px,#0000 6px 12px); }
#poll-card .c.win .row .t { color:var(--red); }
#poll-card .c.lose { opacity:.55; }
#poll-card .heart { position:absolute; right:-78px; top:-22px; width:64px; opacity:0;
filter:drop-shadow(3px 0 0 #fff) drop-shadow(-3px 0 0 #fff) drop-shadow(0 3px 0 #fff) drop-shadow(0 -3px 0 #fff) drop-shadow(0 4px 6px rgba(0,0,0,.35)); }
#poll-card .stamp { position:absolute; right:22px; top:14px; padding:4px 14px; border:4px solid var(--red); border-radius:8px; color:var(--red);
font:900 26px 'Nunito', sans-serif; letter-spacing:3px; transform:rotate(-12deg); opacity:0; }

91
public/alerts/poll.js Normal file
View file

@ -0,0 +1,91 @@
/*
Live poll card for the overlay. Not part of the alert queue: it stays up while the poll runs.
PollCard.update(phase, poll) phase: begin | progress | end
poll: { id, title, choices:[{ id, title, votes }], ends_at, status } (status on end: completed | archived | terminated)
Votes animate live; on 'completed' the winner(s) get a heart and a WINNER stamp, then the card drops away.
*/
(function () {
const COLORS = ['#f4a0a8', '#a88be0', '#7fcfa6', '#f6c75b', '#8cc8f0'];
const HEART = (window.ALERTS_BASE || '/alerts/') + 'art/Heart.png';
const SHOW_RESULT_MS = 9000;
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
let el = null, pollId = null, timer = null, hideTimer = null, endsAt = 0;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'poll-card'; document.body.appendChild(el); }
return el;
}
function build(poll) {
const el = root();
clearTimeout(hideTimer); el.getAnimations().forEach(a => a.cancel());
pollId = poll.id;
el.innerHTML = `<div class="head"><span>POLL</span><span class="timer"></span></div>
<div class="q">${esc(poll.title)}</div>
${poll.choices.map((c, i) => `<div class="c" data-id="${esc(c.id)}">
<div class="row"><span class="t">${esc(c.title)}</span><span class="n">0</span></div>
<div class="track"><div class="fill" style="background-color:${COLORS[i % COLORS.length]}"></div></div>
<img class="heart" src="${HEART}" alt=""></div>`).join('')}
<div class="stamp">WINNER</div>`;
el.style.visibility = 'visible';
const tilt = (Math.random() * 4 - 2).toFixed(2);
el.animate([
{ transform:`translateX(-560px) rotate(-8deg)`, opacity:0 },
{ transform:`translateX(10px) rotate(${+tilt + 1}deg)`, opacity:1, offset:.75 },
{ transform:`translateX(0) rotate(${tilt}deg)`, opacity:1 },
], { duration:650, easing:'cubic-bezier(.2,.8,.3,1)', fill:'forwards' });
}
function votes(poll) {
const total = poll.choices.reduce((s, c) => s + c.votes, 0);
for (const c of poll.choices) {
const row = el.querySelector(`.c[data-id="${CSS.escape(c.id)}"]`);
if (!row) continue;
const pct = total ? Math.round(100 * c.votes / total) : 0;
row.querySelector('.n').textContent = `${c.votes} · ${pct}%`;
row.querySelector('.fill').style.width = `${total ? Math.max(3, pct) : 0}%`;
}
return total;
}
function tick() {
const s = Math.max(0, Math.round((endsAt - Date.now()) / 1000));
const t = el.querySelector('.timer');
if (t) t.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')} left`;
}
function hide(delay) {
clearTimeout(hideTimer);
hideTimer = setTimeout(() => {
el.animate([{ transform:'translateY(0)', opacity:1 }, { transform:'translateY(160px) rotate(10deg)', opacity:0 }],
{ duration:550, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; pollId = null; }).catch(() => {});
}, delay);
}
function update(phase, poll) {
if (!poll || !poll.choices) return;
if (phase === 'begin' || pollId !== poll.id) build(poll);
votes(poll);
if (poll.ends_at) { endsAt = Date.parse(poll.ends_at); clearInterval(timer); timer = setInterval(tick, 500); tick(); }
if (phase !== 'end') return;
clearInterval(timer);
const t = el.querySelector('.timer');
if (poll.status !== 'completed') { if (t) t.textContent = 'cancelled'; hide(1500); return; }
if (t) t.textContent = ''; // the WINNER stamp takes this corner
const max = Math.max(...poll.choices.map(c => c.votes));
el.querySelectorAll('.c').forEach(row => {
const c = poll.choices.find(x => x.id === row.dataset.id);
const win = max > 0 && c.votes === max;
row.classList.add(win ? 'win' : 'lose');
if (win) row.querySelector('.heart').animate([
{ transform:'rotate(-40deg) scale(0)', opacity:0 }, { transform:'rotate(10deg) scale(1.3)', opacity:1, offset:.6 }, { transform:'rotate(6deg) scale(1)', opacity:1 },
], { delay:300, duration:450, easing:'ease-out', fill:'forwards' });
});
if (max > 0) el.querySelector('.stamp').animate([
{ transform:'rotate(-12deg) scale(2.2)', opacity:0 }, { transform:'rotate(-12deg) scale(.9)', opacity:1, offset:.7 }, { transform:'rotate(-12deg) scale(1)', opacity:1 },
], { delay:700, duration:380, easing:'ease-in', fill:'forwards' });
hide(SHOW_RESULT_MS);
}
window.PollCard = { update };
})();

View file

@ -0,0 +1,15 @@
/* Outgoing raid send-off card (see raidcard.js): big taped polaroid, top-centre, silent, stays during the countdown. */
#raid-card { --ink:#3a2a20; --red:#b74347; position:fixed; left:50%; top:60px; width:340px; margin-left:-170px; z-index:58; visibility:hidden;
padding:16px 16px 0; background:#fffdf7; box-shadow:0 16px 34px rgba(0,0,0,.5); }
#raid-card * { box-sizing:border-box; }
#raid-card:before, #raid-card:after { content:''; position:absolute; top:-15px; width:120px; height:34px; z-index:2;
background:rgba(250,170,120,.9); background-image:repeating-linear-gradient(45deg,#fff6 0 8px,#0000 8px 16px); box-shadow:0 1px 2px rgba(0,0,0,.15); }
#raid-card:before { left:-30px; transform:rotate(-28deg); }
#raid-card:after { right:-30px; transform:rotate(26deg); }
#raid-card .ph { height:300px; background:linear-gradient(#ffe6d6,#f8c8a8) ; position:relative; overflow:hidden; }
#raid-card .ph img { width:100%; height:100%; object-fit:cover; display:block; }
#raid-card .ph img.fallback { object-fit:contain; object-position:bottom; }
#raid-card .cap { font:700 32px/1.05 'Caveat', cursive; color:var(--ink); text-align:center; padding:12px 10px 16px; }
#raid-card .cap .u { color:var(--red); display:block; font-size:38px; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#raid-card .when { position:absolute; right:-40px; top:28px; padding:6px 14px; background:#e07a45; color:#fff; border:4px solid #fff; border-radius:30px;
font:900 20px 'Nunito', sans-serif; letter-spacing:1px; box-shadow:0 6px 10px rgba(0,0,0,.35); transform:rotate(6deg); white-space:nowrap; }

63
public/alerts/raidcard.js Normal file
View file

@ -0,0 +1,63 @@
/*
Outgoing raid send-off card. Silent, outside the alert queue.
RaidCard.update(phase, raid) phase: start | done | cancel
raid: { target, avatar (Twitch profile picture URL or null), viewers, started_at }
start: appears and stays with a countdown (Twitch raids wait up to 90 s); done: "raid sent!" then leaves; cancel: leaves.
*/
(function () {
const COUNTDOWN_S = 90;
const BASE = window.ALERTS_BASE || '/alerts/';
const FALLBACK = BASE + 'art/CharacterHappy.png';
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
let el = null, timer = null, hideTimer = null, startedAt = 0, shown = false;
function root() { if (!el) { el = document.createElement('div'); el.id = 'raid-card'; document.body.appendChild(el); } return el; }
function render(raid, line, badge) {
const img = raid.avatar ? `<img src="${esc(raid.avatar)}" alt="" onerror="this.onerror=null;this.className='fallback';this.src='${FALLBACK}'">`
: `<img class="fallback" src="${FALLBACK}" alt="">`;
el.innerHTML = `<div class="ph">${img}</div>
<div class="cap"><span class="u">raiding ${esc(raid.target)}</span>${esc(line)}</div>
<div class="when">${esc(badge)}</div>`;
}
function tick() {
const left = Math.max(0, COUNTDOWN_S - Math.round((Date.now() - startedAt) / 1000));
const w = el.querySelector('.when');
if (w) w.textContent = left ? `raid in ${Math.floor(left / 60)}:${String(left % 60).padStart(2, '0')}` : 'any second now…';
}
function enter() {
if (shown) return;
shown = true; el.style.visibility = 'visible';
el.getAnimations().forEach(a => a.cancel());
el.animate([{ transform:'translateY(-420px) rotate(-10deg)', opacity:0 }, { transform:'translateY(10px) rotate(2deg)', opacity:1, offset:.75 },
{ transform:'translateY(0) rotate(-1deg)', opacity:1 }], { duration:700, easing:'cubic-bezier(.2,.8,.3,1)', fill:'forwards' });
}
function leave(delay) {
clearTimeout(hideTimer);
hideTimer = setTimeout(() => {
clearInterval(timer);
el.animate([{ transform:'translateY(0) rotate(-1deg)', opacity:1 }, { transform:'translateX(700px) rotate(18deg)', opacity:0 }],
{ duration:700, easing:'ease-in', fill:'forwards' }).finished.then(() => { el.style.visibility = 'hidden'; shown = false; }).catch(() => {});
}, delay);
}
function update(phase, raid) {
root(); clearTimeout(hideTimer);
const viewers = raid.viewers != null ? `with ${raid.viewers} of you, be nice! ♡` : 'with all of you, be nice! ♡';
if (phase === 'start') {
startedAt = raid.started_at ? Date.parse(raid.started_at) : Date.now();
render(raid, viewers, '');
enter(); clearInterval(timer); timer = setInterval(tick, 500); tick();
} else if (phase === 'done') {
clearInterval(timer);
render(raid, 'raid sent! see you there ♡', 'GO GO GO');
enter(); leave(6000);
} else if (phase === 'cancel') {
clearInterval(timer);
if (!shown) return;
const w = el.querySelector('.when'); if (w) w.textContent = 'cancelled';
leave(1500);
}
}
window.RaidCard = { update };
})();