mirror of
https://github.com/yusufipk/YTChatHub.git
synced 2026-09-11 10:56:17 +00:00
Rewrite dashboard and overlay, single /events stream, static client served by the backend
Backend: one SSE stream for messages, selection, poll and connection status; reconnect with backoff; no on-disk Innertube session cache; mock only with MOCK_CHAT=1; binds to 127.0.0.1; serves client/out so production runs on one port. Full URLs for links YouTube truncates in chat. Client: components split out, Lucide icons, stream title and status, on-air strip, search, pause, keyboard shortcuts, overlay settings dialog. Overlay themes, position, size, animation and auto-hide via URL, sized for 1080p and scaled with the source. New blueprint theme for the brand background. Removed Tailwind, better-sqlite3, zod, the timezone helpers, Cline memory bank and AGENTS.md. Added ESLint, node:test tests and CI.
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
root: true
|
||||
extends: next/core-web-vitals
|
||||
rules:
|
||||
# Images come from the local proxy and the client is a static export; next/image adds nothing here.
|
||||
"@next/next/no-img-element": off
|
||||
+163
-709
@@ -1,761 +1,215 @@
|
||||
'use client';
|
||||
|
||||
import { useCallback, useEffect, useMemo, useState, useRef } from 'react';
|
||||
import type { ChatMessage, Poll } from '@shared/chat';
|
||||
import { useTimezone } from '../../lib/TimezoneContext';
|
||||
import { formatTimestamp } from '../../lib/timezone';
|
||||
import { proxyImageUrl } from '../../lib/imageProxy';
|
||||
import { Gift, MessageSquare, Sparkles } from 'lucide-react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
import { api } from '../../lib/api';
|
||||
import { useEvents } from '../../lib/useEvents';
|
||||
import { ChatList } from '../../components/ChatList';
|
||||
import { ConnectForm } from '../../components/ConnectForm';
|
||||
import { MessageCard } from '../../components/MessageCard';
|
||||
import { OnAir } from '../../components/OnAir';
|
||||
import { OverlaySettings } from '../../components/OverlaySettings';
|
||||
import { TopBar } from '../../components/TopBar';
|
||||
|
||||
// URL regex for detecting links (http/https)
|
||||
const URL_REGEX = /(https?:\/\/[^\s]+)/gi;
|
||||
type Toast = { id: number; text: string };
|
||||
|
||||
function parseTextWithLinks(text: string): Array<{ type: 'text' | 'link'; content: string }> {
|
||||
const parts: Array<{ type: 'text' | 'link'; content: string }> = [];
|
||||
let lastIndex = 0;
|
||||
const matches = text.matchAll(URL_REGEX);
|
||||
|
||||
for (const match of matches) {
|
||||
const url = match[0];
|
||||
const index = match.index!;
|
||||
|
||||
// Add text before the URL
|
||||
if (index > lastIndex) {
|
||||
parts.push({ type: 'text', content: text.slice(lastIndex, index) });
|
||||
}
|
||||
|
||||
// Add the URL
|
||||
parts.push({ type: 'link', content: url });
|
||||
lastIndex = index + url.length;
|
||||
}
|
||||
|
||||
// Add remaining text
|
||||
if (lastIndex < text.length) {
|
||||
parts.push({ type: 'text', content: text.slice(lastIndex) });
|
||||
}
|
||||
|
||||
return parts.length > 0 ? parts : [{ type: 'text', content: text }];
|
||||
function matches(message: ChatMessage, needle: string): boolean {
|
||||
if (!needle) return true;
|
||||
return message.author.toLowerCase().includes(needle) || message.text.toLowerCase().includes(needle);
|
||||
}
|
||||
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100';
|
||||
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() {
|
||||
const { messages, refresh, error: pollError } = useChatMessages();
|
||||
const { selection, status: overlayStatus } = useOverlaySelection();
|
||||
const { poll: currentPoll } = usePoll();
|
||||
const { connected, liveId, connect, disconnect, connecting } = useConnection();
|
||||
const [confirmUrl, setConfirmUrl] = useState<string | null>(null);
|
||||
const [superChatPulse, setSuperChatPulse] = useState(false);
|
||||
const [memberPulse, setMemberPulse] = useState(false);
|
||||
const [previouslySelected, setPreviouslySelected] = useState<Set<string>>(new Set());
|
||||
const prevSuperChatCountRef = useRef(0);
|
||||
const prevMemberCountRef = useRef(0);
|
||||
const hasInitializedRef = useRef(false);
|
||||
const { stream, status, messages, selection, poll } = useEvents();
|
||||
const [search, setSearch] = useState('');
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [settingsOpen, setSettingsOpen] = useState(false);
|
||||
const [linkToOpen, setLinkToOpen] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [connectError, setConnectError] = useState<string | null>(null);
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
const shownBefore = useRef(new Set<string>());
|
||||
const searchRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
const toast = useCallback((text: string) => {
|
||||
const id = Date.now() + Math.random();
|
||||
setToasts((list) => [...list, { id, text }]);
|
||||
setTimeout(() => setToasts((list) => list.filter((item) => item.id !== id)), 4000);
|
||||
}, []);
|
||||
|
||||
const select = useCallback(
|
||||
async (message: ChatMessage) => {
|
||||
try {
|
||||
// If clicking the already-selected message, clear it
|
||||
if (selection?.id === message.id) {
|
||||
await fetch(`${BACKEND_URL}/overlay/selection`, { method: 'DELETE' });
|
||||
await api.clearSelection();
|
||||
} else {
|
||||
// Otherwise, select the new message
|
||||
await fetch(`${BACKEND_URL}/overlay/selection`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id: message.id })
|
||||
});
|
||||
|
||||
// Mark this message as previously selected
|
||||
setPreviouslySelected(prev => new Set([...prev, message.id]));
|
||||
shownBefore.current.add(message.id);
|
||||
await api.select(message.id);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to select message', error);
|
||||
toast(`Could not update overlay: ${(error as Error).message}`);
|
||||
}
|
||||
},
|
||||
[selection]
|
||||
[selection, toast]
|
||||
);
|
||||
|
||||
const handleClear = useCallback(async () => {
|
||||
const clearSelection = useCallback(async () => {
|
||||
try {
|
||||
await fetch(`${BACKEND_URL}/overlay/selection`, { method: 'DELETE' });
|
||||
await api.clearSelection();
|
||||
} catch (error) {
|
||||
console.error('Failed to clear selection', error);
|
||||
toast(`Could not clear overlay: ${(error as Error).message}`);
|
||||
}
|
||||
}, [toast]);
|
||||
|
||||
const connect = useCallback(async (liveId: string) => {
|
||||
setBusy(true);
|
||||
setConnectError(null);
|
||||
try {
|
||||
await api.connect(liveId);
|
||||
shownBefore.current.clear();
|
||||
} catch (error) {
|
||||
setConnectError((error as Error).message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
refresh();
|
||||
}, POLL_INTERVAL);
|
||||
|
||||
return () => clearInterval(timer);
|
||||
}, [refresh]);
|
||||
|
||||
const statusHint = useMemo(() => {
|
||||
if (pollError) return 'Backend unreachable';
|
||||
if (overlayStatus === 'connecting') return 'Connecting to overlay…';
|
||||
if (overlayStatus === 'error') return 'Overlay stream disconnected';
|
||||
return 'Live';
|
||||
}, [pollError, overlayStatus]);
|
||||
|
||||
const handleLinkClick = useCallback((url: string) => {
|
||||
setConfirmUrl(url);
|
||||
}, []);
|
||||
|
||||
const handleConfirmOpen = useCallback(() => {
|
||||
if (confirmUrl) {
|
||||
window.open(confirmUrl, '_blank', 'noopener,noreferrer');
|
||||
setConfirmUrl(null);
|
||||
const disconnect = useCallback(async () => {
|
||||
try {
|
||||
await api.disconnect();
|
||||
} catch (error) {
|
||||
toast(`Could not disconnect: ${(error as Error).message}`);
|
||||
}
|
||||
}, [confirmUrl]);
|
||||
}, [toast]);
|
||||
|
||||
const handleCancelOpen = useCallback(() => {
|
||||
setConfirmUrl(null);
|
||||
}, []);
|
||||
|
||||
const superChats = useMemo(() => messages.filter(m => m.superChat), [messages]);
|
||||
const newMembers = useMemo(() => messages.filter(m => m.membershipGift || m.membershipGiftPurchase), [messages]);
|
||||
const regularMessages = useMemo(() => messages.filter(m => !m.superChat && !m.membershipGift && !m.membershipGiftPurchase), [messages]);
|
||||
|
||||
// Initialize counts on first load without triggering pulse
|
||||
useEffect(() => {
|
||||
if (!hasInitializedRef.current && messages.length > 0) {
|
||||
prevSuperChatCountRef.current = superChats.length;
|
||||
prevMemberCountRef.current = newMembers.length;
|
||||
hasInitializedRef.current = true;
|
||||
}
|
||||
}, [messages.length, superChats.length, newMembers.length]);
|
||||
const onKey = (event: KeyboardEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
const typing = target && (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.tagName === 'SELECT');
|
||||
if (typing) {
|
||||
if (event.key === 'Escape') (target as HTMLElement).blur();
|
||||
return;
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
if (linkToOpen) setLinkToOpen(null);
|
||||
else if (settingsOpen) setSettingsOpen(false);
|
||||
else if (selection) void clearSelection();
|
||||
} else if (event.key === '/') {
|
||||
event.preventDefault();
|
||||
searchRef.current?.focus();
|
||||
} else if (event.key.toLowerCase() === 'p') {
|
||||
setPaused((value) => !value);
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [selection, linkToOpen, settingsOpen, clearSelection]);
|
||||
|
||||
// Detect new superchats and trigger pulse
|
||||
useEffect(() => {
|
||||
if (!hasInitializedRef.current) return;
|
||||
|
||||
const prevCount = prevSuperChatCountRef.current;
|
||||
const currentCount = superChats.length;
|
||||
|
||||
// Trigger pulse if count increased
|
||||
if (currentCount > prevCount) {
|
||||
setSuperChatPulse(true);
|
||||
const timer = setTimeout(() => setSuperChatPulse(false), 10000);
|
||||
prevSuperChatCountRef.current = currentCount;
|
||||
return () => clearTimeout(timer);
|
||||
const needle = search.trim().toLowerCase();
|
||||
const groups = useMemo(() => {
|
||||
const chat: ChatMessage[] = [];
|
||||
const supers: ChatMessage[] = [];
|
||||
const members: ChatMessage[] = [];
|
||||
for (const message of messages) {
|
||||
if (!matches(message, needle)) continue;
|
||||
if (message.superChat) supers.push(message);
|
||||
else if (message.membershipGift || message.membershipGiftPurchase) members.push(message);
|
||||
else chat.push(message);
|
||||
}
|
||||
|
||||
prevSuperChatCountRef.current = currentCount;
|
||||
}, [superChats.length]);
|
||||
return { chat, supers, members };
|
||||
}, [messages, needle]);
|
||||
|
||||
// Detect new members and trigger pulse
|
||||
useEffect(() => {
|
||||
if (!hasInitializedRef.current) return;
|
||||
|
||||
const prevCount = prevMemberCountRef.current;
|
||||
const currentCount = newMembers.length;
|
||||
|
||||
// Trigger pulse if count increased
|
||||
if (currentCount > prevCount) {
|
||||
setMemberPulse(true);
|
||||
const timer = setTimeout(() => setMemberPulse(false), 10000);
|
||||
prevMemberCountRef.current = currentCount;
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
|
||||
prevMemberCountRef.current = currentCount;
|
||||
}, [newMembers.length]);
|
||||
const renderCard = (message: ChatMessage) => (
|
||||
<MessageCard
|
||||
key={message.id}
|
||||
message={message}
|
||||
selected={selection?.id === message.id}
|
||||
wasSelected={selection?.id !== message.id && shownBefore.current.has(message.id)}
|
||||
onSelect={select}
|
||||
onLink={setLinkToOpen}
|
||||
/>
|
||||
);
|
||||
|
||||
// Mock mode feeds messages while disconnected; keep the dashboard up in that case.
|
||||
const showConnect = (status.state === 'disconnected' || status.state === 'connecting') && messages.length === 0;
|
||||
|
||||
return (
|
||||
<main className="dashboard">
|
||||
{!connected && (
|
||||
<div className="connectionPrompt">
|
||||
<div className="connectionPrompt__content">
|
||||
<h2>Connect to YouTube Live Stream</h2>
|
||||
<form className="connectionPrompt__form" onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
const formData = new FormData(e.currentTarget);
|
||||
const liveId = formData.get('liveId') as string;
|
||||
if (liveId.trim()) {
|
||||
connect(liveId.trim());
|
||||
}
|
||||
}}>
|
||||
<input
|
||||
name="liveId"
|
||||
type="text"
|
||||
placeholder="Enter YouTube Live Stream ID or URL"
|
||||
disabled={connecting}
|
||||
autoFocus
|
||||
/>
|
||||
<button type="submit" disabled={connecting}>
|
||||
{connecting ? 'Connecting...' : 'Connect'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{connected && (
|
||||
<main className="dash">
|
||||
{showConnect ? (
|
||||
<ConnectForm
|
||||
busy={busy || status.state === 'connecting'}
|
||||
error={connectError ?? (stream === 'error' ? 'Backend is not reachable. Is it running?' : status.error ?? null)}
|
||||
onConnect={connect}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
<header className="dashboard__tabs">
|
||||
{currentPoll && (
|
||||
<div className="poll-indicator" title="Active poll on YouTube">
|
||||
<span className="poll-indicator__icon">📊</span>
|
||||
<span className="poll-indicator__text">Active Poll</span>
|
||||
<TopBar
|
||||
status={status}
|
||||
stream={stream}
|
||||
poll={poll}
|
||||
counts={{ chat: groups.chat.length, super: groups.supers.length, members: groups.members.length }}
|
||||
search={search}
|
||||
searchRef={searchRef}
|
||||
onSearch={setSearch}
|
||||
paused={paused}
|
||||
onTogglePause={() => setPaused((value) => !value)}
|
||||
onOverlaySettings={() => setSettingsOpen(true)}
|
||||
onDisconnect={disconnect}
|
||||
/>
|
||||
<OnAir selection={selection} onClear={clearSelection} />
|
||||
<section className="grid">
|
||||
<div className="panel">
|
||||
<div className="panel__head">
|
||||
<MessageSquare size={13} />
|
||||
Chat
|
||||
{needle && <span className="panel__note">filtered</span>}
|
||||
</div>
|
||||
)}
|
||||
<div className="tab">
|
||||
Messages <span className="tab__count">{regularMessages.length}</span>
|
||||
<ChatList messages={groups.chat} paused={paused} render={renderCard} empty={needle ? 'No messages match.' : 'Waiting for messages…'} />
|
||||
</div>
|
||||
<div className={`tab ${superChatPulse ? 'tab--pulse' : ''}`}>
|
||||
Superchats <span className="tab__count">{superChats.length}</span>
|
||||
</div>
|
||||
<div className={`tab ${memberPulse ? 'tab--pulse' : ''}`}>
|
||||
Members <span className="tab__count">{newMembers.length}</span>
|
||||
</div>
|
||||
<button className="btn-reset" onClick={disconnect} title="Reset stream connection">
|
||||
🔄
|
||||
</button>
|
||||
</header>
|
||||
|
||||
<section className="dashboard__grid">
|
||||
<div className="panel panel--chat">
|
||||
<div className="panel__header">
|
||||
<h2>💬 CHAT MESSAGES</h2>
|
||||
<button
|
||||
className="btn-clear-inline"
|
||||
onClick={handleClear}
|
||||
disabled={!selection}
|
||||
>
|
||||
CLEAR
|
||||
</button>
|
||||
</div>
|
||||
<ChatListPanel
|
||||
messages={regularMessages}
|
||||
renderItem={(message) => (
|
||||
<ChatItem
|
||||
key={message.id}
|
||||
message={message}
|
||||
isSelected={selection?.id === message.id}
|
||||
onSelect={() => handleSelect(message)}
|
||||
onLinkClick={handleLinkClick}
|
||||
isPreviouslySelected={previouslySelected.has(message.id)}
|
||||
/>
|
||||
)}
|
||||
emptyState={
|
||||
<div className="chatList__empty">
|
||||
<p>⏳ Waiting for chat messages...</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="dashboard__grid-right">
|
||||
<div className="panel panel--super">
|
||||
<div className="panel__header">
|
||||
<h2>🔥 SUPER CHATS</h2>
|
||||
<div className="side">
|
||||
<div className="panel">
|
||||
<div className="panel__head">
|
||||
<Sparkles size={13} />
|
||||
Super Chats
|
||||
</div>
|
||||
<ChatListPanel
|
||||
messages={superChats}
|
||||
renderItem={(message) => (
|
||||
<ChatItem
|
||||
key={message.id}
|
||||
message={message}
|
||||
isSelected={selection?.id === message.id}
|
||||
onSelect={() => handleSelect(message)}
|
||||
onLinkClick={handleLinkClick}
|
||||
isPreviouslySelected={previouslySelected.has(message.id)}
|
||||
/>
|
||||
)}
|
||||
emptyState={
|
||||
<div className="chatList__empty">
|
||||
<p>No super chats yet</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<ChatList messages={groups.supers} render={renderCard} empty="No Super Chats yet." />
|
||||
</div>
|
||||
|
||||
<div className="panel panel--members">
|
||||
<div className="panel__header">
|
||||
<h2>⭐ MEMBERSHIPS & MILESTONES</h2>
|
||||
<div className="panel">
|
||||
<div className="panel__head">
|
||||
<Gift size={13} />
|
||||
Memberships
|
||||
</div>
|
||||
<ChatListPanel
|
||||
messages={newMembers}
|
||||
renderItem={(message) => (
|
||||
<MemberItem
|
||||
key={message.id}
|
||||
message={message}
|
||||
isSelected={selection?.id === message.id}
|
||||
onSelect={() => handleSelect(message)}
|
||||
onLinkClick={handleLinkClick}
|
||||
isPreviouslySelected={previouslySelected.has(message.id)}
|
||||
/>
|
||||
)}
|
||||
emptyState={
|
||||
<div className="chatList__empty">
|
||||
<p>No new members yet</p>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<ChatList messages={groups.members} render={renderCard} empty="No new members yet." />
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</>
|
||||
)}
|
||||
|
||||
{confirmUrl && (
|
||||
<div className="modal-overlay" onClick={handleCancelOpen}>
|
||||
<div className="modal" onClick={(e) => e.stopPropagation()}>
|
||||
<h3 className="modal__title">Open External Link?</h3>
|
||||
<p className="modal__url">{confirmUrl}</p>
|
||||
{settingsOpen && <OverlaySettings onClose={() => setSettingsOpen(false)} />}
|
||||
|
||||
{linkToOpen && (
|
||||
<div className="modal" onClick={() => setLinkToOpen(null)}>
|
||||
<div className="modal__card" onClick={(event) => event.stopPropagation()}>
|
||||
<h2>Open this link?</h2>
|
||||
<p className="modal__url">{linkToOpen}</p>
|
||||
<div className="modal__actions">
|
||||
<button className="modal__btn modal__btn--cancel" onClick={handleCancelOpen}>
|
||||
Cancel
|
||||
</button>
|
||||
<button className="modal__btn modal__btn--confirm" onClick={handleConfirmOpen}>
|
||||
Open Link
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={() => setLinkToOpen(null)}>Cancel</button>
|
||||
<a className="btn btn--primary" href={linkToOpen} target="_blank" rel="noopener noreferrer" onClick={() => setLinkToOpen(null)}>
|
||||
Open in new tab
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{toasts.length > 0 && (
|
||||
<div className="toasts">
|
||||
{toasts.map((item) => (
|
||||
<div key={item.id} className="toast">{item.text}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function useChatMessages() {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${BACKEND_URL}/chat/messages`);
|
||||
if (!response.ok) throw new Error(`Request failed: ${response.status}`);
|
||||
const data = await response.json();
|
||||
setMessages(Array.isArray(data.messages) ? data.messages : []);
|
||||
setError(null);
|
||||
} catch (err) {
|
||||
setError(err as Error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
refresh();
|
||||
}, [refresh]);
|
||||
|
||||
return { messages, refresh, error };
|
||||
}
|
||||
|
||||
type OverlayStatus = 'connecting' | 'live' | 'error';
|
||||
|
||||
type SelectionPayload = {
|
||||
message: ChatMessage | null;
|
||||
};
|
||||
|
||||
function useOverlaySelection() {
|
||||
const [selection, setSelection] = useState<ChatMessage | null>(null);
|
||||
const [status, setStatus] = useState<OverlayStatus>('connecting');
|
||||
const listenerRef = useRef<((payload: any) => void) | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Create global connection if it doesn't exist
|
||||
if (!globalSSEConnection) {
|
||||
console.log('[Dashboard] Creating GLOBAL SSE connection');
|
||||
globalSSEConnection = new EventSource(`${BACKEND_URL}/overlay/stream`);
|
||||
|
||||
globalSSEConnection.addEventListener('selection', ((event: MessageEvent) => {
|
||||
try {
|
||||
const payload: SelectionPayload = JSON.parse(event.data);
|
||||
// Broadcast to all listeners
|
||||
globalConnectionListeners.forEach(listener => listener(payload));
|
||||
} catch (error) {
|
||||
console.error('Failed to parse selection payload', error);
|
||||
}
|
||||
}) as EventListener);
|
||||
|
||||
globalSSEConnection.addEventListener('heartbeat', () => {
|
||||
// Heartbeat - connection is alive
|
||||
});
|
||||
|
||||
globalSSEConnection.onerror = (error) => {
|
||||
console.error('[Dashboard] SSE connection error - will auto-reconnect', error);
|
||||
// EventSource automatically reconnects, no action needed
|
||||
};
|
||||
}
|
||||
|
||||
// Register this component's listener
|
||||
const myListener = (payload: SelectionPayload) => {
|
||||
setSelection(payload.message);
|
||||
setStatus('live');
|
||||
};
|
||||
|
||||
listenerRef.current = myListener;
|
||||
globalConnectionListeners.add(myListener);
|
||||
|
||||
return () => {
|
||||
// Unregister this component's listener
|
||||
if (listenerRef.current) {
|
||||
globalConnectionListeners.delete(listenerRef.current);
|
||||
}
|
||||
// Don't close global connection - other components might use it
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { selection, status };
|
||||
}
|
||||
|
||||
function useConnection() {
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [liveId, setLiveId] = useState<string | null>(null);
|
||||
const [connecting, setConnecting] = useState(false);
|
||||
|
||||
const checkStatus = useCallback(async () => {
|
||||
try {
|
||||
const response = await fetch(`${BACKEND_URL}/health`);
|
||||
const data = await response.json();
|
||||
setConnected(data.connected);
|
||||
setLiveId(data.liveId);
|
||||
} catch (error) {
|
||||
console.error('Failed to check connection status', error);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
checkStatus();
|
||||
const interval = setInterval(checkStatus, 5000);
|
||||
return () => clearInterval(interval);
|
||||
}, [checkStatus]);
|
||||
|
||||
const connect = useCallback(async (liveId: string) => {
|
||||
setConnecting(true);
|
||||
try {
|
||||
const response = await fetch(`${BACKEND_URL}/chat/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ liveId })
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.error || 'Failed to connect');
|
||||
}
|
||||
|
||||
await checkStatus();
|
||||
} catch (error) {
|
||||
console.error('Failed to connect', error);
|
||||
alert('Failed to connect to YouTube Live chat. Please check the Live ID.');
|
||||
} finally {
|
||||
setConnecting(false);
|
||||
}
|
||||
}, [checkStatus]);
|
||||
|
||||
const disconnect = useCallback(async () => {
|
||||
try {
|
||||
await fetch(`${BACKEND_URL}/chat/disconnect`, { method: 'POST' });
|
||||
await checkStatus();
|
||||
} catch (error) {
|
||||
console.error('Failed to disconnect', error);
|
||||
}
|
||||
}, [checkStatus]);
|
||||
|
||||
return { connected, liveId, connect, disconnect, connecting };
|
||||
}
|
||||
|
||||
function usePoll() {
|
||||
const [poll, setPoll] = useState<Poll | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
// Create SSE connection for polls
|
||||
const eventSource = new EventSource(`${BACKEND_URL}/poll/stream`);
|
||||
|
||||
eventSource.addEventListener('poll', ((event: MessageEvent) => {
|
||||
try {
|
||||
const payload = JSON.parse(event.data);
|
||||
setPoll(payload.poll);
|
||||
} catch (error) {
|
||||
console.error('Failed to parse poll payload', error);
|
||||
}
|
||||
}) as EventListener);
|
||||
|
||||
eventSource.addEventListener('heartbeat', () => {
|
||||
// Heartbeat - connection is alive
|
||||
});
|
||||
|
||||
eventSource.onerror = (error) => {
|
||||
console.error('[Dashboard] Poll SSE connection error', error);
|
||||
};
|
||||
|
||||
return () => {
|
||||
eventSource.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { poll };
|
||||
}
|
||||
|
||||
type ConnectionControlProps = {
|
||||
connected: boolean;
|
||||
liveId: string | null;
|
||||
connecting: boolean;
|
||||
onConnect: (liveId: string) => void;
|
||||
onDisconnect: () => void;
|
||||
inline?: boolean;
|
||||
};
|
||||
|
||||
function ConnectionControl({ connected, liveId, connecting, onConnect, onDisconnect, inline }: ConnectionControlProps) {
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (inputValue.trim()) {
|
||||
onConnect(inputValue.trim());
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={"connectionControl" + (inline ? " connectionControl--inline" : "") }>
|
||||
<div className="connectionControl__content">
|
||||
{connected ? (
|
||||
<div className="connectionControl__connected">
|
||||
<div className="connectionControl__info">
|
||||
<span className="connectionControl__badge">🟢 Connected</span>
|
||||
<span className="connectionControl__liveId">Live ID: {liveId}</span>
|
||||
</div>
|
||||
<button className="btn-disconnect" onClick={onDisconnect}>
|
||||
Disconnect
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<form className="connectionControl__form" onSubmit={handleSubmit}>
|
||||
<div className="connectionControl__input">
|
||||
<label htmlFor="liveId">YouTube Live Stream ID or URL</label>
|
||||
<input
|
||||
id="liveId"
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
placeholder="e.g., dQw4w9WgXcQ or https://youtube.com/watch?v=..."
|
||||
disabled={connecting}
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="btn-connect"
|
||||
disabled={connecting || !inputValue.trim()}
|
||||
>
|
||||
{connecting ? 'Connecting...' : 'Connect to Stream'}
|
||||
</button>
|
||||
</form>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type ChatItemProps = {
|
||||
message: ChatMessage;
|
||||
isSelected: boolean;
|
||||
onSelect: () => void;
|
||||
onLinkClick: (url: string) => void;
|
||||
isPreviouslySelected?: boolean;
|
||||
};
|
||||
|
||||
function MessageText({ text, onLinkClick }: { text: string; onLinkClick: (url: string) => void }) {
|
||||
const parts = parseTextWithLinks(text);
|
||||
return (
|
||||
<>
|
||||
{parts.map((part, i) =>
|
||||
part.type === 'link' ? (
|
||||
<a
|
||||
key={i}
|
||||
href="#"
|
||||
className="message-link"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
onLinkClick(part.content);
|
||||
}}
|
||||
>
|
||||
{part.content}
|
||||
</a>
|
||||
) : (
|
||||
<span key={i}>{part.content}</span>
|
||||
)
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type ChatListPanelProps = {
|
||||
messages: ChatMessage[];
|
||||
renderItem: (message: ChatMessage) => React.ReactNode;
|
||||
emptyState: React.ReactNode;
|
||||
};
|
||||
|
||||
function ChatListPanel({ messages, renderItem, emptyState }: ChatListPanelProps) {
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const wasAtBottomRef = useRef(true);
|
||||
|
||||
useEffect(() => {
|
||||
const node = scrollRef.current;
|
||||
if (!node) return;
|
||||
|
||||
const handleScroll = () => {
|
||||
const isAtBottom = node.scrollHeight - node.scrollTop - node.clientHeight <= 150;
|
||||
wasAtBottomRef.current = isAtBottom;
|
||||
};
|
||||
|
||||
node.addEventListener('scroll', handleScroll);
|
||||
return () => node.removeEventListener('scroll', handleScroll);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const node = scrollRef.current;
|
||||
if (node && wasAtBottomRef.current) {
|
||||
// Use setTimeout with requestAnimationFrame for more reliable scrolling
|
||||
setTimeout(() => {
|
||||
requestAnimationFrame(() => {
|
||||
if (node && wasAtBottomRef.current) {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
}
|
||||
});
|
||||
}, 0);
|
||||
}
|
||||
}, [messages]);
|
||||
|
||||
return (
|
||||
<div className="chatList" ref={scrollRef}>
|
||||
{messages.length > 0 ? messages.map(renderItem) : emptyState}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ChatItem({ message, isSelected, onSelect, onLinkClick, isPreviouslySelected }: ChatItemProps) {
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
const className = [
|
||||
'chatItem',
|
||||
isSelected ? 'chatItem--active' : '',
|
||||
isPreviouslySelected ? 'chatItem--previously-selected' : ''
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
className={className}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<div className="chatItem__header">
|
||||
{message.authorPhoto && (
|
||||
<img src={proxyImageUrl(message.authorPhoto)} alt={message.author} className="chatItem__avatar" />
|
||||
)}
|
||||
<div className="chatItem__meta">
|
||||
<div className="chatItem__authorLine">
|
||||
{message.membershipLevel && (
|
||||
<span className="chatItem__membership">{message.membershipLevel}:</span>
|
||||
)}
|
||||
<span className="chatItem__author">{message.author}</span>
|
||||
{message.leaderboardRank && (
|
||||
<span className="badge badge--leaderboard" title={`#${message.leaderboardRank} on leaderboard`}>
|
||||
👑 #{message.leaderboardRank}
|
||||
</span>
|
||||
)}
|
||||
{message.badges && message.badges.map((badge, i) => (
|
||||
badge.imageUrl ? (
|
||||
<img key={i} src={proxyImageUrl(badge.imageUrl)} alt={badge.label} className="badge badge--image" title={badge.label} />
|
||||
) : (
|
||||
<span key={i} className={`badge badge--${badge.type}`} title={badge.label}>
|
||||
{badge.type === 'moderator' && '🛡️'}
|
||||
{badge.type === 'member' && '⭐'}
|
||||
{badge.type === 'verified' && '✓'}
|
||||
</span>
|
||||
)
|
||||
))}
|
||||
{message.superChat && (
|
||||
<span className="chatItem__superchat-inline" style={{ backgroundColor: message.superChat.color }}>
|
||||
{message.superChat.currency}{message.superChat.currency ? ' ' : ''}{message.superChat.amount}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<time className="chatItem__time">{formatTimestamp(message.publishedAt, timezone)}</time>
|
||||
</div>
|
||||
</div>
|
||||
{message.runs?.length ? (
|
||||
<p className="chatItem__text">
|
||||
{message.runs.map((r, i) =>
|
||||
r.emojiUrl ? (
|
||||
<img key={i} src={proxyImageUrl(r.emojiUrl)} alt={r.emojiAlt || 'emoji'} className="chatItem__emoji" />
|
||||
) : (
|
||||
<span key={i}><MessageText text={r.text || ''} onLinkClick={onLinkClick} /></span>
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
) : message.text && message.text !== 'N/A' && (
|
||||
<p className="chatItem__text">
|
||||
<MessageText text={message.text} onLinkClick={onLinkClick} />
|
||||
</p>
|
||||
)}
|
||||
{message.superChat?.stickerUrl && (
|
||||
<div className="chatItem__sticker">
|
||||
<img
|
||||
src={proxyImageUrl(message.superChat.stickerUrl)}
|
||||
alt={message.superChat.stickerAlt || 'Super Sticker'}
|
||||
className="chatItem__stickerImage"
|
||||
onError={(e) => {
|
||||
// Hide image on error
|
||||
e.currentTarget.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function MemberItem({ message, isSelected, onSelect, onLinkClick, isPreviouslySelected }: ChatItemProps) {
|
||||
const { timezone } = useTimezone();
|
||||
|
||||
const className = [
|
||||
'memberItem',
|
||||
isSelected ? 'memberItem--active' : '',
|
||||
isPreviouslySelected ? 'memberItem--previously-selected' : ''
|
||||
].filter(Boolean).join(' ');
|
||||
|
||||
return (
|
||||
<button
|
||||
className={className}
|
||||
onClick={onSelect}
|
||||
>
|
||||
<div className="memberItem__header">
|
||||
{message.authorPhoto && (
|
||||
<img src={proxyImageUrl(message.authorPhoto)} alt={message.author} className="memberItem__avatar" />
|
||||
)}
|
||||
<div className="memberItem__info">
|
||||
<span className="memberItem__author">{message.author}</span>
|
||||
<span className="memberItem__level">
|
||||
{message.membershipGiftPurchase && message.giftCount
|
||||
? `Sent ${message.giftCount} gift membership${message.giftCount > 1 ? 's' : ''}`
|
||||
: message.membershipLevel || 'New member'}
|
||||
</span>
|
||||
<time className="memberItem__time">{formatTimestamp(message.publishedAt, timezone)}</time>
|
||||
</div>
|
||||
</div>
|
||||
{message.runs?.length ? (
|
||||
<p className="memberItem__text">
|
||||
{message.runs.map((r, i) =>
|
||||
r.emojiUrl ? (
|
||||
<img key={i} src={proxyImageUrl(r.emojiUrl)} alt={r.emojiAlt || 'emoji'} className="memberItem__emoji" />
|
||||
) : (
|
||||
<span key={i}><MessageText text={r.text || ''} onLinkClick={onLinkClick} /></span>
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
) : message.text && message.text !== 'N/A' && (
|
||||
<p className="memberItem__text">
|
||||
<MessageText text={message.text} onLinkClick={onLinkClick} />
|
||||
</p>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
+977
-1242
File diff suppressed because it is too large
Load Diff
@@ -1,20 +1,15 @@
|
||||
import './globals.css';
|
||||
import type { ReactNode } from 'react';
|
||||
import { TimezoneProvider } from '../lib/TimezoneContext';
|
||||
|
||||
export const metadata = {
|
||||
title: 'YouTube Chat Client',
|
||||
description: 'High-performance YouTube Live chat dashboard'
|
||||
title: 'YTChatHub',
|
||||
description: 'YouTube Live chat dashboard with an OBS overlay'
|
||||
};
|
||||
|
||||
export default function RootLayout({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body>
|
||||
<TimezoneProvider>
|
||||
{children}
|
||||
</TimezoneProvider>
|
||||
</body>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
+64
-189
@@ -1,211 +1,86 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useState, useRef } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
import { Badges } from '../../components/Badges';
|
||||
import { MessageBody } from '../../components/MessageBody';
|
||||
import { formatAmount } from '../../lib/format';
|
||||
import { proxyImageUrl } from '../../lib/imageProxy';
|
||||
import { DEFAULT_OPTIONS, parseOverlayOptions, type OverlayOptions } from '../../lib/overlayOptions';
|
||||
import { useEvents } from '../../lib/useEvents';
|
||||
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100';
|
||||
const SWAP_MS = 220;
|
||||
|
||||
type SelectionPayload = {
|
||||
message: ChatMessage | null;
|
||||
};
|
||||
function membershipLabel(message: ChatMessage): string {
|
||||
if (message.membershipGiftPurchase && message.giftCount) {
|
||||
return `Gifted ${message.giftCount} membership${message.giftCount > 1 ? 's' : ''}`;
|
||||
}
|
||||
return message.membershipLevel || 'New member';
|
||||
}
|
||||
|
||||
export default function OverlayPage() {
|
||||
const [message, setMessage] = useState<ChatMessage | null>(null);
|
||||
const [displayMessage, setDisplayMessage] = useState<ChatMessage | null>(null);
|
||||
const [connected, setConnected] = useState(false);
|
||||
const [fadingOut, setFadingOut] = useState(false);
|
||||
const [switching, setSwitching] = useState(false);
|
||||
const connectionRef = useRef<EventSource | null>(null);
|
||||
const switchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
|
||||
const { selection } = useEvents();
|
||||
const [options, setOptions] = useState<OverlayOptions>(DEFAULT_OPTIONS);
|
||||
const [shown, setShown] = useState<ChatMessage | null>(null);
|
||||
const [leaving, setLeaving] = useState(false);
|
||||
const [expired, setExpired] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
// Prevent multiple connections
|
||||
if (connectionRef.current) {
|
||||
console.log('[Overlay] SSE already connected');
|
||||
setOptions(parseOverlayOptions(window.location.search));
|
||||
document.body.classList.add('is-overlay');
|
||||
return () => document.body.classList.remove('is-overlay');
|
||||
}, []);
|
||||
|
||||
// Swap with a short exit animation so a new pick never pops in over the old one.
|
||||
useEffect(() => {
|
||||
if ((selection?.id ?? null) === (shown?.id ?? null)) return;
|
||||
if (!shown || options.anim === 'none') {
|
||||
setShown(selection);
|
||||
setExpired(false);
|
||||
return;
|
||||
}
|
||||
setLeaving(true);
|
||||
const timer = setTimeout(() => {
|
||||
setShown(selection);
|
||||
setExpired(false);
|
||||
setLeaving(false);
|
||||
}, SWAP_MS);
|
||||
return () => clearTimeout(timer);
|
||||
}, [selection, shown, options.anim]);
|
||||
|
||||
console.log('[Overlay] Creating SSE connection');
|
||||
const source = new EventSource(`${BACKEND_URL}/overlay/stream`);
|
||||
connectionRef.current = source;
|
||||
|
||||
const onSelection = (event: MessageEvent) => {
|
||||
try {
|
||||
const payload: SelectionPayload = JSON.parse(event.data);
|
||||
setMessage(payload.message);
|
||||
setConnected(true);
|
||||
} catch (error) {
|
||||
console.error('overlay: failed to parse payload', error);
|
||||
}
|
||||
};
|
||||
|
||||
source.addEventListener('selection', onSelection as EventListener);
|
||||
source.addEventListener('heartbeat', () => setConnected(true));
|
||||
source.onerror = () => setConnected(false);
|
||||
|
||||
return () => {
|
||||
console.log('[Overlay] Closing SSE connection');
|
||||
source.removeEventListener('selection', onSelection as EventListener);
|
||||
source.close();
|
||||
connectionRef.current = null;
|
||||
if (switchTimeoutRef.current) {
|
||||
clearTimeout(switchTimeoutRef.current);
|
||||
}
|
||||
};
|
||||
}, []); // Empty dependency array - only connect once
|
||||
|
||||
// Handle message transitions
|
||||
useEffect(() => {
|
||||
// Clear any pending timeout
|
||||
if (switchTimeoutRef.current) {
|
||||
clearTimeout(switchTimeoutRef.current);
|
||||
switchTimeoutRef.current = null;
|
||||
}
|
||||
if (!options.hide || !shown) return;
|
||||
const timer = setTimeout(() => setExpired(true), options.hide * 1000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [shown, options.hide]);
|
||||
|
||||
if (message === null && displayMessage !== null) {
|
||||
// Deselecting - fade out
|
||||
setFadingOut(true);
|
||||
setSwitching(false);
|
||||
switchTimeoutRef.current = setTimeout(() => {
|
||||
setDisplayMessage(null);
|
||||
setFadingOut(false);
|
||||
}, 300);
|
||||
} else if (message !== null && displayMessage !== null && message.id !== displayMessage.id) {
|
||||
// Switching between messages - fade out then fade in
|
||||
setSwitching(true);
|
||||
setFadingOut(true);
|
||||
switchTimeoutRef.current = setTimeout(() => {
|
||||
setDisplayMessage(message);
|
||||
setFadingOut(false);
|
||||
setSwitching(false);
|
||||
}, 300);
|
||||
} else if (message !== null && displayMessage === null) {
|
||||
// First message - just show it
|
||||
setDisplayMessage(message);
|
||||
setFadingOut(false);
|
||||
setSwitching(false);
|
||||
}
|
||||
}, [message, displayMessage]);
|
||||
const message = expired ? null : shown;
|
||||
const kind = message?.superChat ? 'super' : message?.membershipGift || message?.membershipGiftPurchase ? 'member' : 'chat';
|
||||
|
||||
return (
|
||||
<main className="overlay">
|
||||
{displayMessage ? (
|
||||
<div className={`overlay__card ${fadingOut ? 'overlay__card--fadeOut' : ''}`}>
|
||||
{displayMessage.superChat ? (
|
||||
<>
|
||||
<div className="overlay__superchat-header" style={{ backgroundColor: displayMessage.superChat.color }}>
|
||||
{displayMessage.authorPhoto && (
|
||||
<img src={proxyImageUrl(displayMessage.authorPhoto)} alt={displayMessage.author} className="overlay__superchat-avatar" />
|
||||
)}
|
||||
<span className="overlay__superchat-name">{displayMessage.author}</span>
|
||||
<span className="overlay__superchat-separator"> - </span>
|
||||
<span className="overlay__superchat-amount">
|
||||
{displayMessage.superChat.currency}{displayMessage.superChat.currency ? ' ' : ''}{displayMessage.superChat.amount}
|
||||
</span>
|
||||
</div>
|
||||
{displayMessage.runs?.length ? (
|
||||
<p className="overlay__superchat-text">
|
||||
{displayMessage.runs.map((r, i) =>
|
||||
r.emojiUrl ? (
|
||||
<img key={i} src={proxyImageUrl(r.emojiUrl)} alt={r.emojiAlt || 'emoji'} className="overlay__emoji" />
|
||||
) : (
|
||||
<span key={i}>{r.text}</span>
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
) : displayMessage.text && displayMessage.text !== 'N/A' && (
|
||||
<p className="overlay__superchat-text">{displayMessage.text}</p>
|
||||
)}
|
||||
{displayMessage.superChat.stickerUrl && (
|
||||
<div className="overlay__sticker">
|
||||
<img
|
||||
src={proxyImageUrl(displayMessage.superChat.stickerUrl)}
|
||||
alt={displayMessage.superChat.stickerAlt || 'Super Sticker'}
|
||||
className="overlay__stickerImage"
|
||||
onError={(e) => {
|
||||
// Hide image on error
|
||||
e.currentTarget.style.display = 'none';
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (displayMessage.membershipGift || displayMessage.membershipGiftPurchase) ? (
|
||||
<>
|
||||
<div className="overlay__membership-header">
|
||||
{displayMessage.authorPhoto && (
|
||||
<img src={proxyImageUrl(displayMessage.authorPhoto)} alt={displayMessage.author} className="overlay__membership-avatar" />
|
||||
)}
|
||||
<div className="overlay__membership-info">
|
||||
<span className="overlay__membership-name">{displayMessage.author}</span>
|
||||
<span className="overlay__membership-separator"> - </span>
|
||||
<span className="overlay__membership-level">
|
||||
{displayMessage.membershipGiftPurchase && displayMessage.giftCount
|
||||
? `Sent ${displayMessage.giftCount} Gift Membership${displayMessage.giftCount > 1 ? 's' : ''}`
|
||||
: displayMessage.membershipLevel || 'New Member'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
{displayMessage.runs?.length ? (
|
||||
<p className="overlay__membership-text">
|
||||
{displayMessage.runs.map((r, i) =>
|
||||
r.emojiUrl ? (
|
||||
<img key={i} src={proxyImageUrl(r.emojiUrl)} alt={r.emojiAlt || 'emoji'} className="overlay__emoji" />
|
||||
) : (
|
||||
<span key={i}>{r.text}</span>
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
) : displayMessage.text && displayMessage.text !== 'N/A' && (
|
||||
<p className="overlay__membership-text">{displayMessage.text}</p>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<div className="overlay__header">
|
||||
{displayMessage.authorPhoto && (
|
||||
<img src={proxyImageUrl(displayMessage.authorPhoto)} alt={displayMessage.author} className="overlay__avatar" />
|
||||
)}
|
||||
<div>
|
||||
<div className="overlay__authorLine">
|
||||
<span className="overlay__author">{displayMessage.author}</span>
|
||||
{displayMessage.leaderboardRank && (
|
||||
<span className="overlay__badge overlay__badge--leaderboard" title={`#${displayMessage.leaderboardRank} on leaderboard`}>
|
||||
👑 #{displayMessage.leaderboardRank}
|
||||
</span>
|
||||
)}
|
||||
{displayMessage.badges && displayMessage.badges.map((badge, i) => (
|
||||
badge.imageUrl ? (
|
||||
<img key={i} src={proxyImageUrl(badge.imageUrl)} alt={badge.label} className="overlay__badge overlay__badge--image" title={badge.label} />
|
||||
) : (
|
||||
<span key={i} className={`overlay__badge overlay__badge--${badge.type}`} title={badge.label}>
|
||||
{badge.type === 'moderator' && '🛡️'}
|
||||
{badge.type === 'member' && '⭐'}
|
||||
{badge.type === 'verified' && '✓'}
|
||||
</span>
|
||||
)
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{displayMessage.runs?.length ? (
|
||||
<p className="overlay__text">
|
||||
{displayMessage.runs.map((r, i) =>
|
||||
r.emojiUrl ? (
|
||||
<img key={i} src={proxyImageUrl(r.emojiUrl)} alt={r.emojiAlt || 'emoji'} className="overlay__emoji" />
|
||||
) : (
|
||||
<span key={i}>{r.text}</span>
|
||||
)
|
||||
)}
|
||||
</p>
|
||||
) : displayMessage.text && displayMessage.text !== 'N/A' && (
|
||||
<p className="overlay__text">{displayMessage.text}</p>
|
||||
)}
|
||||
</>
|
||||
<main className={`ov ov--${options.theme} ov--${options.pos} ov--size-${options.size} ov--anim-${options.anim}`} style={{ ['--w' as string]: String(options.width) }}>
|
||||
{message && (
|
||||
<div key={message.id} className={`ov__card ov__card--${kind} ${leaving ? 'ov__card--leaving' : ''}`} style={message.superChat ? { ['--accent' as string]: message.superChat.color } : undefined}>
|
||||
<div className="ov__head">
|
||||
{message.authorPhoto && <img src={proxyImageUrl(message.authorPhoto)} alt="" className="ov__avatar" />}
|
||||
<span className="ov__author">{message.author}</span>
|
||||
<Badges message={message} />
|
||||
{message.superChat && <span className="ov__amount">{formatAmount(message.superChat.amount, message.superChat.currency)}</span>}
|
||||
{kind === 'member' && <span className="ov__level">{membershipLabel(message)}</span>}
|
||||
</div>
|
||||
<MessageBody message={message} className="ov__text" />
|
||||
{message.superChat?.stickerUrl && (
|
||||
<img
|
||||
src={proxyImageUrl(message.superChat.stickerUrl)}
|
||||
alt={message.superChat.stickerAlt || 'Super Sticker'}
|
||||
className="ov__sticker"
|
||||
onError={(event) => {
|
||||
event.currentTarget.hidden = true;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
) : null}
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
+14
-9
@@ -1,17 +1,22 @@
|
||||
import Link from 'next/link';
|
||||
import { LayoutDashboard, MonitorPlay } from 'lucide-react';
|
||||
|
||||
export default function HomePage() {
|
||||
return (
|
||||
<main className="landing">
|
||||
<section className="panel">
|
||||
<h1>YouTube Chat Client</h1>
|
||||
<p>
|
||||
Launch the dashboard to monitor live chat and control the overlay that feeds OBS.
|
||||
</p>
|
||||
<Link className="primary" href="/dashboard">
|
||||
Open Dashboard
|
||||
</Link>
|
||||
<p className="muted">Overlay preview lives at /overlay for the OBS browser source.</p>
|
||||
<section className="landing__card">
|
||||
<h1>YTChatHub</h1>
|
||||
<p>Watch a YouTube Live chat, pick a message, and it appears on your OBS overlay.</p>
|
||||
<div className="landing__links">
|
||||
<Link className="btn btn--primary" href="/dashboard/">
|
||||
<LayoutDashboard size={15} />
|
||||
Open dashboard
|
||||
</Link>
|
||||
<Link className="btn" href="/overlay/">
|
||||
<MonitorPlay size={15} />
|
||||
Overlay for OBS
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { BadgeCheck, Crown, Shield, Star, Tv } from 'lucide-react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
import { proxyImageUrl } from '../lib/imageProxy';
|
||||
|
||||
const ICONS = {
|
||||
moderator: Shield,
|
||||
member: Star,
|
||||
verified: BadgeCheck,
|
||||
owner: Tv,
|
||||
custom: null
|
||||
} as const;
|
||||
|
||||
export function Badges({ message }: { message: ChatMessage }) {
|
||||
return (
|
||||
<>
|
||||
{message.leaderboardRank && (
|
||||
<span className="badge badge--rank" title={`#${message.leaderboardRank} on the chat leaderboard`}>
|
||||
<Crown size={11} strokeWidth={2.5} />
|
||||
{message.leaderboardRank}
|
||||
</span>
|
||||
)}
|
||||
{message.badges?.map((badge, i) => {
|
||||
if (badge.imageUrl) {
|
||||
return <img key={i} src={proxyImageUrl(badge.imageUrl)} alt={badge.label ?? badge.type} title={badge.label} className="badge badge--image" />;
|
||||
}
|
||||
const Icon = ICONS[badge.type];
|
||||
if (!Icon) return null;
|
||||
return (
|
||||
<span key={i} className={`badge badge--${badge.type}`} title={badge.label}>
|
||||
<Icon size={12} strokeWidth={2.5} />
|
||||
</span>
|
||||
);
|
||||
})}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
'use client';
|
||||
|
||||
import { ArrowDown } from 'lucide-react';
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
|
||||
type Props = {
|
||||
messages: ChatMessage[];
|
||||
paused?: boolean;
|
||||
render: (message: ChatMessage) => ReactNode;
|
||||
empty: string;
|
||||
};
|
||||
|
||||
const BOTTOM_THRESHOLD = 80;
|
||||
|
||||
/**
|
||||
* Scroll container that follows new messages while the user is at the bottom.
|
||||
* Scrolling up stops following and shows a jump button with the unseen count.
|
||||
* While paused the list is frozen at its current contents.
|
||||
*/
|
||||
export function ChatList({ messages, paused = false, render, empty }: Props) {
|
||||
const scroller = useRef<HTMLDivElement>(null);
|
||||
const following = useRef(true);
|
||||
const [unseen, setUnseen] = useState(0);
|
||||
const [frozen, setFrozen] = useState<ChatMessage[] | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
setFrozen(paused ? messages : null);
|
||||
// Only the pause flag should snapshot; message updates while paused must not refresh the snapshot.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [paused]);
|
||||
|
||||
const shown = frozen ?? messages;
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const node = scroller.current;
|
||||
if (!node) return;
|
||||
if (following.current) {
|
||||
node.scrollTop = node.scrollHeight;
|
||||
setUnseen(0);
|
||||
} else {
|
||||
setUnseen((count) => count + 1);
|
||||
}
|
||||
}, [shown]);
|
||||
|
||||
const onScroll = () => {
|
||||
const node = scroller.current;
|
||||
if (!node) return;
|
||||
const atBottom = node.scrollHeight - node.scrollTop - node.clientHeight <= BOTTOM_THRESHOLD;
|
||||
following.current = atBottom;
|
||||
if (atBottom) setUnseen(0);
|
||||
};
|
||||
|
||||
const jump = () => {
|
||||
const node = scroller.current;
|
||||
if (!node) return;
|
||||
following.current = true;
|
||||
node.scrollTop = node.scrollHeight;
|
||||
setUnseen(0);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="list">
|
||||
<div className="list__scroll" ref={scroller} onScroll={onScroll}>
|
||||
{shown.length ? shown.map(render) : <p className="list__empty">{empty}</p>}
|
||||
</div>
|
||||
{unseen > 0 && !following.current && (
|
||||
<button type="button" className="list__jump" onClick={jump}>
|
||||
<ArrowDown size={14} />
|
||||
{unseen} new
|
||||
</button>
|
||||
)}
|
||||
{paused && frozen && messages.length > frozen.length && (
|
||||
<span className="list__paused">Paused, {messages.length - frozen.length} waiting</span>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
'use client';
|
||||
|
||||
import { Radio } from 'lucide-react';
|
||||
import { useState, type FormEvent } from 'react';
|
||||
|
||||
type Props = {
|
||||
busy: boolean;
|
||||
error?: string | null;
|
||||
onConnect: (liveId: string) => void;
|
||||
};
|
||||
|
||||
export function ConnectForm({ busy, error, onConnect }: Props) {
|
||||
const [value, setValue] = useState('');
|
||||
|
||||
const submit = (event: FormEvent) => {
|
||||
event.preventDefault();
|
||||
if (value.trim()) onConnect(value.trim());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="connect">
|
||||
<form className="connect__card" onSubmit={submit}>
|
||||
<span className="connect__icon">
|
||||
<Radio size={22} />
|
||||
</span>
|
||||
<h1>Connect to a live stream</h1>
|
||||
<p>Paste the video URL or the 11 character video id of a stream that is live now.</p>
|
||||
<input
|
||||
autoFocus
|
||||
value={value}
|
||||
onChange={(event) => setValue(event.target.value)}
|
||||
placeholder="https://youtube.com/watch?v=…"
|
||||
disabled={busy}
|
||||
spellCheck={false}
|
||||
/>
|
||||
{error && <p className="connect__error">{error}</p>}
|
||||
<button type="submit" className="btn btn--primary" disabled={busy || !value.trim()}>
|
||||
{busy ? 'Connecting…' : 'Connect'}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
'use client';
|
||||
|
||||
import type { ChatMessage, MessageRun } from '@shared/chat';
|
||||
import { proxyImageUrl } from '../lib/imageProxy';
|
||||
import { splitLinks } from '../lib/format';
|
||||
|
||||
type Props = {
|
||||
message: ChatMessage;
|
||||
className?: string;
|
||||
/** When given, links are clickable and call this instead of navigating. When omitted links render as text. */
|
||||
onLink?: (url: string) => void;
|
||||
};
|
||||
|
||||
function runsOf(message: ChatMessage): MessageRun[] {
|
||||
if (message.runs?.length) return message.runs;
|
||||
if (message.text && message.text !== 'N/A') return [{ text: message.text }];
|
||||
return [];
|
||||
}
|
||||
|
||||
export function MessageBody({ message, className, onLink }: Props) {
|
||||
const runs = runsOf(message);
|
||||
if (!runs.length) return null;
|
||||
|
||||
const link = (url: string, label: string, key: number) =>
|
||||
onLink ? (
|
||||
<a
|
||||
key={key}
|
||||
href={url}
|
||||
className="link"
|
||||
title={url}
|
||||
onClick={(event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
onLink(url);
|
||||
}}
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
) : (
|
||||
<span key={key} className="link">{label}</span>
|
||||
);
|
||||
|
||||
return (
|
||||
<p className={className}>
|
||||
{runs.map((run, i) => {
|
||||
if (run.emojiUrl) {
|
||||
return <img key={i} src={proxyImageUrl(run.emojiUrl)} alt={run.emojiAlt || 'emoji'} className="emoji" loading="lazy" />;
|
||||
}
|
||||
if (run.url) return link(run.url, run.text || run.url, i);
|
||||
return splitLinks(run.text ?? '').map((part, j) =>
|
||||
part.type === 'link' ? link(part.content, part.content, i * 1000 + j) : <span key={i * 1000 + j}>{part.content}</span>
|
||||
);
|
||||
})}
|
||||
</p>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
'use client';
|
||||
|
||||
import { Gift } from 'lucide-react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
import { proxyImageUrl } from '../lib/imageProxy';
|
||||
import { formatAmount, formatTime } from '../lib/format';
|
||||
import { Badges } from './Badges';
|
||||
import { MessageBody } from './MessageBody';
|
||||
|
||||
type Props = {
|
||||
message: ChatMessage;
|
||||
selected: boolean;
|
||||
wasSelected: boolean;
|
||||
onSelect: (message: ChatMessage) => void;
|
||||
onLink: (url: string) => void;
|
||||
};
|
||||
|
||||
function membershipLabel(message: ChatMessage): string {
|
||||
if (message.membershipGiftPurchase && message.giftCount) {
|
||||
return `Gifted ${message.giftCount} membership${message.giftCount > 1 ? 's' : ''}`;
|
||||
}
|
||||
return message.membershipLevel || 'New member';
|
||||
}
|
||||
|
||||
export function MessageCard({ message, selected, wasSelected, onSelect, onLink }: Props) {
|
||||
const kind = message.superChat ? 'super' : message.membershipGift || message.membershipGiftPurchase ? 'member' : 'chat';
|
||||
const className = ['card', `card--${kind}`, selected && 'card--selected', wasSelected && 'card--seen'].filter(Boolean).join(' ');
|
||||
const accent = message.superChat?.color;
|
||||
|
||||
return (
|
||||
<button type="button" className={className} onClick={() => onSelect(message)} style={accent ? { ['--accent' as string]: accent } : undefined}>
|
||||
<div className="card__head">
|
||||
{message.authorPhoto ? (
|
||||
<img src={proxyImageUrl(message.authorPhoto)} alt="" className="avatar" loading="lazy" />
|
||||
) : (
|
||||
<span className="avatar avatar--empty">{message.author.slice(0, 1)}</span>
|
||||
)}
|
||||
<span className="card__author">{message.author}</span>
|
||||
<Badges message={message} />
|
||||
{message.superChat && <span className="card__amount">{formatAmount(message.superChat.amount, message.superChat.currency)}</span>}
|
||||
{kind === 'member' && (
|
||||
<span className="card__level">
|
||||
<Gift size={11} strokeWidth={2.5} />
|
||||
{membershipLabel(message)}
|
||||
</span>
|
||||
)}
|
||||
<time className="card__time">{formatTime(message.publishedAt)}</time>
|
||||
</div>
|
||||
<MessageBody message={message} className="card__text" onLink={onLink} />
|
||||
{message.superChat?.stickerUrl && (
|
||||
<img
|
||||
src={proxyImageUrl(message.superChat.stickerUrl)}
|
||||
alt={message.superChat.stickerAlt || 'Super Sticker'}
|
||||
className="sticker"
|
||||
onError={(event) => {
|
||||
event.currentTarget.hidden = true;
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
'use client';
|
||||
|
||||
import { X } from 'lucide-react';
|
||||
import type { ChatMessage } from '@shared/chat';
|
||||
import { proxyImageUrl } from '../lib/imageProxy';
|
||||
import { formatAmount } from '../lib/format';
|
||||
import { MessageBody } from './MessageBody';
|
||||
|
||||
type Props = { selection: ChatMessage | null; onClear: () => void };
|
||||
|
||||
/** Mirrors what the OBS overlay is showing right now, so the operator never has to guess. */
|
||||
export function OnAir({ selection, onClear }: Props) {
|
||||
return (
|
||||
<section className={`onair ${selection ? 'onair--live' : ''}`}>
|
||||
<span className="onair__label">On air</span>
|
||||
{selection ? (
|
||||
<>
|
||||
{selection.authorPhoto && <img src={proxyImageUrl(selection.authorPhoto)} alt="" className="avatar avatar--sm" />}
|
||||
<span className="onair__author">{selection.author}</span>
|
||||
{selection.superChat && (
|
||||
<span className="card__amount" style={{ background: selection.superChat.color }}>
|
||||
{formatAmount(selection.superChat.amount, selection.superChat.currency)}
|
||||
</span>
|
||||
)}
|
||||
<MessageBody message={selection} className="onair__text" />
|
||||
<button type="button" className="btn btn--sm" onClick={onClear} title="Clear the overlay (Esc)">
|
||||
<X size={13} />
|
||||
Clear
|
||||
</button>
|
||||
</>
|
||||
) : (
|
||||
<span className="onair__hint">Nothing on the overlay. Click a message to show it, click again to hide it.</span>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
'use client';
|
||||
|
||||
import { Check, Copy, ExternalLink, X } from 'lucide-react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { ANIMATIONS, buildOverlayUrl, DEFAULT_OPTIONS, POSITIONS, SIZES, THEMES, type OverlayOptions } from '../lib/overlayOptions';
|
||||
|
||||
const STORAGE_KEY = 'ytchathub.overlay';
|
||||
|
||||
const LABELS: Record<string, string> = {
|
||||
bl: 'Bottom left', bc: 'Bottom center', br: 'Bottom right',
|
||||
tl: 'Top left', tc: 'Top center', tr: 'Top right',
|
||||
s: 'Small', m: 'Medium', l: 'Large', xl: 'Extra large',
|
||||
dark: 'Dark', light: 'Light', blueprint: 'Blueprint (light, brand)', glass: 'Glass', youtube: 'YouTube red',
|
||||
fade: 'Fade', slide: 'Slide', none: 'None'
|
||||
};
|
||||
|
||||
function load(): OverlayOptions {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY);
|
||||
if (raw) return { ...DEFAULT_OPTIONS, ...JSON.parse(raw) };
|
||||
} catch {
|
||||
// storage unavailable or corrupt
|
||||
}
|
||||
return DEFAULT_OPTIONS;
|
||||
}
|
||||
|
||||
export function OverlaySettings({ onClose }: { onClose: () => void }) {
|
||||
const [options, setOptions] = useState<OverlayOptions>(DEFAULT_OPTIONS);
|
||||
const [origin, setOrigin] = useState('');
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
setOptions(load());
|
||||
setOrigin(window.location.origin);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(options));
|
||||
} catch {
|
||||
// storage unavailable
|
||||
}
|
||||
}, [options]);
|
||||
|
||||
const url = buildOverlayUrl(origin, options);
|
||||
const set = <K extends keyof OverlayOptions>(key: K, value: OverlayOptions[K]) => setOptions((prev) => ({ ...prev, [key]: value }));
|
||||
|
||||
const copy = async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(url);
|
||||
setCopied(true);
|
||||
setTimeout(() => setCopied(false), 1500);
|
||||
} catch {
|
||||
// clipboard blocked; the URL is still selectable in the field
|
||||
}
|
||||
};
|
||||
|
||||
const select = <K extends 'theme' | 'pos' | 'size' | 'anim'>(key: K, label: string, values: readonly OverlayOptions[K][]) => (
|
||||
<label className="field">
|
||||
<span>{label}</span>
|
||||
<select value={options[key]} onChange={(event) => set(key, event.target.value as OverlayOptions[K])}>
|
||||
{values.map((value) => (
|
||||
<option key={value} value={value}>{LABELS[value] ?? value}</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="modal" onClick={onClose}>
|
||||
<div className="modal__card modal__card--wide" onClick={(event) => event.stopPropagation()}>
|
||||
<div className="modal__head">
|
||||
<h2>Overlay for OBS</h2>
|
||||
<button type="button" className="btn btn--icon" onClick={onClose} aria-label="Close">
|
||||
<X size={16} />
|
||||
</button>
|
||||
</div>
|
||||
<p className="muted">Add the URL below as a Browser Source. Settings are stored in the URL, so one source can have its own look.</p>
|
||||
<div className="fields">
|
||||
{select('theme', 'Theme', THEMES)}
|
||||
{select('pos', 'Position', POSITIONS)}
|
||||
{select('size', 'Text size', SIZES)}
|
||||
{select('anim', 'Animation', ANIMATIONS)}
|
||||
<label className="field">
|
||||
<span>Hide after (seconds, 0 = never)</span>
|
||||
<input type="number" min={0} max={600} value={options.hide} onChange={(event) => set('hide', Math.max(0, Number(event.target.value) || 0))} />
|
||||
</label>
|
||||
<label className="field">
|
||||
<span>Max width (px on a 1080p canvas, scales with source size)</span>
|
||||
<input type="number" min={240} max={1920} step={20} value={options.width} onChange={(event) => set('width', Math.max(240, Number(event.target.value) || 240))} />
|
||||
</label>
|
||||
</div>
|
||||
<div className="urlbox">
|
||||
<input readOnly value={url} onFocus={(event) => event.target.select()} />
|
||||
<button type="button" className="btn" onClick={copy}>
|
||||
{copied ? <Check size={14} /> : <Copy size={14} />}
|
||||
{copied ? 'Copied' : 'Copy'}
|
||||
</button>
|
||||
<a className="btn" href={url} target="_blank" rel="noopener noreferrer">
|
||||
<ExternalLink size={14} />
|
||||
Open
|
||||
</a>
|
||||
</div>
|
||||
<p className="muted">Recommended Browser Source size: 1920 × 1080, with “Shutdown source when not visible” off so the connection stays warm.</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
'use client';
|
||||
|
||||
import { BarChart3, MonitorPlay, Pause, Play, Search, Unplug } from 'lucide-react';
|
||||
import type { RefObject } from 'react';
|
||||
import type { ConnectionStatus, Poll } from '@shared/chat';
|
||||
import type { StreamState } from '../lib/useEvents';
|
||||
|
||||
type Props = {
|
||||
status: ConnectionStatus;
|
||||
stream: StreamState;
|
||||
poll: Poll | null;
|
||||
counts: { chat: number; super: number; members: number };
|
||||
search: string;
|
||||
searchRef: RefObject<HTMLInputElement | null>;
|
||||
onSearch: (value: string) => void;
|
||||
paused: boolean;
|
||||
onTogglePause: () => void;
|
||||
onOverlaySettings: () => void;
|
||||
onDisconnect: () => void;
|
||||
};
|
||||
|
||||
function statusLabel(status: ConnectionStatus, stream: StreamState): { text: string; tone: string } {
|
||||
if (stream === 'error') return { text: 'Backend unreachable', tone: 'danger' };
|
||||
if (stream === 'connecting') return { text: 'Connecting to backend', tone: 'muted' };
|
||||
switch (status.state) {
|
||||
case 'live':
|
||||
return { text: 'Live', tone: 'live' };
|
||||
case 'connecting':
|
||||
return { text: 'Connecting', tone: 'warn' };
|
||||
case 'reconnecting':
|
||||
return { text: 'Reconnecting', tone: 'warn' };
|
||||
default:
|
||||
return { text: status.error ? `Disconnected: ${status.error}` : 'Disconnected', tone: 'danger' };
|
||||
}
|
||||
}
|
||||
|
||||
export function TopBar({ status, stream, poll, counts, search, searchRef, onSearch, paused, onTogglePause, onOverlaySettings, onDisconnect }: Props) {
|
||||
const label = statusLabel(status, stream);
|
||||
return (
|
||||
<header className="topbar">
|
||||
<div className="topbar__stream">
|
||||
<span className={`dot dot--${label.tone}`} />
|
||||
<span className="topbar__title" title={status.liveId ?? undefined}>{status.title || status.liveId || 'No stream'}</span>
|
||||
<span className={`chip chip--${label.tone}`}>{label.text}</span>
|
||||
{poll?.active && (
|
||||
<span className="chip chip--poll" title="A poll is running on YouTube">
|
||||
<BarChart3 size={12} />
|
||||
Poll
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<label className="search">
|
||||
<Search size={14} />
|
||||
<input ref={searchRef} value={search} onChange={(event) => onSearch(event.target.value)} placeholder="Search author or text ( / )" spellCheck={false} />
|
||||
</label>
|
||||
|
||||
<div className="topbar__stats">
|
||||
<span title="Chat messages kept">{counts.chat} chat</span>
|
||||
<span title="Super Chats this session">{counts.super} super</span>
|
||||
<span title="Memberships this session">{counts.members} members</span>
|
||||
</div>
|
||||
|
||||
<div className="topbar__actions">
|
||||
<button type="button" className={`btn btn--icon ${paused ? 'btn--active' : ''}`} onClick={onTogglePause} title={paused ? 'Resume chat (P)' : 'Pause chat (P)'}>
|
||||
{paused ? <Play size={16} /> : <Pause size={16} />}
|
||||
</button>
|
||||
<button type="button" className="btn" onClick={onOverlaySettings} title="Overlay URL and look">
|
||||
<MonitorPlay size={15} />
|
||||
Overlay
|
||||
</button>
|
||||
<button type="button" className="btn btn--icon btn--danger" onClick={onDisconnect} title="Disconnect from this stream">
|
||||
<Unplug size={16} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
'use client';
|
||||
|
||||
import React, { createContext, useContext, useState, useEffect } from 'react';
|
||||
import { getBrowserTimezone } from './timezone';
|
||||
|
||||
interface TimezoneContextType {
|
||||
timezone: string;
|
||||
setTimezone: (timezone: string) => void;
|
||||
}
|
||||
|
||||
const TimezoneContext = createContext<TimezoneContextType | undefined>(undefined);
|
||||
|
||||
export function TimezoneProvider({ children }: { children: React.ReactNode }) {
|
||||
// Initialize with detected timezone immediately to avoid empty string
|
||||
const [timezone, setTimezone] = useState<string>(() => {
|
||||
try {
|
||||
return getBrowserTimezone();
|
||||
} catch (error) {
|
||||
console.warn('Failed to detect timezone on initialization:', error);
|
||||
return 'UTC';
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Re-detect browser timezone on mount (in case it changed)
|
||||
const detectedTimezone = getBrowserTimezone();
|
||||
setTimezone(detectedTimezone);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<TimezoneContext.Provider value={{ timezone, setTimezone }}>
|
||||
{children}
|
||||
</TimezoneContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export function useTimezone() {
|
||||
const context = useContext(TimezoneContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useTimezone must be used within a TimezoneProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { BACKEND_URL } from './config';
|
||||
|
||||
async function call<T = unknown>(path: string, init?: RequestInit): Promise<T> {
|
||||
const response = await fetch(`${BACKEND_URL}${path}`, init);
|
||||
if (!response.ok) {
|
||||
let message = `HTTP ${response.status}`;
|
||||
try {
|
||||
const body = await response.json();
|
||||
if (body?.error) message = String(body.error);
|
||||
} catch {
|
||||
// body was not JSON
|
||||
}
|
||||
throw new Error(message);
|
||||
}
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
const json = (body: unknown): RequestInit => ({
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
export const api = {
|
||||
connect: (liveId: string) => call<{ ok: true; liveId: string }>('/chat/connect', json({ liveId })),
|
||||
disconnect: () => call('/chat/disconnect', { method: 'POST' }),
|
||||
select: (id: string) => call('/overlay/selection', json({ id })),
|
||||
clearSelection: () => call('/overlay/selection', { method: 'DELETE' })
|
||||
};
|
||||
@@ -0,0 +1,2 @@
|
||||
/** Backend origin. Empty means same origin, which is the case when the backend serves the built client. */
|
||||
export const BACKEND_URL = (process.env.NEXT_PUBLIC_BACKEND_URL ?? '').replace(/\/$/, '');
|
||||
@@ -0,0 +1,27 @@
|
||||
export function formatTime(iso: string): string {
|
||||
const date = new Date(iso);
|
||||
if (Number.isNaN(date.getTime())) return '';
|
||||
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
const URL_PATTERN = /(https?:\/\/[^\s<>"']+)/gi;
|
||||
|
||||
export type TextPart = { type: 'text' | 'link'; content: string };
|
||||
|
||||
/** Splits plain text into text and link parts. Used only for runs YouTube did not mark as links. */
|
||||
export function splitLinks(text: string): TextPart[] {
|
||||
const parts: TextPart[] = [];
|
||||
let last = 0;
|
||||
for (const match of text.matchAll(URL_PATTERN)) {
|
||||
const index = match.index ?? 0;
|
||||
if (index > last) parts.push({ type: 'text', content: text.slice(last, index) });
|
||||
parts.push({ type: 'link', content: match[0] });
|
||||
last = index + match[0].length;
|
||||
}
|
||||
if (last < text.length) parts.push({ type: 'text', content: text.slice(last) });
|
||||
return parts;
|
||||
}
|
||||
|
||||
export function formatAmount(amount: string, currency: string): string {
|
||||
return currency ? `${currency} ${amount}` : amount;
|
||||
}
|
||||
@@ -1,27 +1,17 @@
|
||||
const BACKEND_URL = process.env.NEXT_PUBLIC_BACKEND_URL ?? 'http://localhost:4100';
|
||||
import { BACKEND_URL } from './config';
|
||||
|
||||
/**
|
||||
* Converts a YouTube CDN image URL to use our backend proxy
|
||||
* This prevents 429 rate limit errors from YouTube's CDN
|
||||
*/
|
||||
const PROXIED_HOSTS = new Set(['yt3.ggpht.com', 'yt4.ggpht.com', 'i.ytimg.com', 'lh3.googleusercontent.com']);
|
||||
|
||||
/** Routes YouTube CDN images through the backend cache so OBS and the dashboard do not hit CDN rate limits. */
|
||||
export function proxyImageUrl(url: string | undefined): string | undefined {
|
||||
if (!url) return undefined;
|
||||
|
||||
// Check if it's a YouTube CDN URL
|
||||
const youtubeCdnDomains = ['yt3.ggpht.com', 'yt4.ggpht.com', 'i.ytimg.com'];
|
||||
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
if (youtubeCdnDomains.includes(urlObj.hostname)) {
|
||||
// Proxy through our backend
|
||||
const parsed = new URL(url);
|
||||
if (PROXIED_HOSTS.has(parsed.hostname)) {
|
||||
return `${BACKEND_URL}/proxy/image?url=${encodeURIComponent(url)}`;
|
||||
}
|
||||
} catch {
|
||||
// If URL parsing fails, return as-is
|
||||
return url;
|
||||
}
|
||||
|
||||
// Return non-YouTube URLs as-is
|
||||
return url;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
export const THEMES = ['dark', 'light', 'blueprint', 'glass', 'youtube'] as const;
|
||||
export const POSITIONS = ['bl', 'bc', 'br', 'tl', 'tc', 'tr'] as const;
|
||||
export const SIZES = ['s', 'm', 'l', 'xl'] as const;
|
||||
export const ANIMATIONS = ['fade', 'slide', 'none'] as const;
|
||||
|
||||
export type OverlayOptions = {
|
||||
theme: (typeof THEMES)[number];
|
||||
pos: (typeof POSITIONS)[number];
|
||||
size: (typeof SIZES)[number];
|
||||
anim: (typeof ANIMATIONS)[number];
|
||||
/** Seconds before the overlay hides the message by itself. 0 keeps it until cleared. */
|
||||
hide: number;
|
||||
/** Max card width in pixels. */
|
||||
width: number;
|
||||
};
|
||||
|
||||
export const DEFAULT_OPTIONS: OverlayOptions = { theme: 'dark', pos: 'bl', size: 'm', anim: 'fade', hide: 0, width: 640 };
|
||||
|
||||
function pick<T extends readonly string[]>(list: T, value: string | null, fallback: T[number]): T[number] {
|
||||
return value && (list as readonly string[]).includes(value) ? (value as T[number]) : fallback;
|
||||
}
|
||||
|
||||
export function parseOverlayOptions(search: string): OverlayOptions {
|
||||
const params = new URLSearchParams(search);
|
||||
const hide = Number(params.get('hide'));
|
||||
const width = Number(params.get('w'));
|
||||
return {
|
||||
theme: pick(THEMES, params.get('theme'), DEFAULT_OPTIONS.theme),
|
||||
pos: pick(POSITIONS, params.get('pos'), DEFAULT_OPTIONS.pos),
|
||||
size: pick(SIZES, params.get('size'), DEFAULT_OPTIONS.size),
|
||||
anim: pick(ANIMATIONS, params.get('anim'), DEFAULT_OPTIONS.anim),
|
||||
hide: Number.isFinite(hide) && hide >= 0 ? Math.floor(hide) : DEFAULT_OPTIONS.hide,
|
||||
width: Number.isFinite(width) && width >= 240 ? Math.floor(width) : DEFAULT_OPTIONS.width
|
||||
};
|
||||
}
|
||||
|
||||
/** Only non-default values go in the URL so the plain /overlay/ link keeps working. */
|
||||
export function buildOverlayUrl(origin: string, options: OverlayOptions): string {
|
||||
const params = new URLSearchParams();
|
||||
if (options.theme !== DEFAULT_OPTIONS.theme) params.set('theme', options.theme);
|
||||
if (options.pos !== DEFAULT_OPTIONS.pos) params.set('pos', options.pos);
|
||||
if (options.size !== DEFAULT_OPTIONS.size) params.set('size', options.size);
|
||||
if (options.anim !== DEFAULT_OPTIONS.anim) params.set('anim', options.anim);
|
||||
if (options.hide !== DEFAULT_OPTIONS.hide) params.set('hide', String(options.hide));
|
||||
if (options.width !== DEFAULT_OPTIONS.width) params.set('w', String(options.width));
|
||||
const query = params.toString();
|
||||
return `${origin}/overlay/${query ? `?${query}` : ''}`;
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
/**
|
||||
* Timezone utilities for handling browser timezone detection and formatting
|
||||
*/
|
||||
|
||||
export function getBrowserTimezone(): string {
|
||||
try {
|
||||
return Intl.DateTimeFormat().resolvedOptions().timeZone;
|
||||
} catch (error) {
|
||||
console.warn('Failed to detect browser timezone, falling back to UTC:', error);
|
||||
return 'UTC';
|
||||
}
|
||||
}
|
||||
|
||||
export function formatTimestamp(
|
||||
isoString: string,
|
||||
timezone?: string,
|
||||
options?: Intl.DateTimeFormatOptions
|
||||
): string {
|
||||
const date = new Date(isoString);
|
||||
|
||||
if (!date || isNaN(date.getTime())) {
|
||||
return 'Invalid date';
|
||||
}
|
||||
|
||||
const defaultOptions: Intl.DateTimeFormatOptions = {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
...options
|
||||
};
|
||||
|
||||
const targetTimezone = timezone || getBrowserTimezone();
|
||||
|
||||
// If no valid timezone, fall back to local time
|
||||
if (!targetTimezone || targetTimezone === '') {
|
||||
console.warn('No valid timezone provided, using local time');
|
||||
return date.toLocaleTimeString('en-US', defaultOptions);
|
||||
}
|
||||
|
||||
try {
|
||||
const result = new Intl.DateTimeFormat('en-US', {
|
||||
...defaultOptions,
|
||||
timeZone: targetTimezone
|
||||
}).format(date);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.warn('Failed to format timestamp with timezone, falling back to local:', error);
|
||||
|
||||
// Try GMT+3 as a fallback if the detected timezone fails
|
||||
try {
|
||||
const gmt3Result = new Intl.DateTimeFormat('en-US', {
|
||||
...defaultOptions,
|
||||
timeZone: 'Europe/Istanbul' // GMT+3
|
||||
}).format(date);
|
||||
return gmt3Result;
|
||||
} catch (gmt3Error) {
|
||||
console.warn('GMT+3 fallback also failed:', gmt3Error);
|
||||
return date.toLocaleTimeString('en-US', defaultOptions);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function formatTimestampWithDate(
|
||||
isoString: string,
|
||||
timezone?: string,
|
||||
options?: Intl.DateTimeFormatOptions
|
||||
): string {
|
||||
const date = new Date(isoString);
|
||||
|
||||
if (!date || isNaN(date.getTime())) {
|
||||
return 'Invalid date';
|
||||
}
|
||||
|
||||
const defaultOptions: Intl.DateTimeFormatOptions = {
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hour12: false,
|
||||
...options
|
||||
};
|
||||
|
||||
const targetTimezone = timezone || getBrowserTimezone();
|
||||
|
||||
try {
|
||||
return new Intl.DateTimeFormat('en-US', {
|
||||
...defaultOptions,
|
||||
timeZone: targetTimezone
|
||||
}).format(date);
|
||||
} catch (error) {
|
||||
console.warn('Failed to format timestamp with timezone, falling back to local:', error);
|
||||
return date.toLocaleString('en-US', defaultOptions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
'use client';
|
||||
|
||||
import { useEffect, useReducer } from 'react';
|
||||
import type { ChatMessage, ConnectionStatus, Poll, ServerEvent, ServerEventType } from '@shared/chat';
|
||||
import { BACKEND_URL } from './config';
|
||||
|
||||
export type StreamState = 'connecting' | 'open' | 'error';
|
||||
|
||||
export type EventsState = {
|
||||
stream: StreamState;
|
||||
status: ConnectionStatus;
|
||||
messages: ChatMessage[];
|
||||
selection: ChatMessage | null;
|
||||
poll: Poll | null;
|
||||
};
|
||||
|
||||
const MAX_REGULAR = 200;
|
||||
const EVENT_TYPES: ServerEventType[] = ['init', 'message', 'selection', 'poll', 'status', 'clear'];
|
||||
|
||||
const initialState: EventsState = {
|
||||
stream: 'connecting',
|
||||
status: { state: 'disconnected', liveId: null },
|
||||
messages: [],
|
||||
selection: null,
|
||||
poll: null
|
||||
};
|
||||
|
||||
export function isSpecial(message: ChatMessage): boolean {
|
||||
return !!(message.superChat || message.membershipGift || message.membershipGiftPurchase);
|
||||
}
|
||||
|
||||
/** Appends a message and drops the oldest regular ones past the cap. Special messages are always kept. */
|
||||
function append(list: ChatMessage[], message: ChatMessage): ChatMessage[] {
|
||||
const next = [...list, message];
|
||||
let regular = 0;
|
||||
for (const item of next) if (!isSpecial(item)) regular += 1;
|
||||
let drop = regular - MAX_REGULAR;
|
||||
if (drop <= 0) return next;
|
||||
return next.filter((item) => {
|
||||
if (drop > 0 && !isSpecial(item)) {
|
||||
drop -= 1;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
type Action = ServerEvent | { type: 'stream'; stream: StreamState };
|
||||
|
||||
function reducer(state: EventsState, action: Action): EventsState {
|
||||
switch (action.type) {
|
||||
case 'stream':
|
||||
return { ...state, stream: action.stream };
|
||||
case 'init':
|
||||
return { ...state, status: action.status, messages: action.messages, selection: action.selection, poll: action.poll };
|
||||
case 'message':
|
||||
return { ...state, messages: append(state.messages, action.message) };
|
||||
case 'selection':
|
||||
return { ...state, selection: action.message };
|
||||
case 'poll':
|
||||
return { ...state, poll: action.poll };
|
||||
case 'status':
|
||||
return { ...state, status: action.status };
|
||||
case 'clear':
|
||||
return { ...state, messages: [], selection: null, poll: null };
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
/** Single SSE subscription to the backend. EventSource reconnects on its own and the server replays state on `init`. */
|
||||
export function useEvents(): EventsState {
|
||||
const [state, dispatch] = useReducer(reducer, initialState);
|
||||
|
||||
useEffect(() => {
|
||||
const source = new EventSource(`${BACKEND_URL}/events`);
|
||||
const onEvent = (event: Event) => {
|
||||
try {
|
||||
dispatch(JSON.parse((event as MessageEvent).data));
|
||||
} catch (error) {
|
||||
console.error('Bad event payload', error);
|
||||
}
|
||||
};
|
||||
for (const type of EVENT_TYPES) source.addEventListener(type, onEvent);
|
||||
source.onopen = () => dispatch({ type: 'stream', stream: 'open' });
|
||||
source.onerror = () => dispatch({ type: 'stream', stream: 'error' });
|
||||
return () => source.close();
|
||||
}, []);
|
||||
|
||||
return state;
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
/** @type {import('next').NextConfig} */
|
||||
const nextConfig = {
|
||||
reactStrictMode: true,
|
||||
experimental: {
|
||||
serverActions: {
|
||||
bodySizeLimit: '2mb'
|
||||
}
|
||||
}
|
||||
// Static export: the backend serves `client/out` so production runs on a single port.
|
||||
output: 'export',
|
||||
trailingSlash: true,
|
||||
images: { unoptimized: true }
|
||||
};
|
||||
|
||||
module.exports = nextConfig;
|
||||
|
||||
Reference in New Issue
Block a user