feat: improve superchat and membership handling with fallback fields and UI panels

This commit is contained in:
Yusuf İpek
2025-10-05 04:42:47 +03:00
parent 18d2f78516
commit c973b8b176
5 changed files with 388 additions and 136 deletions
+33 -4
View File
@@ -154,12 +154,32 @@ function extractBadges(item: any): Badge[] {
function extractSuperChatInfo(item: any): SuperChatInfo | undefined { function extractSuperChatInfo(item: any): SuperChatInfo | undefined {
if (item.type !== 'LiveChatPaidMessage') return undefined; if (item.type !== 'LiveChatPaidMessage') return undefined;
const amount = item.purchase_amount_text?.toString() ?? ''; // Try multiple possible field names for the amount
let amount = '';
if (item.purchase_amount_text) {
amount = typeof item.purchase_amount_text === 'string'
? item.purchase_amount_text
: item.purchase_amount_text.simpleText || item.purchase_amount_text.toString();
} else if (item.purchaseAmountText) {
amount = typeof item.purchaseAmountText === 'string'
? item.purchaseAmountText
: item.purchaseAmountText.simpleText || item.purchaseAmountText.toString();
} else if (item.amount) {
amount = item.amount.toString();
}
// Try multiple possible field names for color
const color = item.body_background_color?.toString()
|| item.bodyBackgroundColor?.toString()
|| item.headerBackgroundColor?.toString()
|| '#1e3a8a';
console.log('[SuperChat] Extracted:', { amount, color, rawItem: item });
return { return {
amount, amount: amount || 'Super Chat',
currency: item.currency ?? 'USD', currency: item.currency ?? 'USD',
color: item.body_background_color?.toString() ?? '#1e3a8a' color
}; };
} }
@@ -181,6 +201,14 @@ function normalizeAction(action: any): ChatMessage | null {
const isMember = badges.some(b => b.type === 'member'); const isMember = badges.some(b => b.type === 'member');
const isVerified = badges.some(b => b.type === 'verified'); const isVerified = badges.some(b => b.type === 'verified');
// Extract membership level for new members
let membershipLevel: string | undefined;
if (item.type === 'LiveChatMembershipItem') {
membershipLevel = item.header_subtext?.toString() ||
item.header_primary_text?.toString() ||
'New member';
}
return { return {
id: String(item.id ?? item.timestamp_usec ?? Date.now()), id: String(item.id ?? item.timestamp_usec ?? Date.now()),
author: String(item.author?.name ?? 'Unknown'), author: String(item.author?.name ?? 'Unknown'),
@@ -192,7 +220,8 @@ function normalizeAction(action: any): ChatMessage | null {
isMember, isMember,
isVerified, isVerified,
superChat: extractSuperChatInfo(item), superChat: extractSuperChatInfo(item),
membershipGift: item.type === 'LiveChatMembershipItem' membershipGift: item.type === 'LiveChatMembershipItem',
membershipLevel
}; };
} }
+158 -77
View File
@@ -1,11 +1,15 @@
'use client'; 'use client';
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useState, useRef } from 'react';
import type { ChatMessage } from '@shared/chat'; import type { ChatMessage } from '@shared/chat';
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100'; const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100';
const POLL_INTERVAL = 2500; const POLL_INTERVAL = 2500;
// Global singleton to prevent multiple SSE connections across all renders/remounts
let globalSSEConnection: EventSource | null = null;
let globalConnectionListeners: Set<(payload: any) => void> = new Set();
export default function DashboardPage() { export default function DashboardPage() {
const { messages, refresh, error: pollError } = useChatMessages(); const { messages, refresh, error: pollError } = useChatMessages();
const { selection, status: overlayStatus } = useOverlaySelection(); const { selection, status: overlayStatus } = useOverlaySelection();
@@ -49,6 +53,10 @@ export default function DashboardPage() {
return 'Live'; return 'Live';
}, [pollError, overlayStatus]); }, [pollError, overlayStatus]);
const superChats = useMemo(() => messages.filter(m => m.superChat), [messages]);
const newMembers = useMemo(() => messages.filter(m => m.membershipGift), [messages]);
const regularMessages = useMemo(() => messages.filter(m => !m.superChat && !m.membershipGift), [messages]);
return ( return (
<main className="dashboard"> <main className="dashboard">
<header className="dashboard__header"> <header className="dashboard__header">
@@ -70,10 +78,12 @@ export default function DashboardPage() {
onDisconnect={disconnect} onDisconnect={disconnect}
/> />
<section className="dashboard__main"> <section className="dashboard__grid">
<div className="chatPanel"> {/* Main Chat Column */}
<div className="chatPanel__header"> <div className="chatColumn">
<h2>Live Chat Stream</h2> <div className="panel">
<div className="panel__header">
<h2>💬 Live Chat</h2>
{selection && ( {selection && (
<button className="btn-clear" onClick={handleClear}> <button className="btn-clear" onClick={handleClear}>
Clear Selection Clear Selection
@@ -81,84 +91,71 @@ export default function DashboardPage() {
)} )}
</div> </div>
<div className="chatList"> <div className="chatList">
{messages.map((message) => ( {regularMessages.map((message) => (
<button <ChatItem
key={message.id} key={message.id}
className={ message={message}
selection?.id === message.id ? 'chatItem chatItem--active' : 'chatItem' isSelected={selection?.id === message.id}
} onSelect={() => handleSelect(message)}
onClick={() => handleSelect(message)} />
>
<div className="chatItem__header">
{message.authorPhoto && (
<img src={message.authorPhoto} alt={message.author} className="chatItem__avatar" />
)}
<div className="chatItem__meta">
<div className="chatItem__authorLine">
<span className="chatItem__author">{message.author}</span>
{message.badges && message.badges.map((badge, i) => (
<span key={i} className={`badge badge--${badge.type}`} title={badge.label}>
{badge.type === 'moderator' && '🛡️'}
{badge.type === 'member' && '⭐'}
{badge.type === 'verified' && '✓'}
</span>
))} ))}
</div> {regularMessages.length === 0 && (
<time className="chatItem__time">{new Date(message.publishedAt).toLocaleTimeString()}</time>
</div>
</div>
{message.superChat && (
<div className="chatItem__superchat" style={{ backgroundColor: message.superChat.color }}>
💰 Super Chat: {message.superChat.amount}
</div>
)}
{message.membershipGift && (
<div className="chatItem__membership">
🎁 New Member!
</div>
)}
<p className="chatItem__text">{message.text}</p>
</button>
))}
{messages.length === 0 && (
<div className="chatList__empty"> <div className="chatList__empty">
<p> Waiting for chat messages...</p> <p> Waiting for chat messages...</p>
</div> </div>
)} )}
</div> </div>
</div> </div>
</div>
{selection && ( {/* Right Split Column */}
<div className="selectedPreview"> <div className="splitColumn">
<h3>🎯 Selected for Overlay</h3> {/* Super Chats - Top Half */}
<div className="selectedPreview__card"> <div className="panel">
<div className="selectedPreview__header"> <div className="panel__header">
{selection.authorPhoto && ( <h2>💰 Super Chats</h2>
<img src={selection.authorPhoto} alt={selection.author} className="selectedPreview__avatar" /> <span className="badge badge--count">{superChats.length}</span>
)} </div>
<div> <div className="chatList">
<div className="selectedPreview__authorLine"> {superChats.map((message) => (
<span className="selectedPreview__author">{selection.author}</span> <ChatItem
{selection.badges && selection.badges.map((badge, i) => ( key={message.id}
<span key={i} className={`badge badge--${badge.type}`} title={badge.label}> message={message}
{badge.type === 'moderator' && '🛡️'} isSelected={selection?.id === message.id}
{badge.type === 'member' && '⭐'} onSelect={() => handleSelect(message)}
{badge.type === 'verified' && '✓'} />
</span>
))} ))}
</div> {superChats.length === 0 && (
<time>{new Date(selection.publishedAt).toLocaleTimeString()}</time> <div className="chatList__empty">
</div> <p>No super chats yet</p>
</div>
{selection.superChat && (
<div className="selectedPreview__superchat" style={{ backgroundColor: selection.superChat.color }}>
💰 {selection.superChat.amount}
</div> </div>
)} )}
<p className="selectedPreview__text">{selection.text}</p>
</div> </div>
</div> </div>
{/* New Members - Bottom Half */}
<div className="panel">
<div className="panel__header">
<h2> New Members</h2>
<span className="badge badge--count">{newMembers.length}</span>
</div>
<div className="chatList">
{newMembers.map((message) => (
<MemberItem
key={message.id}
message={message}
isSelected={selection?.id === message.id}
onSelect={() => handleSelect(message)}
/>
))}
{newMembers.length === 0 && (
<div className="chatList__empty">
<p>No new members yet</p>
</div>
)} )}
</div>
</div>
</div>
</section> </section>
</main> </main>
); );
@@ -196,27 +193,48 @@ type SelectionPayload = {
function useOverlaySelection() { function useOverlaySelection() {
const [selection, setSelection] = useState<ChatMessage | null>(null); const [selection, setSelection] = useState<ChatMessage | null>(null);
const [status, setStatus] = useState<OverlayStatus>('connecting'); const [status, setStatus] = useState<OverlayStatus>('connecting');
const listenerRef = useRef<((payload: any) => void) | null>(null);
useEffect(() => { useEffect(() => {
const source = new EventSource(`${BACKEND_URL}/overlay/stream`); // Create global connection if it doesn't exist
if (!globalSSEConnection) {
console.log('[Dashboard] Creating GLOBAL SSE connection');
globalSSEConnection = new EventSource(`${BACKEND_URL}/overlay/stream`);
const onSelection = (event: MessageEvent) => { globalSSEConnection.addEventListener('selection', ((event: MessageEvent) => {
try { try {
const payload: SelectionPayload = JSON.parse(event.data); const payload: SelectionPayload = JSON.parse(event.data);
setSelection(payload.message); // Broadcast to all listeners
setStatus('live'); globalConnectionListeners.forEach(listener => listener(payload));
} catch (error) { } catch (error) {
console.error('Failed to parse selection payload', error); console.error('Failed to parse selection payload', error);
} }
}) as EventListener);
globalSSEConnection.addEventListener('heartbeat', () => {
// Heartbeat - connection is alive
});
globalSSEConnection.onerror = () => {
console.error('[Dashboard] SSE error');
};
}
// Register this component's listener
const myListener = (payload: SelectionPayload) => {
setSelection(payload.message);
setStatus('live');
}; };
source.addEventListener('selection', onSelection as EventListener); listenerRef.current = myListener;
source.addEventListener('heartbeat', () => setStatus('live')); globalConnectionListeners.add(myListener);
source.onerror = () => setStatus('error');
return () => { return () => {
source.removeEventListener('selection', onSelection as EventListener); // Unregister this component's listener
source.close(); if (listenerRef.current) {
globalConnectionListeners.delete(listenerRef.current);
}
// Don't close global connection - other components might use it
}; };
}, []); }, []);
@@ -337,3 +355,66 @@ function ConnectionControl({ connected, liveId, connecting, onConnect, onDisconn
</div> </div>
); );
} }
type ChatItemProps = {
message: ChatMessage;
isSelected: boolean;
onSelect: () => void;
};
function ChatItem({ message, isSelected, onSelect }: ChatItemProps) {
return (
<button
className={isSelected ? 'chatItem chatItem--active' : 'chatItem'}
onClick={onSelect}
>
<div className="chatItem__header">
{message.authorPhoto && (
<img src={message.authorPhoto} alt={message.author} className="chatItem__avatar" />
)}
<div className="chatItem__meta">
<div className="chatItem__authorLine">
<span className="chatItem__author">{message.author}</span>
{message.badges && message.badges.map((badge, i) => (
<span key={i} className={`badge badge--${badge.type}`} title={badge.label}>
{badge.type === 'moderator' && '🛡️'}
{badge.type === 'member' && '⭐'}
{badge.type === 'verified' && '✓'}
</span>
))}
</div>
<time className="chatItem__time">{new Date(message.publishedAt).toLocaleTimeString()}</time>
</div>
</div>
{message.superChat && (
<div className="chatItem__superchat" style={{ backgroundColor: message.superChat.color }}>
💰 {message.superChat.amount}
</div>
)}
<p className="chatItem__text">{message.text}</p>
</button>
);
}
function MemberItem({ message, isSelected, onSelect }: ChatItemProps) {
return (
<button
className={isSelected ? 'memberItem memberItem--active' : 'memberItem'}
onClick={onSelect}
>
<div className="memberItem__header">
{message.authorPhoto && (
<img src={message.authorPhoto} alt={message.author} className="memberItem__avatar" />
)}
<div className="memberItem__info">
<span className="memberItem__author">{message.author}</span>
<span className="memberItem__level">
{message.membershipLevel || 'New member'}
</span>
<time className="memberItem__time">{new Date(message.publishedAt).toLocaleTimeString()}</time>
</div>
</div>
{message.text && <p className="memberItem__text">{message.text}</p>}
</button>
);
}
+164 -34
View File
@@ -81,7 +81,8 @@ main {
.dashboard { .dashboard {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
min-height: 100vh; height: 100vh;
overflow: hidden;
background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%); background: linear-gradient(135deg, #0f172a 0%, #1e1b4b 100%);
} }
@@ -89,7 +90,7 @@ main {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
padding: 2rem clamp(1.5rem, 5vw, 4rem); padding: 1.25rem clamp(1rem, 3vw, 2rem);
background: rgba(15, 23, 42, 0.6); background: rgba(15, 23, 42, 0.6);
border-bottom: 1px solid rgba(255, 255, 255, 0.1); border-bottom: 1px solid rgba(255, 255, 255, 0.1);
backdrop-filter: blur(10px); backdrop-filter: blur(10px);
@@ -119,21 +120,32 @@ main {
color: #94a3b8; color: #94a3b8;
} }
.dashboard__main { .dashboard__grid {
flex: 1; flex: 1;
display: flex; display: flex;
flex-direction: column; gap: 0.75rem;
align-items: center; padding: 1rem clamp(1rem, 3vw, 2rem);
padding: 0 clamp(1rem, 5vw, 3rem) 2rem;
gap: 2rem;
max-width: 1400px;
width: 100%; width: 100%;
max-width: 100%;
margin: 0 auto; margin: 0 auto;
min-height: 0;
overflow: hidden;
}
@media (max-width: 1100px) {
.dashboard__grid {
flex-direction: column;
}
.chatColumn,
.splitColumn {
flex: 1 1 auto;
}
} }
.connectionControl { .connectionControl {
width: 100%; width: 100%;
padding: 1.5rem clamp(1rem, 5vw, 3rem); padding: 1rem clamp(1rem, 3vw, 2rem);
background: rgba(30, 41, 59, 0.5); background: rgba(30, 41, 59, 0.5);
border-bottom: 1px solid rgba(255, 255, 255, 0.1); border-bottom: 1px solid rgba(255, 255, 255, 0.1);
} }
@@ -265,28 +277,71 @@ main {
} }
} }
.chatPanel { .chatColumn {
width: 100%; display: flex;
background: rgba(30, 41, 59, 0.4); flex-direction: column;
border: 1px solid rgba(255, 255, 255, 0.1); flex: 1 1 55%;
border-radius: 20px; min-height: 0;
padding: 1.5rem; min-width: 0;
backdrop-filter: blur(10px); overflow: hidden;
} }
.chatPanel__header { .splitColumn {
display: flex;
flex-direction: column;
flex: 1 1 45%;
gap: 0.5rem;
min-height: 0;
min-width: 0;
overflow: hidden;
}
.splitColumn .panel {
flex: 1;
min-height: 0;
}
.panel {
background: rgba(30, 41, 59, 0.4);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
padding: 1rem;
backdrop-filter: blur(10px);
display: flex;
flex-direction: column;
min-height: 0;
min-width: 0;
max-width: 100%;
height: 100%;
overflow: hidden;
}
.panel__header {
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 1.5rem; margin-bottom: 1rem;
padding-bottom: 1rem; padding-bottom: 0.75rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1); border-bottom: 1px solid rgba(255, 255, 255, 0.1);
flex-shrink: 0;
} }
.chatPanel__header h2 { .panel__header h2 {
margin: 0; margin: 0;
font-size: 1.3rem; font-size: 1.2rem;
color: #e2e8f0; color: #e2e8f0;
display: flex;
align-items: center;
gap: 0.5rem;
}
.badge--count {
background: rgba(96, 165, 250, 0.2);
color: #60a5fa;
padding: 0.25rem 0.6rem;
border-radius: 999px;
font-size: 0.8rem;
font-weight: 700;
} }
.btn-clear { .btn-clear {
@@ -308,10 +363,12 @@ main {
.chatList { .chatList {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.75rem; gap: 0.5rem;
max-height: 65vh; flex: 1;
overflow-y: auto; overflow-y: auto;
padding-right: 0.5rem; overflow-x: hidden;
padding-right: 0.25rem;
min-height: 0;
} }
.chatList::-webkit-scrollbar { .chatList::-webkit-scrollbar {
@@ -343,14 +400,15 @@ main {
.chatItem { .chatItem {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 0.75rem; gap: 0.5rem;
padding: 1rem 1.25rem; padding: 0.75rem 1rem;
border-radius: 12px; border-radius: 10px;
background: rgba(15, 23, 42, 0.6); background: rgba(15, 23, 42, 0.6);
border: 1px solid rgba(255, 255, 255, 0.06); border: 1px solid rgba(255, 255, 255, 0.06);
text-align: left; text-align: left;
transition: all 150ms ease; transition: all 150ms ease;
cursor: pointer; cursor: pointer;
flex-shrink: 0;
} }
.chatItem:hover { .chatItem:hover {
@@ -408,6 +466,8 @@ main {
margin: 0; margin: 0;
line-height: 1.5; line-height: 1.5;
color: #e2e8f0; color: #e2e8f0;
word-break: break-word;
overflow-wrap: break-word;
font-size: 0.95rem; font-size: 0.95rem;
} }
@@ -453,6 +513,77 @@ main {
color: #93c5fd; color: #93c5fd;
} }
.memberItem {
display: flex;
flex-direction: column;
gap: 0.5rem;
padding: 0.75rem 1rem;
border-radius: 10px;
background: linear-gradient(135deg, rgba(16, 185, 129, 0.1), rgba(5, 150, 105, 0.1));
border: 1px solid rgba(16, 185, 129, 0.2);
text-align: left;
transition: all 150ms ease;
cursor: pointer;
flex-shrink: 0;
}
.memberItem:hover {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.2), rgba(5, 150, 105, 0.2));
border-color: rgba(16, 185, 129, 0.4);
transform: translateX(4px);
}
.memberItem--active {
background: linear-gradient(135deg, rgba(16, 185, 129, 0.25), rgba(5, 150, 105, 0.25));
border-color: rgba(16, 185, 129, 0.6);
box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
}
.memberItem__header {
display: flex;
gap: 0.75rem;
align-items: center;
}
.memberItem__avatar {
width: 40px;
height: 40px;
border-radius: 50%;
object-fit: cover;
border: 2px solid rgba(16, 185, 129, 0.4);
}
.memberItem__info {
flex: 1;
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.memberItem__author {
font-weight: 700;
font-size: 0.95rem;
color: #10b981;
}
.memberItem__level {
font-size: 0.85rem;
color: #6ee7b7;
font-weight: 600;
}
.memberItem__time {
font-size: 0.7rem;
color: #64748b;
}
.memberItem__text {
margin: 0;
line-height: 1.4;
color: #d1fae5;
font-size: 0.9rem;
}
.selectedPreview { .selectedPreview {
width: 100%; width: 100%;
background: rgba(59, 130, 246, 0.1); background: rgba(59, 130, 246, 0.1);
@@ -523,7 +654,7 @@ main {
min-height: 100vh; min-height: 100vh;
display: grid; display: grid;
place-items: center; place-items: center;
background: rgba(0, 0, 0, 0); background: transparent;
} }
@keyframes fadeIn { @keyframes fadeIn {
@@ -551,15 +682,14 @@ main {
.overlay__card { .overlay__card {
padding: 2rem 2.5rem; padding: 2rem 2.5rem;
border-radius: 24px; border-radius: 24px;
background: linear-gradient(135deg, rgba(15, 23, 42, 0.95), rgba(30, 41, 59, 0.95)); background: linear-gradient(135deg, #0f172a, #1e293b);
border: 2px solid rgba(96, 165, 250, 0.3); border: 2px solid rgba(96, 165, 250, 0.3);
color: #f8fafc; box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
max-width: 1000px;
width: min(90vw, 1000px);
box-shadow: 0 20px 80px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.1);
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 1.25rem; gap: 1.5rem;
min-width: min(600px, 90vw);
max-width: min(900px, 95vw);
animation: fadeIn 0.4s ease-out; animation: fadeIn 0.4s ease-out;
} }
+12 -1
View File
@@ -1,6 +1,6 @@
'use client'; 'use client';
import { useEffect, useState } from 'react'; import { useEffect, useState, useRef } from 'react';
import type { ChatMessage } from '@shared/chat'; import type { ChatMessage } from '@shared/chat';
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100'; const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100';
@@ -13,9 +13,18 @@ export default function OverlayPage() {
const [message, setMessage] = useState<ChatMessage | null>(null); const [message, setMessage] = useState<ChatMessage | null>(null);
const [connected, setConnected] = useState(false); const [connected, setConnected] = useState(false);
const [fadingOut, setFadingOut] = useState(false); const [fadingOut, setFadingOut] = useState(false);
const connectionRef = useRef<EventSource | null>(null);
useEffect(() => { useEffect(() => {
// Prevent multiple connections
if (connectionRef.current) {
console.log('[Overlay] SSE already connected');
return;
}
console.log('[Overlay] Creating SSE connection');
const source = new EventSource(`${BACKEND_URL}/overlay/stream`); const source = new EventSource(`${BACKEND_URL}/overlay/stream`);
connectionRef.current = source;
const onSelection = (event: MessageEvent) => { const onSelection = (event: MessageEvent) => {
try { try {
@@ -47,8 +56,10 @@ export default function OverlayPage() {
source.onerror = () => setConnected(false); source.onerror = () => setConnected(false);
return () => { return () => {
console.log('[Overlay] Closing SSE connection');
source.removeEventListener('selection', onSelection as EventListener); source.removeEventListener('selection', onSelection as EventListener);
source.close(); source.close();
connectionRef.current = null;
}; };
}, []); // Empty dependency array - only connect once }, []); // Empty dependency array - only connect once
+1
View File
@@ -22,4 +22,5 @@ export type ChatMessage = {
isVerified?: boolean; isVerified?: boolean;
superChat?: SuperChatInfo; superChat?: SuperChatInfo;
membershipGift?: boolean; membershipGift?: boolean;
membershipLevel?: string; // e.g., "New member", "Member (6 months)", etc.
}; };