Make twitch/youtube chat widget

This commit is contained in:
Joey Yakimowich-Payne 2026-01-07 12:47:09 -07:00
commit 0842dccf73
22 changed files with 3787 additions and 45 deletions

View file

@ -0,0 +1,277 @@
class LiveChatWidget {
constructor() {
this.ws = null;
this.messagesContainer = document.getElementById('chat-messages');
this.maxMessages = 50;
this.autoScroll = true;
this.reconnectAttempts = 0;
this.maxReconnectAttempts = 10;
this.platformIcons = {
twitch: `<svg width="20" height="20" viewBox="0 0 24 24" fill="#9146FF"><path d="M11.571 4.714h1.715v5.143H11.57zm4.715 0H18v5.143h-1.714zM6 0L1.714 4.286v15.428h5.143V24l4.286-4.286h3.428L22.286 12V0zm14.571 11.143l-3.428 3.428h-3.429l-3 3v-3H6.857V1.714h13.714Z"/></svg>`,
youtube: `<svg width="20" height="20" viewBox="0 0 24 24" fill="#FF0000"><path d="M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z"/></svg>`,
};
// Apply theme from URL query param
const urlParams = new URLSearchParams(window.location.search);
const theme = urlParams.get('theme');
if (theme === 'light') {
document.body.classList.add('theme-light');
} else {
document.body.classList.add('theme-dark');
}
// Direction: 'down' = newest at bottom (default), 'up' = newest at top
this.direction = urlParams.get('direction') || 'down';
if (this.direction === 'up') {
document.body.classList.add('direction-up');
}
this.init();
}
init() {
this.showStatus('Connecting to chat...', 'connecting');
this.connect();
// Handle scroll to detect manual scrolling
this.messagesContainer.addEventListener('scroll', () => {
const container = this.messagesContainer;
const isAtBottom = container.scrollHeight - container.scrollTop <= container.clientHeight + 50;
this.autoScroll = isAtBottom;
});
}
connect() {
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const wsUrl = `${protocol}//${window.location.host}/ws`;
this.ws = new WebSocket(wsUrl);
this.ws.onopen = () => {
console.log('Chat WebSocket connected');
this.reconnectAttempts = 0;
this.clearStatus();
};
this.ws.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
this.handleMessage(data);
} catch (err) {
console.error('Failed to parse message:', err);
}
};
this.ws.onerror = (error) => {
console.error('WebSocket error:', error);
};
this.ws.onclose = () => {
console.log('Chat WebSocket disconnected');
this.showStatus('Disconnected. Reconnecting...', 'error');
this.reconnect();
};
}
reconnect() {
if (this.reconnectAttempts >= this.maxReconnectAttempts) {
this.showStatus('Failed to connect. Please refresh.', 'error');
return;
}
this.reconnectAttempts++;
const delay = Math.min(1000 * Math.pow(2, this.reconnectAttempts), 30000);
setTimeout(() => {
console.log(`Reconnecting... (attempt ${this.reconnectAttempts})`);
this.connect();
}, delay);
}
handleMessage(data) {
switch (data.type) {
case 'chat_message':
this.addChatMessage(data.data);
break;
case 'chat_history':
// Initial history load (comes in oldest-to-newest order)
if (data.data && Array.isArray(data.data)) {
// For both directions, we add messages in order
// The addChatMessage handles placement based on direction
data.data.forEach(msg => this.addChatMessage(msg, false));
if (this.direction === 'down') {
this.scrollToBottom();
}
}
break;
default:
// Ignore other message types
break;
}
}
addChatMessage(messageData, shouldAnimate = true) {
const msgElement = this.createMessageElement(messageData);
if (!shouldAnimate) {
msgElement.style.animation = 'none';
}
if (this.direction === 'up') {
// Direction UP: newest at bottom (anchored), older messages bubble upward
// With flex-direction: column-reverse, prepending puts new message at visual bottom
this.messagesContainer.insertBefore(msgElement, this.messagesContainer.firstChild);
// Limit total messages (remove oldest = last child = visually at top)
while (this.messagesContainer.children.length > this.maxMessages) {
this.messagesContainer.removeChild(this.messagesContainer.lastChild);
}
} else {
// Direction DOWN (default): newest at bottom, scroll down
this.messagesContainer.appendChild(msgElement);
// Limit total messages (remove oldest = first child = visually at top)
while (this.messagesContainer.children.length > this.maxMessages) {
this.messagesContainer.removeChild(this.messagesContainer.firstChild);
}
if (this.autoScroll) {
this.scrollToBottom();
}
}
}
createMessageElement(data) {
const msg = document.createElement('div');
msg.className = `chat-message ${data.platform}`;
msg.dataset.messageId = data.id;
if (data.is_action) {
msg.classList.add('action');
}
// Platform icon (optional)
if (data.platform) {
const iconDiv = document.createElement('div');
iconDiv.className = 'platform-icon';
iconDiv.innerHTML = this.platformIcons[data.platform] || '';
msg.appendChild(iconDiv);
}
// Message content
const content = document.createElement('div');
content.className = 'message-content';
// User info line
const userInfo = document.createElement('div');
userInfo.className = 'user-info';
// Badges
if (data.user.badges && data.user.badges.length > 0) {
const badgesContainer = document.createElement('div');
badgesContainer.className = 'user-badges';
data.user.badges.forEach(badge => {
const badgeEl = document.createElement('span');
badgeEl.className = 'badge';
badgeEl.title = badge.name;
if (badge.icon_url) {
badgeEl.innerHTML = `<img src="${badge.icon_url}" alt="${badge.name}">`;
} else {
// Simple text badge fallback
badgeEl.textContent = badge.name.charAt(0).toUpperCase();
}
badgesContainer.appendChild(badgeEl);
});
userInfo.appendChild(badgesContainer);
}
// Username
const username = document.createElement('span');
username.className = 'username';
username.textContent = data.user.display_name;
if (data.user.color) {
username.style.color = data.user.color;
}
userInfo.appendChild(username);
// Timestamp (optional)
const timestamp = document.createElement('span');
timestamp.className = 'timestamp';
timestamp.textContent = this.formatTime(data.timestamp);
userInfo.appendChild(timestamp);
content.appendChild(userInfo);
// Message text with emotes
const messageText = document.createElement('div');
messageText.className = 'message-text';
messageText.innerHTML = this.parseMessageWithEmotes(data.message, data.emotes);
content.appendChild(messageText);
msg.appendChild(content);
return msg;
}
parseMessageWithEmotes(message, emotes) {
if (!emotes || emotes.length === 0) {
return this.escapeHtml(message);
}
// Build a map of emote codes to emote data
const emoteMap = {};
emotes.forEach(emote => {
emoteMap[emote.code] = emote;
});
// Split message into words and replace emotes
const words = message.split(' ');
const result = words.map(word => {
if (emoteMap[word]) {
const emote = emoteMap[word];
const animatedClass = emote.is_animated ? 'animated' : '';
return `<img class="emote ${animatedClass}" src="${emote.url}" alt="${emote.code}" title="${emote.code} (${emote.provider})">`;
}
return this.escapeHtml(word);
});
return result.join(' ');
}
escapeHtml(text) {
const div = document.createElement('div');
div.textContent = text;
return div.innerHTML;
}
formatTime(timestamp) {
const date = new Date(timestamp);
const hours = date.getHours().toString().padStart(2, '0');
const minutes = date.getMinutes().toString().padStart(2, '0');
return `${hours}:${minutes}`;
}
scrollToBottom() {
this.messagesContainer.scrollTop = this.messagesContainer.scrollHeight;
}
showStatus(message, className = '') {
this.messagesContainer.innerHTML = `<div class="status-message ${className}">${message}</div>`;
}
clearStatus() {
const statusMsg = this.messagesContainer.querySelector('.status-message');
if (statusMsg) {
statusMsg.remove();
}
}
}
// Initialize when DOM is ready
document.addEventListener('DOMContentLoaded', () => {
new LiveChatWidget();
});

View file

@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Chat</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="chat-container">
<div id="chat-messages"></div>
</div>
<script src="app.js"></script>
</body>
</html>

View file

@ -0,0 +1,266 @@
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: transparent;
overflow: hidden;
color: #fff; /* Default dark mode text */
}
/* Light Theme overrides */
body.theme-light {
color: #1a1a1a;
}
body.theme-light .chat-message {
background: rgba(255, 255, 255, 0.85);
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
body.theme-light .username {
text-shadow: none;
}
body.theme-light .timestamp {
color: #666;
}
body.theme-light .badge {
background: rgba(0, 0, 0, 0.1);
color: #333;
}
body.theme-light #chat-messages::-webkit-scrollbar-thumb {
background: rgba(0, 0, 0, 0.2);
}
/* Dark Theme (Default) overrides for clarity */
body.theme-dark .chat-message {
background: rgba(0, 0, 0, 0.6);
}
#chat-container {
width: 100vw;
height: 100vh;
display: flex;
flex-direction: column;
padding: 10px;
}
#chat-messages {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
display: flex;
flex-direction: column;
gap: 4px;
}
/* Hide scrollbar but keep functionality */
#chat-messages::-webkit-scrollbar {
width: 4px;
}
#chat-messages::-webkit-scrollbar-track {
background: transparent;
}
#chat-messages::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.2);
border-radius: 2px;
}
/* Chat message */
.chat-message {
display: flex;
align-items: flex-start;
gap: 8px;
padding: 6px 10px;
background: rgba(0, 0, 0, 0.4);
border-radius: 4px;
animation: slideIn 0.2s ease-out;
word-wrap: break-word;
}
@keyframes slideIn {
from {
opacity: 0;
transform: translateX(-20px);
}
to {
opacity: 1;
transform: translateX(0);
}
}
/* Direction UP: Messages anchor to bottom, bubble upward */
body.direction-up #chat-messages {
flex-direction: column-reverse;
justify-content: flex-start;
}
body.direction-up .chat-message {
animation: slideUp 0.2s ease-out;
}
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.chat-message.twitch {
border-left: 3px solid #9146FF;
}
.chat-message.youtube {
border-left: 3px solid #FF0000;
}
.chat-message.action {
font-style: italic;
background: rgba(100, 100, 100, 0.3);
}
/* Platform icon */
.platform-icon {
flex-shrink: 0;
width: 20px;
height: 20px;
margin-top: 2px;
}
.platform-icon img {
width: 100%;
height: 100%;
}
/* Message content area */
.message-content {
flex: 1;
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
/* User info line */
.user-info {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.user-badges {
display: flex;
gap: 4px;
align-items: center;
}
.badge {
width: 18px;
height: 18px;
display: inline-flex;
align-items: center;
justify-content: center;
vertical-align: middle;
font-size: 10px;
font-weight: bold;
background: rgba(255, 255, 255, 0.15);
border-radius: 3px;
color: #fff;
text-transform: uppercase;
}
.badge img {
width: 100%;
height: 100%;
border-radius: 3px;
}
.username {
font-weight: bold;
font-size: 14px;
text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.8);
}
.timestamp {
font-size: 11px;
color: #aaa;
opacity: 0.8;
}
/* Message text */
.message-text {
font-size: 14px;
line-height: 1.4;
word-wrap: break-word;
overflow-wrap: break-word;
}
/* Emotes */
.emote {
display: inline-block;
vertical-align: middle;
margin: 0 2px;
max-height: 28px;
max-width: 28px;
image-rendering: pixelated;
}
.emote.animated {
image-rendering: auto;
}
/* Roles */
.role-badge {
display: inline-block;
padding: 2px 6px;
border-radius: 3px;
font-size: 10px;
font-weight: bold;
text-transform: uppercase;
background: rgba(255, 255, 255, 0.1);
}
.role-badge.broadcaster {
background: #e91916;
}
.role-badge.moderator {
background: #00ad03;
}
.role-badge.vip {
background: #e005b9;
}
.role-badge.subscriber {
background: #6441a5;
}
/* Loading/Error states */
.status-message {
text-align: center;
padding: 20px;
color: #aaa;
font-size: 14px;
}
.error {
color: #ff6b6b;
}
.connecting {
color: #4ecdc4;
}