feat: add auction chat
This commit is contained in:
1 parent
c4f19d256d
commit
5ad0f8a1c2
7 files changed
+448
-19
No files matched your search
@@ -16,6 +16,7 @@ import { IdentityService } from '../auth/identity.service';
|
|||||||
import { JwtService } from '../auth/jwt.service';
|
import { JwtService } from '../auth/jwt.service';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import type {
|
import type {
|
||||||
|
AuctionChatMessage,
|
||||||
AuctionDocument,
|
AuctionDocument,
|
||||||
IdentityDocument,
|
IdentityDocument,
|
||||||
Position,
|
Position,
|
||||||
@@ -37,6 +38,11 @@ interface SoldPayload {
|
|||||||
assignedPosition?: Position;
|
assignedPosition?: Position;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ChatMessagePayload {
|
||||||
|
message?: string;
|
||||||
|
displayName?: string;
|
||||||
|
}
|
||||||
|
|
||||||
@WebSocketGateway({
|
@WebSocketGateway({
|
||||||
namespace: '/auction',
|
namespace: '/auction',
|
||||||
cors: {
|
cors: {
|
||||||
@@ -100,6 +106,7 @@ export class AuctionGateway
|
|||||||
const auction = await this.auctionService.getByMatchId(
|
const auction = await this.auctionService.getByMatchId(
|
||||||
new mongoose.Types.ObjectId(payload.matchId),
|
new mongoose.Types.ObjectId(payload.matchId),
|
||||||
);
|
);
|
||||||
|
this.emitChatHistory(socket, auction);
|
||||||
this.broadcastState(payload.matchId, auction);
|
this.broadcastState(payload.matchId, auction);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.emitKnownError(socket, error);
|
this.emitKnownError(socket, error);
|
||||||
@@ -182,6 +189,34 @@ export class AuctionGateway
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SubscribeMessage('chat-message')
|
||||||
|
public async handleChatMessage(
|
||||||
|
@ConnectedSocket() socket: Socket,
|
||||||
|
@MessageBody() payload: ChatMessagePayload,
|
||||||
|
) {
|
||||||
|
const matchId = this.requireJoinedMatchId(socket);
|
||||||
|
if (!matchId) return;
|
||||||
|
|
||||||
|
if (typeof payload?.message !== 'string') {
|
||||||
|
this.emitError(socket, 'Chat message is required.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { message } = await this.auctionService.appendChatMessage({
|
||||||
|
matchId: new mongoose.Types.ObjectId(matchId),
|
||||||
|
userId: this.resolveSocketUserId(socket),
|
||||||
|
displayName: this.resolveChatDisplayName(socket, payload.displayName),
|
||||||
|
message: payload.message,
|
||||||
|
});
|
||||||
|
this.server
|
||||||
|
.to(matchId)
|
||||||
|
.emit('chat-message', this.serializeChatMessage(message));
|
||||||
|
} catch (error) {
|
||||||
|
this.emitKnownError(socket, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private requireJoinedMatchId(socket: Socket): string | null {
|
private requireJoinedMatchId(socket: Socket): string | null {
|
||||||
const matchId = this.getSocketMatchId(socket);
|
const matchId = this.getSocketMatchId(socket);
|
||||||
if (!matchId) {
|
if (!matchId) {
|
||||||
@@ -219,6 +254,36 @@ export class AuctionGateway
|
|||||||
return Array.isArray(header) ? header[0] : header;
|
return Array.isArray(header) ? header[0] : header;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private resolveSocketUserId(
|
||||||
|
socket: Socket,
|
||||||
|
): mongoose.Types.ObjectId | undefined {
|
||||||
|
return (socket.data.user as UserDocument | undefined)?._id;
|
||||||
|
}
|
||||||
|
|
||||||
|
private resolveChatDisplayName(
|
||||||
|
socket: Socket,
|
||||||
|
fallbackDisplayName?: string,
|
||||||
|
): string {
|
||||||
|
const user = socket.data.user as UserDocument | undefined;
|
||||||
|
const primaryRiotAccount =
|
||||||
|
user?.riotAccounts.find((entry) => entry.isPrimary) ??
|
||||||
|
user?.riotAccounts[0];
|
||||||
|
if (primaryRiotAccount?.gameName) {
|
||||||
|
return primaryRiotAccount.tagLine
|
||||||
|
? `${primaryRiotAccount.gameName}#${primaryRiotAccount.tagLine}`
|
||||||
|
: primaryRiotAccount.gameName;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (user?.kakaoTalkNickname) return user.kakaoTalkNickname;
|
||||||
|
if (user?.discordNickname) return user.discordNickname;
|
||||||
|
|
||||||
|
const identity = socket.data.identity as IdentityDocument | undefined;
|
||||||
|
if (identity?.displayName) return identity.displayName;
|
||||||
|
if (identity?.email) return identity.email;
|
||||||
|
|
||||||
|
return fallbackDisplayName ?? '관전자';
|
||||||
|
}
|
||||||
|
|
||||||
private async authenticateSocket(socket: Socket): Promise<void> {
|
private async authenticateSocket(socket: Socket): Promise<void> {
|
||||||
const fallback = await this.authService.resolveDevUserById(
|
const fallback = await this.authService.resolveDevUserById(
|
||||||
this.readHandshakeUserId(socket),
|
this.readHandshakeUserId(socket),
|
||||||
@@ -299,6 +364,14 @@ export class AuctionGateway
|
|||||||
this.syncRoomTimer(matchId, auction);
|
this.syncRoomTimer(matchId, auction);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private emitChatHistory(socket: Socket, auction: AuctionDocument) {
|
||||||
|
socket.emit('chat-history', {
|
||||||
|
messages: (auction.chatMessages ?? []).map((message) =>
|
||||||
|
this.serializeChatMessage(message),
|
||||||
|
),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
|
private syncRoomTimer(matchId: string, auction: AuctionDocument) {
|
||||||
this.clearRoomTimer(matchId);
|
this.clearRoomTimer(matchId);
|
||||||
if (!auction.currentDeadline) return;
|
if (!auction.currentDeadline) return;
|
||||||
@@ -382,4 +455,8 @@ export class AuctionGateway
|
|||||||
private serializeAuction(auction: AuctionDocument) {
|
private serializeAuction(auction: AuctionDocument) {
|
||||||
return JSON.parse(JSON.stringify(auction));
|
return JSON.parse(JSON.stringify(auction));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private serializeChatMessage(message: AuctionChatMessage) {
|
||||||
|
return JSON.parse(JSON.stringify(message));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -159,6 +159,76 @@ describe('AuctionService', () => {
|
|||||||
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
expect(tournamentResultService.scheduleInitialPoll).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('appends a chat message and keeps only the latest 200 messages', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const userId = new mongoose.Types.ObjectId();
|
||||||
|
const oldMessages = Array.from({ length: 200 }, (_, index) => ({
|
||||||
|
id: `old-${index}`,
|
||||||
|
displayName: 'Old',
|
||||||
|
message: `old message ${index}`,
|
||||||
|
sentAt: new Date(index),
|
||||||
|
}));
|
||||||
|
const auction = {
|
||||||
|
matchId,
|
||||||
|
chatMessages: oldMessages,
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const { service } = createService({
|
||||||
|
auction: {
|
||||||
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const appended = await service.appendChatMessage({
|
||||||
|
matchId,
|
||||||
|
userId,
|
||||||
|
displayName: ' Captain One ',
|
||||||
|
message: ' 좋은 픽입니다 ',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(appended.message).toMatchObject({
|
||||||
|
userId,
|
||||||
|
displayName: 'Captain One',
|
||||||
|
message: '좋은 픽입니다',
|
||||||
|
});
|
||||||
|
expect(appended.message.id).toHaveLength(36);
|
||||||
|
expect(appended.message.sentAt).toBeInstanceOf(Date);
|
||||||
|
expect(auction.chatMessages).toHaveLength(200);
|
||||||
|
expect(auction.chatMessages[0].id).toBe('old-1');
|
||||||
|
expect(auction.chatMessages.at(-1)).toBe(appended.message);
|
||||||
|
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects blank and overly long chat messages', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const auction = {
|
||||||
|
matchId,
|
||||||
|
chatMessages: [],
|
||||||
|
save: jest.fn().mockResolvedValue(undefined),
|
||||||
|
};
|
||||||
|
const { service } = createService({
|
||||||
|
auction: {
|
||||||
|
findOne: jest.fn().mockResolvedValue(auction),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.appendChatMessage({
|
||||||
|
matchId,
|
||||||
|
displayName: 'Spectator',
|
||||||
|
message: ' ',
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Chat message is required.');
|
||||||
|
await expect(
|
||||||
|
service.appendChatMessage({
|
||||||
|
matchId,
|
||||||
|
displayName: 'Spectator',
|
||||||
|
message: 'a'.repeat(301),
|
||||||
|
}),
|
||||||
|
).rejects.toThrow('Chat message must be 300 characters or less.');
|
||||||
|
expect(auction.save).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('randomizes the non-captain player order when starting an auction', async () => {
|
it('randomizes the non-captain player order when starting an auction', async () => {
|
||||||
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0);
|
const randomSpy = jest.spyOn(Math, 'random').mockReturnValue(0);
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import {
|
|||||||
Logger,
|
Logger,
|
||||||
NotFoundException,
|
NotFoundException,
|
||||||
} from '@nestjs/common';
|
} from '@nestjs/common';
|
||||||
|
import { randomUUID } from 'crypto';
|
||||||
import mongoose from 'mongoose';
|
import mongoose from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import {
|
import {
|
||||||
AuctionActionType,
|
AuctionActionType,
|
||||||
|
AuctionChatMessage,
|
||||||
AuctionDocument,
|
AuctionDocument,
|
||||||
AuctionPlayerSnapshot,
|
AuctionPlayerSnapshot,
|
||||||
AuctionTeam,
|
AuctionTeam,
|
||||||
@@ -26,6 +28,9 @@ import { TournamentResultService } from '../tournament-result/tournament-result.
|
|||||||
const AUCTION_MAX_TEAM_SIZE = 5;
|
const AUCTION_MAX_TEAM_SIZE = 5;
|
||||||
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
|
const AUCTION_BACKGROUND_ENRICHMENT_CONCURRENCY = 1;
|
||||||
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
|
const AUCTION_ENRICHMENT_COOLDOWN_MS = 3 * 60 * 60 * 1000;
|
||||||
|
const AUCTION_CHAT_MAX_MESSAGES = 200;
|
||||||
|
const AUCTION_CHAT_MAX_MESSAGE_LENGTH = 300;
|
||||||
|
const AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH = 24;
|
||||||
|
|
||||||
interface StartAuctionParams {
|
interface StartAuctionParams {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
@@ -54,6 +59,13 @@ interface MarkSoldParams {
|
|||||||
assignedPosition?: Position;
|
assignedPosition?: Position;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface AppendChatMessageParams {
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
userId?: mongoose.Types.ObjectId;
|
||||||
|
displayName?: string;
|
||||||
|
message: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AuctionHistoryView {
|
export interface AuctionHistoryView {
|
||||||
sequence: number;
|
sequence: number;
|
||||||
action: AuctionActionType;
|
action: AuctionActionType;
|
||||||
@@ -221,6 +233,31 @@ export class AuctionService {
|
|||||||
return auction;
|
return auction;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
|
||||||
|
auction: AuctionDocument;
|
||||||
|
message: AuctionChatMessage;
|
||||||
|
}> {
|
||||||
|
const auction = await this.getByMatchId(params.matchId);
|
||||||
|
const messageText = this.normalizeChatMessage(params.message);
|
||||||
|
const message: AuctionChatMessage = {
|
||||||
|
id: randomUUID(),
|
||||||
|
userId: params.userId,
|
||||||
|
displayName: this.normalizeChatDisplayName(params.displayName),
|
||||||
|
message: messageText,
|
||||||
|
sentAt: new Date(),
|
||||||
|
};
|
||||||
|
|
||||||
|
auction.chatMessages ??= [];
|
||||||
|
auction.chatMessages.push(message);
|
||||||
|
const overflow = auction.chatMessages.length - AUCTION_CHAT_MAX_MESSAGES;
|
||||||
|
if (overflow > 0) {
|
||||||
|
auction.chatMessages.splice(0, overflow);
|
||||||
|
}
|
||||||
|
|
||||||
|
await auction.save();
|
||||||
|
return { auction, message };
|
||||||
|
}
|
||||||
|
|
||||||
public async listHistory(params: {
|
public async listHistory(params: {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
communityId: mongoose.Types.ObjectId;
|
communityId: mongoose.Types.ObjectId;
|
||||||
@@ -601,6 +638,28 @@ export class AuctionService {
|
|||||||
return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot;
|
return JSON.parse(JSON.stringify(player)) as AuctionPlayerSnapshot;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private normalizeChatMessage(message: string): string {
|
||||||
|
const normalized = message.trim();
|
||||||
|
if (!normalized) {
|
||||||
|
throw new BadRequestException('Chat message is required.');
|
||||||
|
}
|
||||||
|
if (Array.from(normalized).length > AUCTION_CHAT_MAX_MESSAGE_LENGTH) {
|
||||||
|
throw new BadRequestException(
|
||||||
|
`Chat message must be ${AUCTION_CHAT_MAX_MESSAGE_LENGTH} characters or less.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
|
||||||
|
private normalizeChatDisplayName(displayName: string | undefined): string {
|
||||||
|
const normalized = displayName?.trim() || '관전자';
|
||||||
|
const chars = Array.from(normalized);
|
||||||
|
if (chars.length <= AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH) {
|
||||||
|
return normalized;
|
||||||
|
}
|
||||||
|
return chars.slice(0, AUCTION_CHAT_MAX_DISPLAY_NAME_LENGTH).join('');
|
||||||
|
}
|
||||||
|
|
||||||
private async recordSnapshot(
|
private async recordSnapshot(
|
||||||
auction: AuctionDocument,
|
auction: AuctionDocument,
|
||||||
action: AuctionActionType,
|
action: AuctionActionType,
|
||||||
|
|||||||
@@ -618,6 +618,14 @@ export interface AuctionBid {
|
|||||||
timestamp: Date;
|
timestamp: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AuctionChatMessage {
|
||||||
|
id: string;
|
||||||
|
userId?: mongoose.Types.ObjectId;
|
||||||
|
displayName: string;
|
||||||
|
message: string;
|
||||||
|
sentAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
export interface Auction extends MongooseTimestamps {
|
export interface Auction extends MongooseTimestamps {
|
||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
phase: AuctionPhase;
|
phase: AuctionPhase;
|
||||||
@@ -635,6 +643,7 @@ export interface Auction extends MongooseTimestamps {
|
|||||||
initialPoints: number;
|
initialPoints: number;
|
||||||
topTierThreshold: AuctionTopTierThreshold;
|
topTierThreshold: AuctionTopTierThreshold;
|
||||||
manualTopTierUserIds: mongoose.Types.ObjectId[];
|
manualTopTierUserIds: mongoose.Types.ObjectId[];
|
||||||
|
chatMessages: AuctionChatMessage[];
|
||||||
startedAt?: Date;
|
startedAt?: Date;
|
||||||
completedAt?: Date;
|
completedAt?: Date;
|
||||||
}
|
}
|
||||||
@@ -1566,6 +1575,17 @@ const AuctionBidSubSchema = new Schema<AuctionBid>(
|
|||||||
{ _id: false },
|
{ _id: false },
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
|
||||||
|
{
|
||||||
|
id: { type: String, required: true },
|
||||||
|
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||||
|
displayName: { type: String, required: true },
|
||||||
|
message: { type: String, required: true },
|
||||||
|
sentAt: { type: Date, required: true, default: Date.now },
|
||||||
|
},
|
||||||
|
{ _id: false },
|
||||||
|
);
|
||||||
|
|
||||||
export const AuctionSchema = new Schema<Auction>(
|
export const AuctionSchema = new Schema<Auction>(
|
||||||
{
|
{
|
||||||
matchId: {
|
matchId: {
|
||||||
@@ -1612,6 +1632,11 @@ export const AuctionSchema = new Schema<Auction>(
|
|||||||
required: true,
|
required: true,
|
||||||
default: [],
|
default: [],
|
||||||
},
|
},
|
||||||
|
chatMessages: {
|
||||||
|
type: [AuctionChatMessageSubSchema],
|
||||||
|
required: true,
|
||||||
|
default: [],
|
||||||
|
},
|
||||||
startedAt: { type: Date, required: false },
|
startedAt: { type: Date, required: false },
|
||||||
completedAt: { type: Date, required: false },
|
completedAt: { type: Date, required: false },
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -272,6 +272,14 @@ export interface ApiAuctionBid {
|
|||||||
timestamp: string;
|
timestamp: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface ApiAuctionChatMessage {
|
||||||
|
id: string;
|
||||||
|
userId?: string;
|
||||||
|
displayName: string;
|
||||||
|
message: string;
|
||||||
|
sentAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
export interface ApiAuction {
|
export interface ApiAuction {
|
||||||
_id: string;
|
_id: string;
|
||||||
matchId: string;
|
matchId: string;
|
||||||
@@ -290,6 +298,7 @@ export interface ApiAuction {
|
|||||||
initialPoints: number;
|
initialPoints: number;
|
||||||
topTierThreshold: AuctionTopTierThreshold;
|
topTierThreshold: AuctionTopTierThreshold;
|
||||||
manualTopTierUserIds: string[];
|
manualTopTierUserIds: string[];
|
||||||
|
chatMessages?: ApiAuctionChatMessage[];
|
||||||
startedAt?: string;
|
startedAt?: string;
|
||||||
completedAt?: string;
|
completedAt?: string;
|
||||||
createdAt: string;
|
createdAt: string;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react';
|
|||||||
import { io, type Socket } from 'socket.io-client';
|
import { io, type Socket } from 'socket.io-client';
|
||||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||||
import type { ApiAuction, Position } from './types';
|
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
|
||||||
|
|
||||||
type ConnectionStatus =
|
type ConnectionStatus =
|
||||||
| 'idle'
|
| 'idle'
|
||||||
@@ -17,18 +17,42 @@ interface BidPayload {
|
|||||||
bidderUserId?: string;
|
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) {
|
export function useAuctionSocket(matchId: string | undefined) {
|
||||||
const authUserId = useAuthUserId();
|
const authUserId = useAuthUserId();
|
||||||
const socketRef = useRef<Socket | null>(null);
|
const socketRef = useRef<Socket | null>(null);
|
||||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||||
|
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
|
||||||
const [connectionStatus, setConnectionStatus] =
|
const [connectionStatus, setConnectionStatus] =
|
||||||
useState<ConnectionStatus>('idle');
|
useState<ConnectionStatus>('idle');
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!matchId) {
|
if (!matchId) {
|
||||||
setAuction(null);
|
|
||||||
setConnectionStatus('idle');
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,9 +89,20 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
|
|
||||||
socket.on('state', (nextAuction: ApiAuction) => {
|
socket.on('state', (nextAuction: ApiAuction) => {
|
||||||
setAuction(nextAuction);
|
setAuction(nextAuction);
|
||||||
|
if (nextAuction.chatMessages) {
|
||||||
|
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||||
|
}
|
||||||
setError(null);
|
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 }) => {
|
socket.on('error', (payload: { message?: string }) => {
|
||||||
setConnectionStatus('error');
|
setConnectionStatus('error');
|
||||||
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
setError(payload.message ?? '실시간 경매 연결 중 오류가 발생했습니다.');
|
||||||
@@ -101,9 +136,15 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
socket.emit(eventName, payload);
|
socket.emit(eventName, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const visibleAuction = auction?.matchId === matchId ? auction : null;
|
||||||
|
const visibleConnectionStatus: ConnectionStatus = matchId
|
||||||
|
? connectionStatus
|
||||||
|
: 'idle';
|
||||||
|
|
||||||
return {
|
return {
|
||||||
auction,
|
auction: visibleAuction,
|
||||||
connectionStatus,
|
chatMessages: visibleAuction ? chatMessages : [],
|
||||||
|
connectionStatus: visibleConnectionStatus,
|
||||||
error,
|
error,
|
||||||
placeBid(payload: BidPayload) {
|
placeBid(payload: BidPayload) {
|
||||||
emit('bid', payload);
|
emit('bid', payload);
|
||||||
@@ -117,5 +158,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
|||||||
next() {
|
next() {
|
||||||
emit('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 { useQueryClient } from '@tanstack/react-query';
|
||||||
|
import { SendHorizontal } from 'lucide-react';
|
||||||
import { Link, useLocation, useParams } from 'react-router';
|
import { Link, useLocation, useParams } from 'react-router';
|
||||||
import {
|
import {
|
||||||
useAuction,
|
useAuction,
|
||||||
@@ -34,8 +42,10 @@ import {
|
|||||||
} from '../lib/league';
|
} from '../lib/league';
|
||||||
import type {
|
import type {
|
||||||
ApiAuction,
|
ApiAuction,
|
||||||
|
ApiAuctionChatMessage,
|
||||||
ApiRiotLaneStats,
|
ApiRiotLaneStats,
|
||||||
ApiTierInfo,
|
ApiTierInfo,
|
||||||
|
ApiUser,
|
||||||
Position,
|
Position,
|
||||||
} from '../api/types';
|
} from '../api/types';
|
||||||
|
|
||||||
@@ -73,6 +83,31 @@ function relativeTime(dateLike: string) {
|
|||||||
return `${Math.floor(hours / 24)}일 전`;
|
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) {
|
function normalizeRank(rank: string | undefined) {
|
||||||
switch (rank) {
|
switch (rank) {
|
||||||
case 'I':
|
case 'I':
|
||||||
@@ -738,6 +773,7 @@ export default function AuctionPage() {
|
|||||||
: {
|
: {
|
||||||
teamIndex: captainTeamIndex,
|
teamIndex: captainTeamIndex,
|
||||||
};
|
};
|
||||||
|
const chatSenderLabel = resolveChatSenderLabel(currentUser, captainRole);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (auctionState?.currentPlayer) {
|
if (auctionState?.currentPlayer) {
|
||||||
@@ -1073,9 +1109,35 @@ export default function AuctionPage() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<aside className="hidden xl:block">
|
<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>
|
</aside>
|
||||||
</div>
|
</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>
|
</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 (
|
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="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 className="text-[10px] font-bold uppercase tracking-wider text-base-content/35">
|
||||||
채팅
|
채팅
|
||||||
</div>
|
</div>
|
||||||
<span className="text-[10px] text-base-content/30">
|
<span
|
||||||
곧 활성화됩니다
|
className={`text-[10px] ${
|
||||||
|
isConnected ? 'text-green-500' : 'text-base-content/30'
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{statusLabel}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</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>
|
</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
|
<textarea
|
||||||
disabled
|
value={draft}
|
||||||
|
onChange={(event) => setDraft(event.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
disabled={!isConnected}
|
||||||
|
maxLength={300}
|
||||||
placeholder="메시지를 입력하세요"
|
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}
|
rows={2}
|
||||||
|
aria-label="경매 채팅 메시지"
|
||||||
/>
|
/>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="submit"
|
||||||
disabled
|
disabled={!canSend}
|
||||||
className="btn btn-primary btn-sm w-full text-[11px] opacity-50"
|
className="btn btn-primary btn-sm w-full text-[11px]"
|
||||||
>
|
>
|
||||||
|
<SendHorizontal className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
전송
|
전송
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user