/* Chat messages for the overlay (?parts=chat). tmi.js in overlay.ejs feeds them in via HSChat.add().
Look: public/chat/chat.css. Emotes: Twitch (from the message tags) + 7TV channel and global sets.
Settings used: S.message_timeout (seconds, 0 = never fade) and S.max_messages. */
(function () {
const box = document.getElementById('chat');
if (!box) return;
const TWITCH_EMOTE = id => `https://static-cdn.jtvnw.net/emoticons/v2/${id}/default/dark/2.0`;
const SEVENTV = 'https://7tv.io/v3';
const ZERO_WIDTH = 256; // 7TV emote data flag: overlays the emote before it
const REFRESH_MS = 10 * 60 * 1000; // pick up newly added 7TV emotes without an OBS refresh
let emotes7tv = new Map(); // name -> { url, zw }
let roomId = null, seq = 0;
// ---------- 7TV ----------
function setFrom(list, into) {
for (const e of list || []) {
const host = e.data && e.data.host;
if (!host || !host.url) continue;
const file = (host.files || []).find(f => f.name === '2x.webp') || (host.files || []).find(f => /\.webp$/.test(f.name));
if (!file) continue;
into.set(e.name, { url: 'https:' + host.url + '/' + file.name, zw: ((e.data.flags || 0) & ZERO_WIDTH) !== 0 });
}
}
async function getJSON(url) {
const r = await fetch(url);
if (!r.ok) throw new Error(url + ' -> ' + r.status);
return r.json();
}
async function load7tv() {
const next = new Map();
try { setFrom((await getJSON(`${SEVENTV}/emote-sets/global`)).emotes, next); }
catch (e) { console.warn('[chat] 7TV global emotes:', e.message); }
if (roomId) {
try { setFrom(((await getJSON(`${SEVENTV}/users/twitch/${roomId}`)).emote_set || {}).emotes, next); } // channel wins over global
catch (e) { console.warn('[chat] 7TV channel emotes:', e.message); }
}
if (next.size) emotes7tv = next;
console.log(`[chat] 7TV emotes loaded: ${next.size}`);
}
function setRoom(id) {
if (!id || id === roomId) return;
roomId = id;
load7tv();
}
load7tv();
setInterval(load7tv, REFRESH_MS);
// ---------- message -> HTML ----------
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const img = (url, name) => `
`;
// Returns { html, emoteOnly, emoteCount }.
function render(text, twitchEmotes) {
// Twitch emote positions are in code points, so work on an array of characters
const chars = Array.from(text);
const ranges = [];
for (const [id, list] of Object.entries(twitchEmotes || {})) {
for (const r of list) { const [a, b] = r.split('-').map(Number); ranges.push({ a, b, id }); }
}
ranges.sort((x, y) => x.a - y.a);
const tokens = []; // { t:'text', s } | { t:'em', url, name, zw }
let i = 0;
for (const r of ranges) {
if (r.a > i) tokens.push({ t: 'text', s: chars.slice(i, r.a).join('') });
tokens.push({ t: 'em', url: TWITCH_EMOTE(r.id), name: chars.slice(r.a, r.b + 1).join(''), zw: false });
i = r.b + 1;
}
if (i < chars.length) tokens.push({ t: 'text', s: chars.slice(i).join('') });
// 7TV: whole words inside the text parts
const out = [];
for (const tk of tokens) {
if (tk.t !== 'text') { out.push(tk); continue; }
for (const part of tk.s.split(/(\s+)/)) {
const e = part && emotes7tv.get(part);
out.push(e ? { t: 'em', url: e.url, name: part, zw: e.zw } : { t: 'text', s: part });
}
}
// build HTML; a zero-width emote joins the emote stack before it (skipping whitespace)
let html = '', open = false, count = 0, words = 0;
for (let k = 0; k < out.length; k++) {
const tk = out[k];
if (tk.t === 'text') {
if (/^\s*$/.test(tk.s)) {
const nx = out.slice(k + 1).find(x => !(x.t === 'text' && /^\s*$/.test(x.s)));
if (open && nx && nx.t === 'em' && nx.zw) continue; // keep the stack open for the overlay emote
if (open) { html += ''; open = false; }
html += esc(tk.s);
continue;
}
if (open) { html += ''; open = false; }
html += esc(tk.s); words++;
continue;
}
count++;
if (tk.zw && open) { html += img(tk.url, tk.name); continue; }
if (open) html += '';
html += '' + img(tk.url, tk.name); open = true;
}
if (open) html += '';
return { html, emoteOnly: count > 0 && words === 0, emoteCount: count };
}
// ---------- add / remove ----------
function tapeFrom(hex) {
const m = /^#?([0-9a-f]{6})$/i.exec(hex || '');
const n = m ? parseInt(m[1], 16) : 0xc9b6e4;
const c = [n >> 16, (n >> 8) & 255, n & 255].map(v => Math.round(v * .55 + 255 * .45));
return `rgba(${c[0]},${c[1]},${c[2]},.92)`;
}
const S = () => window.S || {};
function add(tags, text, isAction) {
if (tags && tags['room-id']) setRoom(tags['room-id']);
const name = (tags && (tags['display-name'] || tags.username)) || '?';
const r = render(text, tags && tags.emotes);
const d = document.createElement('div');
d.className = 'msg in' + (r.emoteOnly && r.emoteCount <= 3 ? ' big' : '') + (isAction ? ' action' : '');
d.dataset.id = (tags && tags.id) || '';
d.dataset.user = ((tags && tags.username) || '').toLowerCase();
d.style.setProperty('--tilt', (Math.random() * 3.2 - 1.6).toFixed(2) + 'deg');
d.style.setProperty('--tape', tapeFrom(tags && tags.color));
d.innerHTML = `${esc(name)}${r.html}`;
d._n = ++seq;
// FLIP: remember where the others are, put the new one on top, then glide them down from the old spot
const before = new Map([...box.children].map(m => [m, m.getBoundingClientRect().top]));
box.prepend(d);
before.forEach((top, m) => {
const dy = top - m.getBoundingClientRect().top;
if (dy && m.animate) m.animate([{ translate: `0 ${dy}px` }, { translate: '0 0' }], { duration: 320, easing: 'cubic-bezier(.2,.8,.3,1)' });
});
d.addEventListener('animationend', () => d.classList.remove('in'), { once: true });
// over the cap: the oldest leave with their exit animation
const live = [...box.children].filter(m => !m.classList.contains('out')).sort((a, b) => a._n - b._n);
const max = Number(S().max_messages) || 10;
live.slice(0, Math.max(0, live.length - max)).forEach(leave);
const t = Number(S().message_timeout);
if (t > 0) d._t = setTimeout(() => leave(d), t * 1000);
}
function leave(d) {
if (d.classList.contains('out')) return;
clearTimeout(d._t);
d.classList.remove('in');
d.classList.add('out');
d.addEventListener('animationend', () => d.remove(), { once: true });
setTimeout(() => d.remove(), 1200); // in case the animation never ends (hidden source)
}
// moderation: a deleted message, or everything from a user who got timed out / banned, leaves at once
function removeId(id) { [...box.children].filter(m => id && m.dataset.id === id).forEach(leave); }
function removeUser(user) { const u = String(user || '').toLowerCase(); [...box.children].filter(m => u && m.dataset.user === u).forEach(leave); }
function clear() { [...box.children].forEach(leave); }
window.HSChat = { add, removeId, removeUser, clear, setRoom, reload7tv: load7tv, render };
})();