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:
+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>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user