heystreamer/public/alerts/cassette.js
Bashy 8ac8fe024c Reward / Power-up icon as a top-left sticker on the cassette and the video box
Twitch icons of channel point rewards (custom images) and Custom Power-ups are cached
(10 min, refreshed on unknown triggers, never holding an alert more than 2 s) and
attached as alert.icon; cassette.js and video.js show it as a white-outlined sticker
on the top-left corner.

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

129 lines
8.1 KiB
JavaScript

/*
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>
${d.icon ? `<div class="ico"><img src="${esc(d.icon)}" 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)' });
if (q('.ico')) A(q('.ico'), [ // the reward's / Power-up's Twitch icon, top-left corner
{ transform:'rotate(10deg) scale(0)', opacity:0 },
{ transform:'rotate(-18deg) scale(1.2)', opacity:1, offset:.6 },
{ transform:'rotate(-10deg) scale(1)', opacity:1 },
], { delay:560, duration:360, easing:'ease-out' });
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 };
})();