Stats per stream and period, public stats page, dashboard settings, Card alert style

Statistics
- Per day and per stream statistics (src/periodstats.js, one generic stat_day table), backfilled
  once from the older tables; Stream / Week / Month / Year / All time views, Community and Streams tabs.
- Viewer count every 5 minutes and title / category history per stream (EventSub channel.update):
  viewer graph, games played (donut), games in the streams list.
- Twitch sync (src/twitchsync.js): followers with follow dates, current subs, mods, VIPs, all-time
  bits, channel emotes, past streams from VODs. Twitch analytics CSV import (src/twitchcsv.js).
- Public stats page on its own host (Settings -> Stats and data): no message text, no bots,
  !hideme / !showme opt-out. Viewer page: roles, follow age, sub status, bits, a menu for rarely used actions.
- StreamElements watch-time importer removed (already imported minutes stay as a baseline).

Dashboard
- Settings and Actions with a left sidebar; each settings page saves only its own fields.
  Connections (Twitch, StreamElements token now set here, HUDFX), OBS links (hidden behind an eye
  toggle) with a link builder, Chat (sound picked from the media library), TTS, Stats and data,
  Backup (export / import the whole setup), Advanced. Time zone setting for the stats pages.
- Actions -> Alerts: alert style, pictures, sounds, bits tiers and card colours, stored in the
  database (src/theme.js); an old file-based theme is imported once. Alert preview page
  (/actions/alerts/preview, tools/preview/export.js for a static copy).
- Old /actions page removed; Actions = Redeems / Alerts / TTS voices / Media.

Alerts
- New plain Card style for everyone (public/alerts/card.js); Polaroid, Cassette and the TTS letter
  stay as optional looks. Redeem variations can be Card, Cassette, Sound only or Video.

Repo
- No channel data in git: the channel's art, stickers and sounds stay on disk (gitignored) and are
  picked in the dashboard; examples for the server config (apache.example.sh, .env.example).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-23 11:22:49 +02:00
parent 5bf4bffaa0
commit c481ca92cb
57 changed files with 3080 additions and 774 deletions

View file

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 300 260"><path d="M150 236C70 180 22 136 22 84c0-34 26-60 60-60 28 0 50 16 68 40 18-24 40-40 68-40 34 0 60 26 60 60 0 52-48 96-128 152z" fill="#f4a0a8" stroke="#fffdf7" stroke-width="10"/><text x="150" y="122" text-anchor="middle" font-family="sans-serif" font-size="26" font-weight="700" fill="#fffdf7">your art</text><text x="150" y="152" text-anchor="middle" font-family="sans-serif" font-size="16" fill="#fffdf7">public/alerts/art</text></svg>

After

Width:  |  Height:  |  Size: 501 B

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

@ -0,0 +1,23 @@
/* Card alerts (card.js): the plain style every channel gets. Colours come from Actions → Alerts (theme.card). */
#card-alert { position:fixed; left:60px; top:60px; width:600px; visibility:hidden; z-index:50; font-family:'Nunito', system-ui, sans-serif;
--accent:#9146ff; --bg:#ffffff; --fg:#1f1f23; }
#card-alert .card { position:relative; display:flex; gap:18px; align-items:center; background:var(--bg); color:var(--fg);
border-radius:20px; padding:16px 24px 18px 16px; box-shadow:0 14px 34px rgba(0,0,0,.35); overflow:hidden; }
#card-alert .card::before { content:''; position:absolute; left:0; top:0; bottom:0; width:8px; background:var(--accent); }
#card-alert .pic { width:104px; height:104px; flex:none; border-radius:16px; margin-left:6px; display:grid; place-items:center; overflow:hidden;
background:color-mix(in srgb, var(--accent) 16%, var(--bg)); }
#card-alert .pic img { width:100%; height:100%; object-fit:contain; }
#card-alert .pic .ini { font:900 50px/1 'Nunito', sans-serif; color:var(--accent); }
#card-alert .txt { min-width:0; flex:1; }
#card-alert .tag { font:800 14px/1.2 'Nunito', sans-serif; text-transform:uppercase; letter-spacing:.08em; color:var(--accent); opacity:.9; margin-bottom:2px;
white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#card-alert .name { font:900 32px/1.1 'Nunito', sans-serif; color:var(--accent); white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
#card-alert .line { font:800 23px/1.2 'Nunito', sans-serif; margin-top:2px; }
#card-alert .msg { font:800 19px/1.3 'Nunito', sans-serif; opacity:.72; margin-top:6px; overflow:hidden; display:-webkit-box; -webkit-line-clamp:4; -webkit-box-orient:vertical; }
#card-alert .msg .w { opacity:.25; transition:opacity .15s; }
#card-alert .msg .w.on { opacity:1; }
#card-alert .badge { position:absolute; right:16px; top:14px; background:var(--badge, var(--accent)); color:#fff; border-radius:99px;
padding:3px 13px; font:900 20px/1.3 'Nunito', sans-serif; box-shadow:0 3px 8px rgba(0,0,0,.2); }
#card-alert .badge small { font-size:13px; margin-left:4px; opacity:.9; }
#card-alert .card.has-badge .txt { padding-right:90px; }
#card-alert .bar { position:absolute; left:0; right:0; bottom:0; height:5px; background:var(--accent); opacity:.55; transform-origin:left center; }

78
public/alerts/card.js Normal file
View file

@ -0,0 +1,78 @@
/*
Card alerts: the plain style (Actions → Alerts: style "Card"). Used for events (follow, sub, gift, raid, bits, tip,
Hype Train) and for redeem variations / read-aloud redeems set to Card. Called by polaroid.js (shared queue):
window.CardAlert.show(d, cur, { url, len, volume }) -> Promise (resolves when it has left)
d: { art|sticker|emote (picture URL), name, line, msg, badge {big, small, color}, tag (small label above the name),
tts (voice URL instead of the sound), ttsEnv (loudness for word timing) }
cur: { anims, timer, audio } from polaroid.js, so reset / skip can stop it.
Timeline: slides in (0.6 s), sound starts, stays until the sound / voice ends (at least 4 s), slides out.
*/
(function () {
const MIN_SHOW = 4000, SOUND_LEAD = 350, ENV_STEP = 0.04;
const esc = s => String(s ?? '').replace(/[&<>"]/g, c => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', '"':'&quot;' }[c]));
let el = null;
function root() {
if (!el) { el = document.createElement('div'); el.id = 'card-alert'; document.body.appendChild(el); }
return el;
}
const theme = () => (window.S && window.S.alert_theme) || {};
function show(d, cur, { url, len, volume }) {
const el = root(), c = theme().card || {};
if (c.accent) el.style.setProperty('--accent', c.accent);
if (c.bg) el.style.setProperty('--bg', c.bg);
if (c.text) el.style.setProperty('--fg', c.text);
const pic = d.emote || d.sticker || d.art || '';
const name = d.name || 'Someone';
const words = d.tts && d.msg ? String(d.msg).split(/\s+/).filter(Boolean) : null;
el.innerHTML = `<div class="card${d.badge ? ' has-badge' : ''}">
<div class="pic">${pic ? `<img src="${esc(pic)}" alt="">` : `<span class="ini">${esc(name.trim()[0] || '♥').toUpperCase()}</span>`}</div>
<div class="txt">
${d.tag ? `<div class="tag">${esc(d.tag)}</div>` : ''}
<div class="name">${esc(name)}</div>
<div class="line">${esc(d.line || '')}</div>
${d.msg ? `<div class="msg">${words ? words.map(w => `<span class="w">${esc(w)}</span>`).join(' ') : `“${esc(d.msg)}”`}</div>` : ''}
</div>
${d.badge ? `<div class="badge"${d.badge.color ? ` style="--badge:${esc(d.badge.color)}"` : ''}>${esc(d.badge.big)}<small>${esc(d.badge.small || '')}</small></div>` : ''}
<div class="bar"></div>
</div>`;
el.style.visibility = 'visible';
const card = el.querySelector('.card');
const A = (node, frames, opts) => { const a = node.animate(frames, { fill:'both', ...opts }); cur.anims.push(a); return a; };
A(card, [
{ transform:'translateX(-700px)', opacity:0 },
{ transform:'translateX(14px)', opacity:1, offset:.75 },
{ transform:'translateX(0)', opacity:1 },
], { duration:600, easing:'cubic-bezier(.2,.8,.3,1)' });
A(el.querySelector('.pic'), [{ transform:'scale(.6) rotate(-8deg)' }, { transform:'scale(1.08) rotate(3deg)', offset:.6 }, { transform:'scale(1) rotate(0)' }],
{ delay:350, duration:450, easing:'ease-out' });
// the voice (read-aloud redeems) or the sound
const voice = d.tts || null;
const playUrl = voice || url;
const playLen = voice ? (d.ttsMs || 0) : len;
if (playUrl) {
const a = new Audio(playUrl); a.volume = volume;
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, SOUND_LEAD);
// words light up roughly as they are spoken
if (words) {
const spans = [...el.querySelectorAll('.msg .w')];
const total = Math.max(playLen, 1000), step = total / Math.max(spans.length, 1);
spans.forEach((s, i) => setTimeout(() => s.classList.add('on'), SOUND_LEAD + i * step));
}
} else if (words) el.querySelectorAll('.msg .w').forEach(s => s.classList.add('on'));
const stay = Math.max(MIN_SHOW, playUrl ? SOUND_LEAD + playLen + 600 : 0);
A(el.querySelector('.bar'), [{ transform:'scaleX(1)' }, { transform:'scaleX(0)' }], { delay:600, duration:Math.max(stay - 600, 500), easing:'linear' });
const exit = A(card, [
{ transform:'translateX(0)', opacity:1 },
{ transform:'translateX(18px)', opacity:1, offset:.25 },
{ transform:'translateX(-720px)', opacity:0 },
], { delay:stay, duration:550, 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.CardAlert = { show, hide };
})();

View file

@ -8,7 +8,8 @@
*/
(function () {
const AFTER_ANIM = 3000, SOUND_LEAD = 600, ANIM_END = 1200;
const DEFAULT_STICKER = (window.ALERTS_BASE || '/alerts/') + 'stickers/default-sticker.png';
// sticker when a variation has none: Actions → Alerts → Default redeem sticker (else a plain shape)
const defaultSticker = () => (window.S && window.S.alert_theme && window.S.alert_theme.defaultSticker) || (window.ALERTS_BASE || '/alerts/') + 'art/placeholder.svg';
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);
@ -58,7 +59,7 @@
<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>
<div class="stk"><img src="${esc(d.sticker || defaultSticker())}" 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>

View file

@ -39,3 +39,6 @@
/* 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; }
/* no picture set (Actions → Alerts): the first letter of the name, handwritten */
#polaroid-alert .ph .ini { position:absolute; inset:0; display:grid; place-items:center; font:700 170px/1 'Caveat', cursive; color:rgba(255,255,255,.9); text-shadow:0 4px 12px rgba(0,0,0,.12); }

View file

@ -26,9 +26,10 @@
// ===================== CONFIG =====================
const BASE = window.ALERTS_BASE || '/alerts/'; // ALERTS_BASE: only set by offline test pages
const rebase = u => (u && u.startsWith('/alerts/') && BASE !== '/alerts/') ? BASE + u.slice(8) : u;
const ART = n => /^(https?:)?\/\//.test(n) ? n : `${BASE}art/${n}`; // full URLs (e.g. Twitch avatars) pass through
// pictures and sounds are URLs from the Media library (Actions → Alerts); bare names = old files in public/alerts/art|sounds
const ART = n => !n ? '' : /^(https?:)?\/\//.test(n) ? n : n.startsWith('/') ? rebase(n) : `${BASE}art/${n}`;
const SND = n => `${BASE}sounds/${n}`;
const VOLUME = 0.8;
const DEFAULT_VOLUME = 0.8;
const TAPE = {
follow:'rgba(201,182,228,.88)', sub:'rgba(244,160,168,.88)', prime:'rgba(140,200,240,.88)',
@ -36,27 +37,10 @@
bits:'rgba(190,160,240,.88)', redeem:'rgba(140,215,215,.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, volume:0.4 }, // very loud clip: half volume
{ 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,
'emotional-damage-meme.mp3':3369,
};
const BACK_ART = ['CharacterHeart.png','CharacterLoveEyes_Glasses.png','CharacterHappy.png',
'CharacterLynx.png','CharacterCool.png','CharacterSelfie.png'];
// The channel's alert theme (src/theme.js, edited on Actions → Alerts) arrives with the overlay settings and is read
// per alert, so a save in the dashboard is used by the next alert without reloading OBS.
const TH = () => (window.S && window.S.alert_theme) || {};
const SOUND_MS = {}; // sound lengths are measured in the browser once (soundLength)
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] };
@ -66,10 +50,12 @@
// Event -> what the polaroid shows. null = no alert.
function describe(e) {
const th = TH(), THA = th.art || {}, THS = th.sounds || {};
const BITS_MIN = th.bitsMin ?? 1, BITS_TIERS = th.bitsTiers || [];
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' };
return { art:THA.follow, name:who, line:'just followed! ♡', tape:TAPE.follow, sound:THS.follow };
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] || '');
@ -79,26 +65,26 @@
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',
const art = e.prime ? THA.prime : (months > 1 || multi ? THA.resub : THA.sub);
return { art, name:who, line, msg:e.message, tape:e.prime ? TAPE.prime : TAPE.sub, sound:THS.sub,
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,
return { art:THA.gift, 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,
tape:TAPE.gift, sound:THS.gift, 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)' };
return { art:THA.streak, name:who, line:`is on a ${e.streak}-stream watch streak!`,
tape:TAPE.streak, sound:THS.streak, 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' },
return { art:THA.raid, name:who, line:`is raiding with ${e.viewers} viewers!`,
tape:TAPE.raid, sound:THS.raid, badge:{ big:e.viewers, small:'raiders' },
phbg:'linear-gradient(#ffe6d6,#f8c8a8)', stack:2 };
case 'tip': {
// StreamElements tip: amount in its own currency, extra hearts for bigger tips
@ -106,18 +92,17 @@
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',
return { art:THA.tip, name:who, line:`tipped ${money}! ♡`, msg:e.message, sound:THS.tip,
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
// Hype Train: start / level up / end (art + sounds from the theme)
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,
const sound = { begin:THS.hypeBegin, level:THS.hypeLevel, end:THS.hypeEnd }[e.phase];
return { art:THA.hype, 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)' };
@ -133,7 +118,7 @@
}
case 'bits': {
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) || BITS_TIERS[BITS_TIERS.length - 1] || { art:THA.follow, badge:'#8a8aa8', hearts:0 };
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, volume:t.volume, phbg:'linear-gradient(#efe6ff,#d7c6f5)' };
}
@ -154,9 +139,8 @@
// 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']);
const th = TH();
const imgs = new Set([...(th.back || []), ...Object.values(th.art || {}), th.heart, ...(th.bitsTiers || []).map(t => t.art)].filter(Boolean));
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); });
}
@ -203,7 +187,7 @@
current.anims.forEach(a => a.cancel());
current = null;
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide();
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
busy = false;
}
@ -230,7 +214,7 @@
current = null;
}
if (el) el.style.visibility = 'hidden';
window.CassetteAlert?.hide(); window.FxAlert?.hide();
window.CassetteAlert?.hide(); window.FxAlert?.hide(); window.CardAlert?.hide();
busy = false;
}
@ -245,7 +229,7 @@
}
function photoHTML(cls, art, inner) {
return `<div class="photo ${cls}"><div class="ph"><img src="${ART(art)}" alt=""></div>${inner}</div>`;
return `<div class="photo ${cls}"><div class="ph">${art ? `<img src="${ART(art)}" alt="">` : ''}</div>${inner}</div>`;
}
async function show(d) {
@ -255,19 +239,31 @@
const len = url ? await soundLength(url) : 0;
if (cur !== current) return; // skipped while measuring the sound
// which look: Card (plain, everyone) or the optional Polaroid / Cassette / Letter (Actions → Alerts, Redeems)
const th = TH();
const asCard = window.CardAlert && !d.soundOnly && (
d.style === 'card' || // redeem variation set to Card
(d.style === 'tts' && th.ttsStyle !== 'letter') || // read-aloud redeem
(!d.cassette && !d.style && th.style !== 'polaroid')); // follow / sub / gift / raid / bits / tip / Hype Train
if (asCard) {
if (d.cassette) d.tag = d.title && d.sub && d.title !== d.sub ? `${d.sub} · ${d.title}` : (d.sub || d.title || '');
if (!d.sticker && d.cassette) d.sticker = ART(th.defaultSticker) || null;
return window.CardAlert.show(d, cur, { url, len, volume: d.volume ?? (th.volume ?? DEFAULT_VOLUME) })
.then(() => { if (current === cur) current = null; });
}
const fx = { emote: 'giant', emote_rain: 'rain', message: 'message', tts: 'envelope' }[d.style];
if (fx && !d.soundOnly && window.FxAlert) {
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? VOLUME })
return window.FxAlert[fx](d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_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 })
return window.CassetteAlert.show(d, cur, { url, len, volume: d.volume ?? (TH().volume ?? DEFAULT_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;
const a = cur.audio = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_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);
@ -275,16 +271,18 @@
}
const nameSize = d.name.length > 18 ? 32 : d.name.length > 14 ? 36 : 40;
const backArt = th.back && th.back.length ? th.back : [d.art]; // photos fanned out behind (theme), else the same one
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('');
photoHTML('back', backArt[i % backArt.length], '<div class="blank"></div>')).join('');
const heart = ART(th.heart); // corner sticker; none set = no stickers
const extraHearts = heart ? Array.from({ length: d.hearts || 0 }, () =>
`<img class="heart extra sticker" src="${heart}" 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${d.avatar ? ' avatar' : ''}"><img src="${ART(d.art)}" alt="">${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
<div class="ph${d.avatar ? ' avatar' : ''}">${d.art ? `<img src="${ART(d.art)}" alt="">` : `<span class="ini">${esc((d.name || '♥').trim()[0] || '♥').toUpperCase()}</span>`}${d.tag ? `<span class="tag">${esc(d.tag)}</span>` : ''}</div>
<div class="cap"><span class="u" style="font-size:${nameSize}px">${esc(d.name)}</span>${esc(d.line)}${d.msg ? `<span class="msg">“${esc(d.msg)}”</span>` : ''}</div>
<img class="heart sticker" src="${ART('Heart.png')}" alt="">
${heart ? `<img class="heart sticker" src="${heart}" 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>`;
@ -339,7 +337,7 @@
{ 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));
if (q('.heart:not(.extra)')) 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])));
@ -354,7 +352,7 @@
const animEnd = t0 + 2400; // caption done writing
const soundEnd = url ? t0 + SOUND_LEAD + len : 0;
if (url) {
const a = new Audio(url); a.volume = d.volume ?? VOLUME;
const a = new Audio(url); a.volume = d.volume ?? (TH().volume ?? DEFAULT_VOLUME);
cur.timer = setTimeout(() => { cur.audio = a; a.play().catch(err => console.warn('[alerts] sound blocked:', err.message)); }, t0 + SOUND_LEAD);
}

View file

@ -7,15 +7,16 @@
(function () {
const COUNTDOWN_S = 90;
const BASE = window.ALERTS_BASE || '/alerts/';
const FALLBACK = BASE + 'art/CharacterHappy.png';
// picture when the raided channel has none: Actions → Alerts → Raid send-off picture
const fallback = () => (window.S && window.S.alert_theme && window.S.alert_theme.raidFallback) || BASE + 'art/placeholder.svg';
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="">`;
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>`;