Chat: paper slips under the camera, Twitch + 7TV emotes

- public/chat/chat.css + chat.js (window.HSChat): cream paper slips with the
  name on a washi-tape label, newest on top sliding out from under the webcam,
  older ones glide down and fade at the bottom; message_timeout / max_messages
- Emotes: Twitch (tags.emotes) and 7TV global + channel sets (refreshed every
  10 min), zero-width 7TV emotes stack, emote-only messages get bigger emotes
- Deleted messages, timeouts, bans and /clear remove slips at once
- overlay.ejs: old chat CSS/JS removed, new files load only for ?parts=chat

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-11-21 12:08:12 +02:00
parent 0cc53e1d73
commit 463c6580f4
4 changed files with 264 additions and 55 deletions

View file

@ -120,10 +120,20 @@ const flt = (v, d) => { const n = parseFloat(v); return isNaN(n) ? d : n; };
## Overlay chat position and style
The layout editor was removed (2026-11-20). Chat box position/size/font and the legacy text/video action alert
position are fixed CSS custom properties in the `:root` block of `views/overlay.ejs` (values copied from the last
saved layout). Change them there, or override with Custom CSS in Settings. The `overlay_layout` table is still
created but unused, so old data is kept.
The layout editor was removed (2026-11-20); the `overlay_layout` table is still created but unused, so old data is kept.
The legacy text/video action alert position lives in the `:root` block of `views/overlay.ejs`.
Chat (`?parts=chat`) is `public/chat/chat.css` + `public/chat/chat.js` (window.HSChat), fed by tmi.js in overlay.ejs:
- Look: cream paper slips, name on a washi-tape label tinted with the chatter's Twitch colour, slight random tilt.
- Flow: the box sits under the webcam (Game scene camera group 1920,600 640x360 on the 2560 canvas), newest on top;
a new message slides out from under the camera, the rest glide down (FLIP with the `translate` property) and the
oldest dissolve at the bottom (mask-image fade). Expire after `message_timeout` s, cap `max_messages`.
- Move/resize with Custom CSS: `#chat { --chat-top: 63%; --chat-right: 2%; --chat-width: 20%; --chat-height: 34%; }`.
- Emotes: Twitch (from `tags.emotes`, code-point ranges) + 7TV global and channel sets (`7tv.io/v3`, channel by
`room-id` from ROOMSTATE, refreshed every 10 min). 7TV zero-width emotes (data flag 256) stack on the emote before.
Emote-only messages (up to 3 emotes) get bigger emotes.
- Moderation: deleted messages, timeouts, bans and /clear remove the matching slips at once.
- Design preview with other styles: `~/Desktop/Stream/chat/index.html` (not in the repo).
## Gap / new-message audio

71
public/chat/chat.css Normal file
View file

@ -0,0 +1,71 @@
/* Chat: cream paper slips with the name on a washi-tape label ("style 5" from the chat preview).
The box sits under the webcam (Game scene: camera group at 1920,600, 640x360 on the 2560 canvas
= 1440,450 480x270 on this 1920x1080 page). Newest message on top, slides out from under the camera,
older ones are pushed down and dissolve at the bottom edge.
Move or resize it with Custom CSS in Settings, e.g. #chat { --chat-top: 60%; --chat-height: 37%; } */
#chat {
--chat-right: 2%;
--chat-top: 63%; /* 680px: just above the bottom of the camera ring, so messages come out from under it */
--chat-width: 20%;
--chat-height: 34%; /* down to the bottom edge */
--ink: #3a2a20;
--cream: #fffdf7;
position: fixed;
right: var(--chat-right);
top: var(--chat-top);
width: var(--chat-width);
height: var(--chat-height);
display: flex;
flex-direction: column;
justify-content: flex-start;
gap: 8px;
padding: 26px 8px 0;
overflow: hidden;
-webkit-mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent);
mask-image: linear-gradient(transparent 0, #000 30px, #000 calc(100% - 60px), transparent);
}
#chat .msg {
position: relative;
flex: none;
margin: 9px 6px 0;
padding: 19px 14px 9px;
border-radius: 2px;
background: var(--cream);
color: var(--ink);
font: 800 17px/1.3 Nunito, sans-serif;
word-break: break-word;
box-shadow: 0 3px 8px rgba(0, 0, 0, .35);
transform: rotate(var(--tilt, 0deg));
}
#chat .msg.action { font-style: italic; }
/* the name on a strip of washi tape, tinted with the chatter's Twitch colour */
#chat .msg .u {
position: absolute;
top: -12px;
left: 10px;
max-width: 85%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
padding: 1px 12px 2px;
font: 700 23px/1 Caveat, cursive;
color: var(--ink);
background-color: var(--tape, rgba(201, 182, 228, .92));
background-image: repeating-linear-gradient(45deg, #fff5 0 6px, #0000 6px 12px);
transform: rotate(calc(var(--tilt, 0deg) * -2));
box-shadow: 0 1px 2px rgba(0, 0, 0, .2);
clip-path: polygon(0 8%, 3% 0, 97% 4%, 100% 0, 98% 100%, 2% 94%);
}
/* emotes (Twitch + 7TV). Zero-width 7TV emotes (RainTime, PETPET...) stack on the emote before them. */
#chat .em { position: relative; display: inline-grid; vertical-align: -0.45em; margin: 0 1px; }
#chat .em > img { grid-area: 1 / 1; height: 1.6em; width: auto; justify-self: center; align-self: center;
filter: drop-shadow(0 0 1px rgba(58, 42, 32, .55)); } /* white emotes (Clap...) stay visible on cream */
#chat .msg.big .em > img { height: 2.6em; } /* emote-only messages: bigger emotes */
#chat .msg.in { animation: chat-in .45s cubic-bezier(.2, 1.3, .4, 1) both; }
#chat .msg.out { animation: chat-out .6s ease-in both; }
@keyframes chat-in { from { opacity: 0; transform: translateY(-24px) rotate(calc(var(--tilt, 0deg) * -3)) scale(.95); } }
@keyframes chat-out { to { opacity: 0; transform: translate(40px, 30px) rotate(calc(var(--tilt, 0deg) + 12deg)); } }

164
public/chat/chat.js Normal file
View file

@ -0,0 +1,164 @@
/* 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 => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const img = (url, name) => `<img src="${esc(url)}" alt="${esc(name)}" title="${esc(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 += '</span>'; open = false; }
html += esc(tk.s);
continue;
}
if (open) { html += '</span>'; open = false; }
html += esc(tk.s); words++;
continue;
}
count++;
if (tk.zw && open) { html += img(tk.url, tk.name); continue; }
if (open) html += '</span>';
html += '<span class="em">' + img(tk.url, tk.name); open = true;
}
if (open) html += '</span>';
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 = `<span class="u">${esc(name)}</span>${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 };
})();

View file

@ -10,6 +10,7 @@
<link rel="stylesheet" href="/alerts/cassette.css">
<link rel="stylesheet" href="/alerts/fx.css">
<% } %>
<% if (has('chat')) { %><link rel="stylesheet" href="/chat/chat.css"><% } %>
<% if (has('poll')) { %><link rel="stylesheet" href="/alerts/poll.css"><% } %>
<% if (has('hypebar')) { %><link rel="stylesheet" href="/alerts/hypebar.css"><% } %>
<% if (has('raid')) { %><link rel="stylesheet" href="/alerts/raidcard.css"><% } %>
@ -19,18 +20,10 @@
<script src="/alerts/nowplaying.js"></script> (same)
the nowplaying line in ws.onmessage below %>
<style>
/* Chat box and legacy text/video action alerts. Values were taken from the layout editor
(removed 2026-11-20); change them here, or override with Custom CSS in Settings. */
/* Legacy text/video action alerts. Values were taken from the layout editor (removed 2026-11-20);
change them here, or override with Custom CSS in Settings. The chat has its own /chat/chat.css. */
:root {
--chat-left: 78%;
--chat-top: 75%;
--chat-width: 20%;
--chat-height: 23%;
--chat-font-size: 16px;
--chat-font-family: Inter, sans-serif;
--chat-bg-opacity: 0.1;
--chat-text-color: #ffffff;
--chat-border-radius: 10px;
--alert-left: 50%;
--alert-top: 40%;
--alert-font-size: 32px;
@ -40,30 +33,6 @@
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: transparent; overflow: hidden; width: 1920px; height: 1080px; }
#chat {
position: fixed;
left: var(--chat-left);
top: var(--chat-top);
width: var(--chat-width);
max-height: var(--chat-height);
overflow: hidden;
display: flex;
flex-direction: column;
gap: 4px;
font-family: var(--chat-font-family);
font-size: var(--chat-font-size);
color: var(--chat-text-color);
}
.chat-msg {
background: rgba(0, 0, 0, var(--chat-bg-opacity));
border-radius: var(--chat-border-radius);
padding: 5px 10px;
word-break: break-word;
animation: fadeIn 0.25s ease;
transition: opacity 0.5s ease;
}
.chat-msg .username { font-weight: 700; margin-right: 4px; }
#alert-box {
position: fixed;
left: var(--alert-left);
@ -103,6 +72,7 @@
<video id="alert-video" autoplay></video><% } %>
<script src="/vendor/tmi.min.js"></script>
<% if (has('chat')) { %><script src="/chat/chat.js"></script><% } %>
<% if (has('alerts')) { %>
<script src="/alerts/cassette.js"></script>
<script src="/alerts/fx.js"></script>
@ -113,6 +83,7 @@
<% if (has('raid')) { %><script src="/alerts/raidcard.js"></script><% } %>
<script>
const S = <%- JSON.stringify(settings) %>;
window.S = S; // chat.js reads message_timeout / max_messages from here (settings_update keeps it current)
// which parts this browser source shows (?parts=chat / ?parts=nochat / ?parts=chat,raid / nothing = all)
const PARTS = new Set(<%- JSON.stringify(parts) %>);
const chat = document.getElementById('chat'); // null when this source has no chat part
@ -135,6 +106,15 @@
user: t['display-name'] || t.login, streak: t['msg-param-value'] });
});
// channel id for the 7TV channel emotes, and moderation: deleted messages / timeouts / bans leave the screen
if (PARTS.has('chat')) {
client.on('roomstate', (_ch, state) => HSChat.setRoom(state['room-id']));
client.on('messagedeleted', (_ch, _user, _msg, tags) => HSChat.removeId(tags['target-msg-id']));
client.on('timeout', (_ch, user) => HSChat.removeUser(user));
client.on('ban', (_ch, user) => HSChat.removeUser(user));
client.on('clearchat', () => HSChat.clear());
}
client.on('message', (channel, tags, message) => {
if (!PARTS.has('chat')) return; // other sources only listen to chat for watch streaks
const now = Date.now();
@ -152,26 +132,10 @@
}
lastMsgTime = now;
addMessage(tags['display-name'] || tags.username, tags.color || '#b4a0d4', message);
HSChat.add(tags, message, tags['message-type'] === 'action');
});
}
function addMessage(username, color, text) {
const div = document.createElement('div');
div.className = 'chat-msg';
div.innerHTML = `<span class="username" style="color:${esc(color)}">${esc(username)}</span>: ${esc(text)}`;
chat.appendChild(div);
while (chat.children.length > S.max_messages) chat.removeChild(chat.firstChild);
if (S.message_timeout > 0) {
setTimeout(() => {
div.style.opacity = '0';
setTimeout(() => div.remove(), 500);
}, S.message_timeout * 1000);
}
}
// --- Alert WebSocket ---
// ?overlay=<id> marks this page as the real overlay, so the server accepts chat_notice messages from it
let ws = null;