The heart on the winning poll option and the picture when Twitch sends no emote were still a fixed file name; they now come from the alert theme (placeholder when none is set). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
196 lines
12 KiB
JavaScript
196 lines
12 KiB
JavaScript
/*
|
|
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
|
|
FxAlert.envelope(d, cur, snd) TTS redeems: envelope opens, the letter rises out and settles in front, words ink in as
|
|
they are spoken (d.tts URL, d.ttsMs length, d.ttsEnv loudness per 40 ms, d.ttsPrefix
|
|
= words said before the message, e.g. "<name> says:")
|
|
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;
|
|
// when Twitch sends no emote: the corner sticker from Actions → Alerts, else a plain shape
|
|
const fallback = () => window.FX_FALLBACK || (window.S && window.S.alert_theme && window.S.alert_theme.heart) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg';
|
|
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&', '<':'<', '>':'>', '"':'"' }[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
|
|
let exitAt = Math.max(650 + AFTER_ANIM, 650 + read, SOUND_LEAD + snd.len);
|
|
if (d.tts) { // TTS: after the intro sound, keep the note up until it is said
|
|
const ttsAt = SOUND_LEAD + (snd.url ? snd.len + 250 : 300);
|
|
const a = new Audio(d.tts); a.volume = snd.volume;
|
|
const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, ttsAt);
|
|
cur.anims.push({ cancel: () => { clearTimeout(t); a.pause(); } }); // skip/reset stop the voice too
|
|
exitAt = Math.max(exitAt, ttsAt + (d.ttsMs || 4000) + 900);
|
|
}
|
|
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' }));
|
|
}
|
|
|
|
// ---- TTS redeems: envelope letter ----
|
|
const VOICE_AT = 1300; // ms: the voice starts while the letter comes back down
|
|
const ENV_STEP = 0.04; // s per loudness value (src/tts.js ENV_STEP_MS)
|
|
|
|
// when each shown word starts (s), spread over the voiced part of the clip, longer words and pauses after
|
|
// punctuation get more time. The first `prefix` spoken words ("<name> says:") are not on the letter.
|
|
function wordStarts(env, prefixWords, words) {
|
|
let s = 0, e = env.length - 1;
|
|
while (s < e && env[s] < .08) s++;
|
|
while (e > s && env[e] < .08) e--;
|
|
const all = [...prefixWords, ...words];
|
|
const weight = all.map(x => x.length + 2 + (/[.!?,:]$/.test(x) ? 5 : 0));
|
|
const total = weight.reduce((a, b) => a + b, 0) || 1;
|
|
let acc = 0;
|
|
const starts = all.map((_, i) => { const t = (s + (e - s + 1) * acc / total) * ENV_STEP; acc += weight[i]; return t; });
|
|
return starts.slice(prefixWords.length);
|
|
}
|
|
|
|
function envelope(d, cur, snd) {
|
|
const el = root();
|
|
const text = d.msg || '';
|
|
const words = text.split(/\s+/).filter(Boolean);
|
|
el.innerHTML = `<div class="envl"><div class="flap"></div>
|
|
<div class="slot"><div class="letter ${text.length > 340 ? 'huge' : text.length > 230 ? 'longer' : text.length > 140 ? 'long' : ''}"><div class="to">from ${esc(d.name)} ♡</div>
|
|
<div class="tx">${words.map(w => `<span class="w">${esc(w)}</span>`).join(' ')}</div></div></div>
|
|
<div class="env"></div><div class="seal">♥</div></div>`;
|
|
el.style.visibility = 'visible';
|
|
const box = el.querySelector('.envl');
|
|
const spans = [...box.querySelectorAll('.w')];
|
|
A(cur, box, [{ transform:'translateY(-40px) scale(.92) rotate(-3deg)', opacity:0 }, { transform:'none', opacity:1 }],
|
|
{ duration:600, easing:'cubic-bezier(.2,1.25,.4,1)' });
|
|
|
|
let exitAt;
|
|
if (d.tts) {
|
|
const prefix = d.ttsPrefix ? [d.name, 'says:'].slice(0, d.ttsPrefix) : [];
|
|
const starts = d.ttsEnv && d.ttsEnv.length ? wordStarts(d.ttsEnv, prefix, words) : null;
|
|
const a = new Audio(d.tts); a.volume = snd.volume;
|
|
const t = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] TTS blocked:', err.message)); }, VOICE_AT);
|
|
let raf = 0, failed = false;
|
|
const fail = () => { failed = true; }; // voice missing/blocked: show the whole text anyway
|
|
a.addEventListener('error', fail, { once:true });
|
|
const t2 = setTimeout(() => { if (!a.currentTime) fail(); }, VOICE_AT + 1500);
|
|
const tick = () => { // ink in each word as it is said
|
|
const now = a.ended ? Infinity : a.currentTime + .05;
|
|
spans.forEach((w, i) => w.classList.toggle('on', failed || a.ended || (!a.paused || a.currentTime > 0) && (!starts || now >= starts[i])));
|
|
raf = requestAnimationFrame(tick);
|
|
};
|
|
raf = requestAnimationFrame(tick);
|
|
cur.anims.push({ cancel: () => { clearTimeout(t); clearTimeout(t2); cancelAnimationFrame(raf); a.pause(); } });
|
|
exitAt = VOICE_AT + (d.ttsMs || 4000) + 1400;
|
|
} else { // blocked or no voice: just show the letter
|
|
spans.forEach(w => w.classList.add('on'));
|
|
exitAt = 2400 + 2000 + 60 * text.length;
|
|
}
|
|
return done(cur, A(cur, box, [{ transform:'none', opacity:1 }, { transform:'translateY(40px) scale(.95) rotate(4deg)', opacity:0 }],
|
|
{ delay:exitAt, duration:500, easing:'ease-in' }));
|
|
}
|
|
|
|
window.FxAlert = { giant, rain, message, envelope, hide };
|
|
})();
|