feat: add auction chat
This commit is contained in:
1 parent
c4f19d256d
commit
5ad0f8a1c2
7 files changed
+449
-20
No files matched your search
@@ -272,6 +272,14 @@ export interface ApiAuctionBid {
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
export interface ApiAuctionChatMessage {
|
||||
id: string;
|
||||
userId?: string;
|
||||
displayName: string;
|
||||
message: string;
|
||||
sentAt: string;
|
||||
}
|
||||
|
||||
export interface ApiAuction {
|
||||
_id: string;
|
||||
matchId: string;
|
||||
@@ -290,6 +298,7 @@ export interface ApiAuction {
|
||||
initialPoints: number;
|
||||
topTierThreshold: AuctionTopTierThreshold;
|
||||
manualTopTierUserIds: string[];
|
||||
chatMessages?: ApiAuctionChatMessage[];
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
createdAt: string;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
import type { ApiAuction, Position } from './types';
|
||||
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
|
||||
|
||||
type ConnectionStatus =
|
||||
| 'idle'
|
||||
@@ -17,18 +17,42 @@ interface BidPayload {
|
||||
bidderUserId?: string;
|
||||
}
|
||||
|
||||
interface ChatMessagePayload {
|
||||
displayName?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface ChatHistoryPayload {
|
||||
messages?: ApiAuctionChatMessage[];
|
||||
}
|
||||
|
||||
const MAX_CHAT_MESSAGES = 200;
|
||||
|
||||
function mergeChatMessages(
|
||||
current: ApiAuctionChatMessage[],
|
||||
incoming: ApiAuctionChatMessage[],
|
||||
) {
|
||||
const byId = new Map(current.map((message) => [message.id, message]));
|
||||
for (const message of incoming) {
|
||||
byId.set(message.id, message);
|
||||
}
|
||||
|
||||
return [...byId.values()]
|
||||
.sort((left, right) => Date.parse(left.sentAt) - Date.parse(right.sentAt))
|
||||
.slice(-MAX_CHAT_MESSAGES);
|
||||
}
|
||||
|
||||
export function useAuctionSocket(matchId: string | undefined) {
|
||||
const authUserId = useAuthUserId();
|
||||
const socketRef = useRef<Socket | null>(null);
|
||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
|
||||
const [connectionStatus, setConnectionStatus] =
|
||||
useState<ConnectionStatus>('idle');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!matchId) {
|
||||
setAuction(null);
|
||||
setConnectionStatus('idle');
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -65,9 +89,20 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
socket.on('state', (nextAuction: ApiAuction) => {
|
||||
setAuction(nextAuction);
|
||||
if (nextAuction.chatMessages) {
|
||||
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||
}
|
||||
setError(null);
|
||||
});
|
||||
|
||||
socket.on('chat-history', (payload: ChatHistoryPayload) => {
|
||||
setChatMessages(mergeChatMessages([], payload.messages ?? []));
|
||||
});
|
||||
|
||||
socket.on('chat-message', (message: ApiAuctionChatMessage) => {
|
||||
setChatMessages((current) => mergeChatMessages(current, [message]));
|
||||
});
|
||||
|
||||
socket.on('error', (payload: { message?: string }) => {
|
||||
setConnectionStatus('error');
|
||||
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
||||
@@ -101,9 +136,15 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
socket.emit(eventName, payload);
|
||||
}
|
||||
|
||||
const visibleAuction = auction?.matchId === matchId ? auction : null;
|
||||
const visibleConnectionStatus: ConnectionStatus = matchId
|
||||
? connectionStatus
|
||||
: 'idle';
|
||||
|
||||
return {
|
||||
auction,
|
||||
connectionStatus,
|
||||
auction: visibleAuction,
|
||||
chatMessages: visibleAuction ? chatMessages : [],
|
||||
connectionStatus: visibleConnectionStatus,
|
||||
error,
|
||||
placeBid(payload: BidPayload) {
|
||||
emit('bid', payload);
|
||||
@@ -117,5 +158,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
next() {
|
||||
emit('next', {});
|
||||
},
|
||||
sendChatMessage(payload: ChatMessagePayload) {
|
||||
emit('chat-message', payload);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import {
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type FormEvent,
|
||||
type KeyboardEvent,
|
||||
} from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { SendHorizontal } from 'lucide-react';
|
||||
import { Link, useLocation, useParams } from 'react-router';
|
||||
import {
|
||||
useAuction,
|
||||
@@ -34,8 +42,10 @@ import {
|
||||
} from '../lib/league';
|
||||
import type {
|
||||
ApiAuction,
|
||||
ApiAuctionChatMessage,
|
||||
ApiRiotLaneStats,
|
||||
ApiTierInfo,
|
||||
ApiUser,
|
||||
Position,
|
||||
} from '../api/types';
|
||||
|
||||
@@ -73,6 +83,31 @@ function relativeTime(dateLike: string) {
|
||||
return `${Math.floor(hours / 24)}일 전`;
|
||||
}
|
||||
|
||||
function formatChatTime(dateLike: string) {
|
||||
return new Intl.DateTimeFormat('ko-KR', {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(new Date(dateLike));
|
||||
}
|
||||
|
||||
function resolveChatSenderLabel(
|
||||
currentUser: ApiUser | null,
|
||||
captainRole: CaptainRole | null,
|
||||
) {
|
||||
const primaryRiotAccount =
|
||||
currentUser?.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||
currentUser?.riotAccounts[0];
|
||||
if (primaryRiotAccount?.gameName) {
|
||||
return primaryRiotAccount.tagLine
|
||||
? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}`
|
||||
: primaryRiotAccount.gameName;
|
||||
}
|
||||
if (currentUser?.kakaoTalkNickname) return currentUser.kakaoTalkNickname;
|
||||
if (currentUser?.discordNickname) return currentUser.discordNickname;
|
||||
if (captainRole) return `${teamIndexLabel(captainRole.teamIndex)} 팀장`;
|
||||
return '관전자';
|
||||
}
|
||||
|
||||
function normalizeRank(rank: string | undefined) {
|
||||
switch (rank) {
|
||||
case 'I':
|
||||
@@ -738,6 +773,7 @@ export default function AuctionPage() {
|
||||
: {
|
||||
teamIndex: captainTeamIndex,
|
||||
};
|
||||
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
|
||||
|
||||
useEffect(() => {
|
||||
if (auctionState?.currentPlayer) {
|
||||
@@ -1073,9 +1109,35 @@ export default function AuctionPage() {
|
||||
</div>
|
||||
|
||||
<aside className="hidden xl:block">
|
||||
<ChatPanel />
|
||||
<ChatPanel
|
||||
messages={socket.chatMessages}
|
||||
connectionStatus={socket.connectionStatus}
|
||||
senderLabel={chatSenderLabel}
|
||||
onSend={(message) =>
|
||||
socket.sendChatMessage({
|
||||
displayName: chatSenderLabel,
|
||||
message,
|
||||
})
|
||||
}
|
||||
className="sticky top-4 h-[520px] max-h-[calc(100vh-2rem)]"
|
||||
/>
|
||||
</aside>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 xl:hidden">
|
||||
<ChatPanel
|
||||
messages={socket.chatMessages}
|
||||
connectionStatus={socket.connectionStatus}
|
||||
senderLabel={chatSenderLabel}
|
||||
onSend={(message) =>
|
||||
socket.sendChatMessage({
|
||||
displayName: chatSenderLabel,
|
||||
message,
|
||||
})
|
||||
}
|
||||
className="h-[420px]"
|
||||
/>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1231,37 +1293,120 @@ function PoolListItem({
|
||||
);
|
||||
}
|
||||
|
||||
function ChatPanel() {
|
||||
function ChatPanel({
|
||||
messages,
|
||||
connectionStatus,
|
||||
senderLabel,
|
||||
onSend,
|
||||
className = '',
|
||||
}: {
|
||||
messages: ApiAuctionChatMessage[];
|
||||
connectionStatus: ReturnType<typeof useAuctionSocket>['connectionStatus'];
|
||||
senderLabel: string;
|
||||
onSend: (message: string) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const [draft, setDraft] = useState('');
|
||||
const messagesEndRef = useRef<HTMLDivElement | null>(null);
|
||||
const trimmedDraft = draft.trim();
|
||||
const isConnected = connectionStatus === 'connected';
|
||||
const canSend = isConnected && trimmedDraft.length > 0;
|
||||
|
||||
useEffect(() => {
|
||||
messagesEndRef.current?.scrollIntoView({ block: 'end' });
|
||||
}, [messages.length]);
|
||||
|
||||
function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!canSend) return;
|
||||
onSend(trimmedDraft);
|
||||
setDraft('');
|
||||
}
|
||||
|
||||
function handleKeyDown(event: KeyboardEvent<HTMLTextAreaElement>) {
|
||||
if (event.key !== 'Enter' || event.shiftKey) return;
|
||||
event.preventDefault();
|
||||
if (!canSend) return;
|
||||
onSend(trimmedDraft);
|
||||
setDraft('');
|
||||
}
|
||||
|
||||
const statusLabel =
|
||||
connectionStatus === 'connected'
|
||||
? '실시간'
|
||||
: connectionStatus === 'connecting'
|
||||
? '연결 중'
|
||||
: '오프라인';
|
||||
|
||||
return (
|
||||
<div className="border border-base-content/10 bg-base-100 sticky top-4 h-[calc(100vh-2rem)] flex flex-col">
|
||||
<div
|
||||
className={`border border-base-content/10 bg-base-100 flex min-h-0 flex-col ${className}`}
|
||||
>
|
||||
<div className="border-b border-base-content/10 px-3 py-2.5 flex items-center justify-between">
|
||||
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
||||
채팅
|
||||
</div>
|
||||
<span className="text-[10px] text-base-content/30">
|
||||
곧 활성화됩니다
|
||||
<span
|
||||
className={`text-[10px] ${
|
||||
isConnected ? 'text-green-500' : 'text-base-content/30'
|
||||
}`}
|
||||
>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="flex-1 overflow-y-auto px-3 py-8 text-center text-[11px] text-base-content/25">
|
||||
아직 메시지가 없습니다
|
||||
<div className="flex-1 min-h-0 overflow-y-auto px-3 py-3">
|
||||
{messages.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-center text-[11px] text-base-content/25">
|
||||
아직 메시지가 없습니다
|
||||
</div>
|
||||
) : (
|
||||
<ol className="space-y-3">
|
||||
{messages.map((message) => (
|
||||
<li key={message.id} className="space-y-1">
|
||||
<div className="flex items-center justify-between gap-2">
|
||||
<span className="min-w-0 truncate text-[11px] font-bold text-base-content/70">
|
||||
{message.displayName}
|
||||
</span>
|
||||
<time className="shrink-0 text-[10px] tabular-nums text-base-content/25">
|
||||
{formatChatTime(message.sentAt)}
|
||||
</time>
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap break-words border border-base-content/8 bg-base-content/[0.03] px-2.5 py-2 text-[12px] leading-relaxed text-base-content/75">
|
||||
{message.message}
|
||||
</p>
|
||||
</li>
|
||||
))}
|
||||
</ol>
|
||||
)}
|
||||
<div ref={messagesEndRef} />
|
||||
</div>
|
||||
|
||||
<div className="border-t border-base-content/10 p-2 space-y-2">
|
||||
<form onSubmit={handleSubmit} className="border-t border-base-content/10 p-2 space-y-2">
|
||||
<div className="flex items-center justify-between gap-2 px-0.5 text-[10px] text-base-content/30">
|
||||
<span className="truncate">{senderLabel}</span>
|
||||
<span className="tabular-nums">{draft.length}/300</span>
|
||||
</div>
|
||||
<textarea
|
||||
disabled
|
||||
value={draft}
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
disabled={!isConnected}
|
||||
maxLength={300}
|
||||
placeholder="메시지를 입력하세요"
|
||||
className="w-full resize-none border border-base-content/10 bg-base-content/5 px-2 py-1.5 text-[12px] text-base-content/40 placeholder:text-base-content/25 focus:outline-none"
|
||||
className="w-full resize-none border border-base-content/10 bg-base-content/5 px-2 py-1.5 text-[12px] text-base-content/80 placeholder:text-base-content/25 focus:border-primary/40 focus:outline-none disabled:cursor-not-allowed disabled:text-base-content/30"
|
||||
rows={2}
|
||||
aria-label="경매 채팅 메시지"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
disabled
|
||||
className="btn btn-primary btn-sm w-full text-[11px] opacity-50"
|
||||
type="submit"
|
||||
disabled={!canSend}
|
||||
className="btn btn-primary btn-sm w-full text-[11px]"
|
||||
>
|
||||
<SendHorizontal className="h-3.5 w-3.5" aria-hidden="true" />
|
||||
전송
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user