Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8d741ef9a7 | ||
|
|
23a0a3f8dd | ||
|
|
e349684523 | ||
|
|
9d7c888b0a | ||
|
|
5882585f69 | ||
|
|
2d8027cb16 | ||
|
|
fbf22284e8 | ||
|
|
6efbd50db7 | ||
|
|
3f68997b9a | ||
|
|
be4de61bb7 | ||
|
|
6c582ba3cf | ||
|
|
9064340584 |
No files matched your search
@@ -26,6 +26,7 @@ website/LICENSE
|
||||
!design-qa.md
|
||||
!docs/specs/home-banner-production.md
|
||||
!docs/specs/match-status-and-result-presentation.md
|
||||
!docs/specs/information-visible-ui.md
|
||||
!docs/ux-audit-2026-11-10/06-ui-improvement-review.md
|
||||
!docs/ux-audit-2026-11-10/07-visual-design-review.md
|
||||
/tmp/
|
||||
|
||||
@@ -72,6 +72,19 @@ executable path. The runner starts an isolated replica set on a random loopback
|
||||
port, uses a temporary database directory, and removes it after the tests. It
|
||||
does not use the application's database connection settings.
|
||||
|
||||
## Temporary auction role selection
|
||||
|
||||
Until captain accounts are issued, bids use the team selected in the auction UI.
|
||||
By default, both WebSocket and HTTP bids accept guests and signed-in users without
|
||||
checking whether the user is that team's captain. Team existence, bid amounts,
|
||||
remaining points, roster limits, deadlines and round consistency are still checked.
|
||||
Bid history continues to identify the selected team's captain, so it is not proof
|
||||
of the account that submitted a bid in this temporary mode.
|
||||
|
||||
After issuing accounts, set `AUCTION_REQUIRE_CAPTAIN_AUTH=true` in the API
|
||||
environment (or `project.env`) and restart the API to require a signed-in captain
|
||||
for the selected team on all bid paths. Unset or `false` keeps temporary mode.
|
||||
|
||||
## Auction durability
|
||||
|
||||
Accepted Redis bids now enter `auction:bidArchivePayloads` and
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// @ts-check
|
||||
import eslint from '@eslint/js';
|
||||
import { defineConfig } from 'eslint/config';
|
||||
import eslintPluginPrettierRecommended from 'eslint-plugin-prettier/recommended';
|
||||
import globals from 'globals';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
export default tseslint.config(
|
||||
export default defineConfig(
|
||||
{
|
||||
ignores: ['eslint.config.mjs'],
|
||||
},
|
||||
|
||||
@@ -35,19 +35,20 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@lolympus/contracts": "workspace:*",
|
||||
"@nats-io/jetstream": "^3.4.0",
|
||||
"@nats-io/transport-node": "^3.4.0",
|
||||
"@nestjs/common": "^11.1.28",
|
||||
"@nestjs/config": "^4.0.4",
|
||||
"@nestjs/core": "^11.1.28",
|
||||
"@nestjs/platform-express": "^11.1.28",
|
||||
"@nestjs/platform-socket.io": "^11.1.28",
|
||||
"@nestjs/swagger": "^11.4.6",
|
||||
"@nestjs/swagger": "^11.4.8",
|
||||
"@nestjs/websockets": "^11.1.28",
|
||||
"@socket.io/redis-adapter": "^8.3.0",
|
||||
"class-transformer": "^0.5.1",
|
||||
"class-validator": "^0.15.1",
|
||||
"jose": "^6.2.2",
|
||||
"mongoose": "9.4.1",
|
||||
"nats": "^2.29.3",
|
||||
"mongoose": "9.12.1",
|
||||
"newrelic": "^14.3.3",
|
||||
"redis": "^5.12.1",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
@@ -56,8 +57,7 @@
|
||||
"temporal-polyfill": "^0.3.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/eslintrc": "^3.2.0",
|
||||
"@eslint/js": "^9.18.0",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@nestjs/cli": "^11.0.0",
|
||||
"@nestjs/schematics": "^11.0.0",
|
||||
"@nestjs/testing": "^11.0.1",
|
||||
@@ -65,7 +65,7 @@
|
||||
"@types/jest": "^30.0.0",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/supertest": "^7.0.0",
|
||||
"eslint": "^9.18.0",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint-config-prettier": "^10.0.1",
|
||||
"eslint-plugin-prettier": "^5.2.2",
|
||||
"globals": "^17.0.0",
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* 계정 지급 전에는 화면에서 선택한 팀으로 입찰하는 임시 운영 모드가 기본이다.
|
||||
* 계정 지급 후 AUCTION_REQUIRE_CAPTAIN_AUTH=true로 로그인·팀장 검증을 복구한다.
|
||||
*/
|
||||
export function isAuctionCaptainAuthRequired(): boolean {
|
||||
return (
|
||||
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH?.trim().toLowerCase() === 'true'
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
import mongoose from 'mongoose';
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
jest.mock('../auth/jwt.service', () => ({ JwtService: class JwtService {} }));
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
|
||||
function setup() {
|
||||
const appendChatMessage = jest.fn();
|
||||
const gateway = new AuctionGateway(
|
||||
{ appendChatMessage } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const broadcast = jest.fn();
|
||||
const to = jest.fn().mockReturnValue({ emit: broadcast });
|
||||
(gateway as unknown as { server: unknown }).server = {
|
||||
to,
|
||||
};
|
||||
const socket = {
|
||||
data: {
|
||||
matchId: new mongoose.Types.ObjectId().toString(),
|
||||
user: {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
role: 'admin',
|
||||
riotAccounts: [],
|
||||
kakaoTalkNickname: '운영자',
|
||||
},
|
||||
},
|
||||
emit: jest.fn(),
|
||||
};
|
||||
return { gateway, appendChatMessage, broadcast, socket, to };
|
||||
}
|
||||
|
||||
describe('Auction chat delivery', () => {
|
||||
const payload = {
|
||||
message: '준비해 주세요',
|
||||
clientMessageId: '0589e8a4-bccd-4ccd-a3ae-28f117401e79',
|
||||
};
|
||||
it('acknowledges only after saving and assigns the operator role from the socket user', async () => {
|
||||
const { gateway, appendChatMessage, broadcast, socket } = setup();
|
||||
const message = { id: 'saved', ...payload, sentAt: new Date() };
|
||||
let finish!: (result: unknown) => void;
|
||||
appendChatMessage.mockReturnValue(
|
||||
new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
}),
|
||||
);
|
||||
const ack = jest.fn();
|
||||
const pending = gateway.handleChatMessage(socket as never, payload, ack);
|
||||
expect(ack).not.toHaveBeenCalled();
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
finish({ message, created: true });
|
||||
await pending;
|
||||
expect(appendChatMessage).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
clientMessageId: payload.clientMessageId,
|
||||
senderRole: 'operator',
|
||||
displayName: '운영자',
|
||||
}),
|
||||
);
|
||||
expect(ack).toHaveBeenCalledWith({
|
||||
ok: true,
|
||||
message: expect.objectContaining({ id: 'saved' }),
|
||||
});
|
||||
expect(broadcast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('acknowledges a retry without broadcasting a duplicate', async () => {
|
||||
const { gateway, appendChatMessage, broadcast, socket } = setup();
|
||||
appendChatMessage.mockResolvedValue({
|
||||
message: { id: 'saved' },
|
||||
created: false,
|
||||
});
|
||||
const ack = jest.fn();
|
||||
await gateway.handleChatMessage(socket as never, payload, ack);
|
||||
expect(ack).toHaveBeenCalledWith({ ok: true, message: { id: 'saved' } });
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns rejection to the requesting composer without reporting success', async () => {
|
||||
const { gateway, appendChatMessage, broadcast, socket } = setup();
|
||||
appendChatMessage.mockRejectedValue(
|
||||
new BadRequestException('Chat message is required.'),
|
||||
);
|
||||
const ack = jest.fn();
|
||||
await gateway.handleChatMessage(socket as never, payload, ack);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ok: false,
|
||||
message: 'Chat message is required.',
|
||||
}),
|
||||
);
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Auction live reactions', () => {
|
||||
it('broadcasts to the joined room with the server-resolved name, without saving a chat message', () => {
|
||||
const { gateway, appendChatMessage, broadcast, socket, to } = setup();
|
||||
const ack = jest.fn();
|
||||
gateway.handleChatReaction(socket as never, { kind: 'clap' }, ack);
|
||||
expect(to).toHaveBeenCalledWith(socket.data.matchId);
|
||||
expect(broadcast).toHaveBeenCalledWith(
|
||||
'chat-reaction',
|
||||
expect.objectContaining({
|
||||
id: expect.any(String),
|
||||
kind: 'clap',
|
||||
displayName: '운영자',
|
||||
userId: socket.data.user._id.toString(),
|
||||
}),
|
||||
);
|
||||
expect(ack).toHaveBeenCalledWith({
|
||||
ok: true,
|
||||
reaction: broadcast.mock.calls[0][1],
|
||||
});
|
||||
expect(appendChatMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unjoined clients and arbitrary reaction values', () => {
|
||||
const { gateway, broadcast, socket } = setup();
|
||||
const ack = jest.fn();
|
||||
gateway.handleChatReaction({ data: {} } as never, { kind: 'heart' }, ack);
|
||||
expect(ack).toHaveBeenLastCalledWith({ ok: false, code: 'NOT_JOINED' });
|
||||
for (const kind of ['__proto__', 'not-supported', 1, null]) {
|
||||
gateway.handleChatReaction(socket as never, { kind }, ack);
|
||||
expect(ack).toHaveBeenLastCalledWith({
|
||||
ok: false,
|
||||
code: 'INVALID_REACTION',
|
||||
});
|
||||
}
|
||||
expect(broadcast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('throttles bursts, then accepts the next reaction after the interval', () => {
|
||||
const { gateway, broadcast, socket } = setup();
|
||||
const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||
const ack = jest.fn();
|
||||
try {
|
||||
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
|
||||
gateway.handleChatReaction(socket as never, { kind: 'heart' }, ack);
|
||||
expect(ack).toHaveBeenLastCalledWith({
|
||||
ok: false,
|
||||
code: 'REACTION_RATE_LIMITED',
|
||||
});
|
||||
expect(broadcast).toHaveBeenCalledTimes(1);
|
||||
clock.mockReturnValue(1400);
|
||||
gateway.handleChatReaction(socket as never, { kind: 'celebrate' }, ack);
|
||||
expect(broadcast).toHaveBeenCalledTimes(2);
|
||||
} finally {
|
||||
clock.mockRestore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -233,6 +233,56 @@ describe('auction durability projection helpers', () => {
|
||||
expect(session.endSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('notifies history only after commit, including when state rebroadcast is disabled', async () => {
|
||||
let finishCommit!: () => void;
|
||||
const session = {
|
||||
startTransaction: jest.fn(),
|
||||
commitTransaction: jest.fn().mockImplementation(
|
||||
() =>
|
||||
new Promise<void>((resolve) => {
|
||||
finishCommit = resolve;
|
||||
}),
|
||||
),
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const updateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ upsertedCount: 1 }),
|
||||
});
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: async () => session,
|
||||
getModel: async () => ({ updateOne }),
|
||||
} as never,
|
||||
{} as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
const pending = scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
shouldBroadcastState: false,
|
||||
});
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(session.commitTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
|
||||
finishCommit();
|
||||
await pending;
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
|
||||
matchId: 'match-1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
});
|
||||
session.commitTransaction.mockRejectedValueOnce(new Error('commit failed'));
|
||||
await expect(scheduler.applyDurabilityPayload(payload)).rejects.toThrow(
|
||||
'commit failed',
|
||||
);
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledTimes(1);
|
||||
expect(session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('broadcasts latest Redis state when durability payload requests it', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
@@ -265,7 +315,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -315,7 +365,7 @@ describe('auction durability projection helpers', () => {
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastState } as never,
|
||||
{ broadcastState, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
{ readAuctionStateView } as never,
|
||||
);
|
||||
|
||||
@@ -407,60 +457,71 @@ describe('auction durability projection helpers', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('skips destructive history mutation for stale payloads', async () => {
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest.fn().mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
it.each(['life-1', 'new-life'])(
|
||||
'skips stale history changes and notifications for current lifecycle %s',
|
||||
async (auctionLifecycleId) => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const session = {
|
||||
abortTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
commitTransaction: jest.fn().mockResolvedValue(undefined),
|
||||
endSession: jest.fn().mockResolvedValue(undefined),
|
||||
startTransaction: jest.fn(),
|
||||
};
|
||||
const historyDeleteMany = jest.fn();
|
||||
const historyUpdateOne = jest.fn();
|
||||
const auctionUpdateOne = jest.fn().mockReturnValue({
|
||||
exec: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ matchedCount: 0, modifiedCount: 0 }),
|
||||
});
|
||||
const projectionExec = jest.fn().mockResolvedValue({
|
||||
auctionLifecycleId,
|
||||
revision: 10,
|
||||
});
|
||||
const auctionFindById = jest.fn().mockReturnValue({
|
||||
select: jest.fn().mockReturnValue({
|
||||
session: jest.fn().mockReturnValue({
|
||||
lean: jest.fn().mockReturnValue({ exec: projectionExec }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
);
|
||||
});
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
{
|
||||
createSession: jest.fn().mockResolvedValue(session),
|
||||
getModel: jest.fn((name: string) => {
|
||||
if (name === 'auctionHistory') {
|
||||
return {
|
||||
deleteMany: historyDeleteMany,
|
||||
updateOne: historyUpdateOne,
|
||||
};
|
||||
}
|
||||
if (name === 'auction') {
|
||||
return { findById: auctionFindById, updateOne: auctionUpdateOne };
|
||||
}
|
||||
return { updateOne: jest.fn() };
|
||||
}),
|
||||
} as never,
|
||||
{ raw: jest.fn() } as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
await scheduler.applyDurabilityPayload({
|
||||
...payload,
|
||||
historyMutation: {
|
||||
targetHistorySequence: 2,
|
||||
type: 'deleteAfterSequenceAndAppendUndo',
|
||||
},
|
||||
});
|
||||
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(historyDeleteMany).not.toHaveBeenCalled();
|
||||
expect(historyUpdateOne).not.toHaveBeenCalled();
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(broadcastHistoryUpdated).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it('recovers stale append payloads as history-only records', async () => {
|
||||
const session = {
|
||||
@@ -597,6 +658,7 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
it('clears stale append payloads after history-only recovery', async () => {
|
||||
const broadcastHistoryUpdated = jest.fn();
|
||||
const sendCommand = jest
|
||||
.fn()
|
||||
.mockResolvedValueOnce(['payload-1'])
|
||||
@@ -653,6 +715,10 @@ describe('auction durability projection helpers', () => {
|
||||
getCurrentRedisTimestampMS: jest.fn().mockResolvedValue(1000),
|
||||
raw: jest.fn().mockReturnValue({ sendCommand }),
|
||||
} as never,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
{ broadcastHistoryUpdated } as never,
|
||||
);
|
||||
|
||||
await expect(scheduler.processDueDurabilityPayloads(10)).resolves.toEqual({
|
||||
@@ -662,6 +728,11 @@ describe('auction durability projection helpers', () => {
|
||||
});
|
||||
|
||||
expect(historyUpdateOne).toHaveBeenCalledTimes(1);
|
||||
expect(broadcastHistoryUpdated).toHaveBeenCalledWith({
|
||||
matchId: 'match-1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
auctionStateTransitionId: 'transition-1',
|
||||
});
|
||||
expect(auctionUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sideEffectUpdateOne).not.toHaveBeenCalled();
|
||||
expect(sendCommand).toHaveBeenNthCalledWith(3, [
|
||||
@@ -1006,7 +1077,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(completePayload);
|
||||
@@ -1203,7 +1274,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ reserveForMatch } as never,
|
||||
{ scheduleInitialPoll } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await expect(
|
||||
@@ -1332,7 +1403,7 @@ describe('auction durability projection helpers', () => {
|
||||
{ releaseFromMatch } as never,
|
||||
{ cancelPolling } as never,
|
||||
{ mirrorMatchSideEffectStatus } as never,
|
||||
{ broadcastMatchSideEffect } as never,
|
||||
{ broadcastMatchSideEffect, broadcastHistoryUpdated: jest.fn() } as never,
|
||||
);
|
||||
|
||||
await scheduler.applyDurabilityPayload(resetPayload);
|
||||
|
||||
@@ -356,6 +356,15 @@ export class AuctionDurabilityScheduler
|
||||
if (session) await session.endSession();
|
||||
}
|
||||
|
||||
if (shouldApplyHistoryMutation) {
|
||||
// This is independent of the primary state broadcast. HTTP reads on every
|
||||
// node can see the committed history before clients are notified.
|
||||
this.auctionEventBusService?.broadcastHistoryUpdated({
|
||||
matchId: String(payload.matchId),
|
||||
auctionLifecycleId: payload.auctionLifecycleId,
|
||||
auctionStateTransitionId: payload.auctionStateTransitionId,
|
||||
});
|
||||
}
|
||||
await this.broadcastLatestRedisAuctionStateIfRequested(payload);
|
||||
|
||||
if (sideEffectMutation && shouldApplySideEffects) {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import type { AuctionHistoryUpdatedEvent } from '@lolympus/contracts';
|
||||
import type { AuctionStateResponse } from './auction.service';
|
||||
import type { MatchSideEffectDelta } from './auction-side-effect.service';
|
||||
import { serializeRealtimeAuction } from './auction-realtime-serializer';
|
||||
@@ -25,6 +26,10 @@ export class AuctionEventBusService {
|
||||
.emit('state', serializeRealtimeAuction(state));
|
||||
}
|
||||
|
||||
public broadcastHistoryUpdated(event: AuctionHistoryUpdatedEvent): void {
|
||||
this.auctionNamespace?.to(event.matchId).emit('history-updated', event);
|
||||
}
|
||||
|
||||
public broadcastReset(matchId: string, auctionLifecycleId: string): void {
|
||||
this.auctionNamespace
|
||||
?.to(matchId)
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import 'reflect-metadata';
|
||||
import mongoose from 'mongoose';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import { METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED } from '../auth/allow-public-access.decorator';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
|
||||
jest.mock('../auth/jwt.service', () => ({
|
||||
JwtService: class JwtService {},
|
||||
}));
|
||||
|
||||
import { AuctionController } from './auction.controller';
|
||||
|
||||
describe('AuctionController bid authentication', () => {
|
||||
beforeEach(() => {
|
||||
jest.replaceProperty(process, 'env', { ...process.env });
|
||||
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
|
||||
});
|
||||
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
it('allows HTTP guests to reach the configurable bid checks', () => {
|
||||
const handler = AuctionController.prototype.placeBid;
|
||||
expect(
|
||||
Reflect.getMetadata(METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED, handler),
|
||||
).toBe(true);
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, handler)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([undefined, 'false', 'true'])(
|
||||
'handles HTTP guests with captain auth=%s',
|
||||
async (auth) => {
|
||||
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
|
||||
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
|
||||
const controller = new AuctionController(
|
||||
{ placeBid } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const result = controller.placeBid(
|
||||
undefined,
|
||||
new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
{
|
||||
bidderTeamIndex: 2,
|
||||
bidPointAmount: 20,
|
||||
},
|
||||
);
|
||||
if (auth === 'true') {
|
||||
await expect(result).rejects.toThrow(
|
||||
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
|
||||
);
|
||||
expect(placeBid).not.toHaveBeenCalled();
|
||||
} else {
|
||||
await expect(result).resolves.toEqual({ revision: 2 });
|
||||
expect(placeBid).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
matchId,
|
||||
teamIndex: 2,
|
||||
amount: 20,
|
||||
bidderUserId: undefined,
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it('passes the signed-in user to service checks and restores community validation in strict mode', async () => {
|
||||
const placeBid = jest.fn().mockResolvedValue({ revision: 2 });
|
||||
const controller = new AuctionController(
|
||||
{ placeBid } as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
);
|
||||
const user = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
communityId: new mongoose.Types.ObjectId(),
|
||||
} as UserDocument;
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const body = { bidderTeamIndex: 2, bidPointAmount: 20 };
|
||||
await controller.placeBid(
|
||||
user,
|
||||
new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
body,
|
||||
);
|
||||
expect(placeBid).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ bidderUserId: user._id }),
|
||||
);
|
||||
|
||||
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
|
||||
await expect(
|
||||
controller.placeBid(user, new mongoose.Types.ObjectId(), matchId, body),
|
||||
).rejects.toThrow('Different community.');
|
||||
expect(placeBid).toHaveBeenCalledTimes(1);
|
||||
await expect(
|
||||
controller.placeBid(user, user.communityId, matchId, body),
|
||||
).resolves.toEqual({ revision: 2 });
|
||||
expect(placeBid).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
Body,
|
||||
Controller,
|
||||
Delete,
|
||||
ForbiddenException,
|
||||
Get,
|
||||
HttpCode,
|
||||
HttpStatus,
|
||||
@@ -19,6 +20,7 @@ import { RolesGuard } from '../auth/roles.guard';
|
||||
import { ParseObjectIdPipe } from '../common/parse-object-id.pipe';
|
||||
import type { UserDocument } from '../global/database/schema';
|
||||
import { AuctionService } from './auction.service';
|
||||
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
import { AuctionBidArchiveService } from './auction-bid-archive.service';
|
||||
import {
|
||||
@@ -106,20 +108,26 @@ export class AuctionController {
|
||||
}
|
||||
|
||||
@Post('bids')
|
||||
@Roles('admin', 'owner', 'member')
|
||||
@UseGuards(RolesGuard)
|
||||
@AllowPublicAccess()
|
||||
@HttpCode(HttpStatus.OK)
|
||||
public async placeBid(
|
||||
@CurrentUser() currentUser: UserDocument,
|
||||
@CurrentUser() currentUser: UserDocument | undefined,
|
||||
@Param('communityId', ParseObjectIdPipe)
|
||||
communityId: mongoose.Types.ObjectId,
|
||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||
@Body() body: PlaceBidDto,
|
||||
) {
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
if (isAuctionCaptainAuthRequired()) {
|
||||
if (!currentUser) {
|
||||
throw new ForbiddenException(
|
||||
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
|
||||
);
|
||||
}
|
||||
this.assertSameCommunity(currentUser, communityId);
|
||||
}
|
||||
return this.auctionService.placeBid({
|
||||
matchId,
|
||||
bidderUserId: currentUser._id,
|
||||
bidderUserId: currentUser?._id,
|
||||
teamIndex: body.bidderTeamIndex,
|
||||
amount: body.bidPointAmount,
|
||||
bidRequestId: body.bidRequestId,
|
||||
|
||||
@@ -8,6 +8,15 @@ jest.mock('../auth/jwt.service', () => ({
|
||||
import { AuctionGateway } from './auction.gateway';
|
||||
|
||||
describe('AuctionGateway', () => {
|
||||
beforeEach(() => {
|
||||
jest.replaceProperty(process, 'env', { ...process.env });
|
||||
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('signals pending initial state so the client can retry privately after recovery', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const gateway = new AuctionGateway(
|
||||
@@ -28,7 +37,11 @@ describe('AuctionGateway', () => {
|
||||
{} as never,
|
||||
);
|
||||
const socket = { data: { matchId }, join: jest.fn(), emit: jest.fn() };
|
||||
await gateway.handleJoin(socket as never, { matchId });
|
||||
const ack = jest.fn();
|
||||
await gateway.handleJoin(socket as never, { matchId }, ack);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ok: false, code: 'AUCTION_STATE_RECOVERING' }),
|
||||
);
|
||||
expect(socket.emit).toHaveBeenCalledTimes(1);
|
||||
expect(socket.emit).toHaveBeenCalledWith('state-pending', {
|
||||
retryAfterMS: 500,
|
||||
@@ -83,9 +96,12 @@ describe('AuctionGateway', () => {
|
||||
function createGateway(params?: {
|
||||
getCurrentRedisTimestampMS?: jest.Mock;
|
||||
placeBidDelta?: jest.Mock;
|
||||
getRealtimeIdentity?: jest.Mock;
|
||||
}) {
|
||||
const auctionService = {
|
||||
placeBidDelta: params?.placeBidDelta ?? jest.fn(),
|
||||
getRealtimeIdentity:
|
||||
params?.getRealtimeIdentity ?? jest.fn().mockResolvedValue(null),
|
||||
};
|
||||
const auctionRedisService = {
|
||||
getCurrentRedisTimestampMS:
|
||||
@@ -114,7 +130,8 @@ describe('AuctionGateway', () => {
|
||||
};
|
||||
}
|
||||
|
||||
it('requires an authenticated user before forwarding a bid', async () => {
|
||||
it('requires an authenticated user when captain authentication is enabled', async () => {
|
||||
process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = 'true';
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const { gateway, auctionService } = createGateway();
|
||||
const ack = jest.fn();
|
||||
@@ -131,6 +148,49 @@ describe('AuctionGateway', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it.each([undefined, bidderUserId])(
|
||||
'accepts the selected team in temporary mode for user %s',
|
||||
async (userId) => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const placeBidDelta = jest.fn().mockResolvedValue({
|
||||
auctionBidHistoryEntry: {
|
||||
bidderTeamIndex: 2,
|
||||
bidderUserId: new mongoose.Types.ObjectId().toString(),
|
||||
bidPointAmount: 120,
|
||||
bidPlacedAtTimestampMS: 1780000000000,
|
||||
},
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
currentHighestBidPointAmount: 120,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
revision: 9,
|
||||
});
|
||||
const { gateway, emit } = createGateway({ placeBidDelta });
|
||||
const ack = jest.fn();
|
||||
|
||||
await gateway.handleBid(
|
||||
{
|
||||
data: { matchId, user: userId ? { _id: userId } : undefined },
|
||||
emit: jest.fn(),
|
||||
} as never,
|
||||
{ bidderTeamIndex: 2, bidPointAmount: 120 },
|
||||
ack,
|
||||
);
|
||||
|
||||
expect(placeBidDelta).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
teamIndex: 2,
|
||||
amount: 120,
|
||||
bidderUserId: userId,
|
||||
}),
|
||||
);
|
||||
expect(ack).toHaveBeenCalledWith(expect.objectContaining({ ok: true }));
|
||||
expect(emit).toHaveBeenCalledWith(
|
||||
'bid',
|
||||
expect.objectContaining({ currentHighestBidderTeamIndex: 2 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('broadcasts a bid delta and acknowledges the matching bid request', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const auctionBidHistoryEntry = {
|
||||
@@ -334,6 +394,46 @@ describe('AuctionGateway', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('adds lightweight auction identity to heartbeats for the joined match', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const identity = {
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 11,
|
||||
matchSideEffectRevision: 3,
|
||||
};
|
||||
const getRealtimeIdentity = jest.fn().mockResolvedValue(identity);
|
||||
const { gateway } = createGateway({ getRealtimeIdentity });
|
||||
const ack = jest.fn();
|
||||
await gateway.handleTimeSync({ sequence: 1 }, ack, {
|
||||
data: { matchId },
|
||||
} as never);
|
||||
expect(getRealtimeIdentity).toHaveBeenCalledWith(matchId);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ ok: true, auctionState: identity }),
|
||||
);
|
||||
});
|
||||
|
||||
it('continues clock sync when the optional auction identity read fails', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
const { gateway } = createGateway({
|
||||
getRealtimeIdentity: jest
|
||||
.fn()
|
||||
.mockRejectedValue(new Error('identity unavailable')),
|
||||
});
|
||||
const ack = jest.fn();
|
||||
await gateway.handleTimeSync({ sequence: 2 }, ack, {
|
||||
data: { matchId },
|
||||
} as never);
|
||||
expect(ack).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
ok: true,
|
||||
sequence: 2,
|
||||
currentServerTimestampMS: 1780000000000,
|
||||
auctionStateUnavailable: true,
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('rate limits excessive bid requests from the same socket', async () => {
|
||||
jest.spyOn(Date, 'now').mockReturnValue(1780000000000);
|
||||
const matchId = new mongoose.Types.ObjectId().toString();
|
||||
|
||||
@@ -14,6 +14,11 @@ import {
|
||||
import mongoose from 'mongoose';
|
||||
import type { JWTPayload } from 'jose';
|
||||
import type { DefaultEventsMap, Namespace, Socket } from 'socket.io';
|
||||
import type {
|
||||
AuctionReactionEvent,
|
||||
AuctionReactionKind,
|
||||
AuctionReactionReply,
|
||||
} from '@lolympus/contracts';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { IdentityService } from '../auth/identity.service';
|
||||
import { JwtService } from '../auth/jwt.service';
|
||||
@@ -31,6 +36,7 @@ import type {
|
||||
AuctionStateResponse,
|
||||
} from './auction.service';
|
||||
import { AuctionEventBusService } from './auction-event-bus.service';
|
||||
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
|
||||
import {
|
||||
isAuctionResyncRecommended,
|
||||
resolveAuctionRejectionReason,
|
||||
@@ -72,6 +78,7 @@ type AuctionActionPayload = Omit<SoldPayload, 'assignedPosition'>;
|
||||
interface ChatMessagePayload {
|
||||
message?: string;
|
||||
displayName?: string;
|
||||
clientMessageId?: string;
|
||||
}
|
||||
|
||||
interface BidRateLimitState {
|
||||
@@ -80,6 +87,7 @@ interface BidRateLimitState {
|
||||
}
|
||||
|
||||
interface AuctionSocketData {
|
||||
auctionReactionSentAt?: number;
|
||||
auctionResyncAtTimestampMS?: number;
|
||||
auctionResyncInProgress?: boolean;
|
||||
auctionBidRateLimit?: BidRateLimitState;
|
||||
@@ -97,6 +105,24 @@ type AuctionSocket = Socket<
|
||||
>;
|
||||
|
||||
const BID_RATE_LIMIT_WINDOW_MS = 1000;
|
||||
const REACTION_KINDS: Record<AuctionReactionKind, true> = {
|
||||
'thumbs-up': true,
|
||||
heart: true,
|
||||
clap: true,
|
||||
laugh: true,
|
||||
wow: true,
|
||||
sad: true,
|
||||
fire: true,
|
||||
celebrate: true,
|
||||
eyes: true,
|
||||
thinking: true,
|
||||
'skull-crossbones': true,
|
||||
poop: true,
|
||||
pray: true,
|
||||
'sweat-smile': true,
|
||||
money: true,
|
||||
trophy: true,
|
||||
};
|
||||
const BID_RATE_LIMIT_MAX_REQUESTS_PER_WINDOW = 8;
|
||||
const BID_RATE_LIMIT_REJECTION_CODE = 'BID_RATE_LIMITED';
|
||||
const BID_RATE_LIMIT_REJECTION_MESSAGE =
|
||||
@@ -154,9 +180,11 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleJoin(
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: JoinAuctionPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
if (!payload?.matchId || !mongoose.isValidObjectId(payload.matchId)) {
|
||||
this.emitError(socket, 'Invalid matchId.');
|
||||
ack?.({ ok: false, code: 'INVALID_MATCH_ID' });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -175,8 +203,10 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
);
|
||||
this.emitChatHistory(socket, auction);
|
||||
socket.emit('state', serializeRealtimeAuction(auctionState));
|
||||
ack?.({ ok: true });
|
||||
} catch (error) {
|
||||
const rejection = this.resolveErrorPayload(error);
|
||||
ack?.({ ...rejection, ok: false });
|
||||
if (rejection.code === 'AUCTION_STATE_RECOVERING') {
|
||||
socket.emit('state-pending', { retryAfterMS: 500 });
|
||||
} else {
|
||||
@@ -250,7 +280,7 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
|
||||
try {
|
||||
const bidderUserId = this.resolveSocketUserId(socket);
|
||||
if (!bidderUserId)
|
||||
if (isAuctionCaptainAuthRequired() && !bidderUserId)
|
||||
throw new ForbiddenException(
|
||||
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
|
||||
);
|
||||
@@ -321,14 +351,27 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleTimeSync(
|
||||
@MessageBody() payload: TimeSyncPayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
@ConnectedSocket() socket?: AuctionSocket,
|
||||
) {
|
||||
const receivedAtMonotonicMS = performance.now();
|
||||
try {
|
||||
const currentServerTimestampMS =
|
||||
await this.auctionRedisService.getCurrentRedisTimestampMS();
|
||||
const [currentServerTimestampMS, auctionState] = await Promise.all([
|
||||
this.auctionRedisService.getCurrentRedisTimestampMS(),
|
||||
socket?.data.matchId
|
||||
? this.auctionService
|
||||
.getRealtimeIdentity(socket.data.matchId)
|
||||
.catch(() => undefined)
|
||||
: undefined,
|
||||
]);
|
||||
ack?.({
|
||||
clientSentAtTimestampMS: payload?.clientSentAtTimestampMS,
|
||||
currentServerTimestampMS,
|
||||
...(socket?.data.matchId
|
||||
? {
|
||||
auctionState,
|
||||
auctionStateUnavailable: auctionState === undefined,
|
||||
}
|
||||
: {}),
|
||||
ok: true,
|
||||
sequence: payload?.sequence,
|
||||
serverProcessingDurationMS:
|
||||
@@ -466,30 +509,82 @@ export class AuctionGateway implements OnGatewayConnection, OnGatewayInit {
|
||||
public async handleChatMessage(
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: ChatMessagePayload,
|
||||
@Ack() ack?: (response: Record<string, unknown>) => void,
|
||||
) {
|
||||
const matchId = this.requireJoinedMatchId(socket);
|
||||
if (!matchId) return;
|
||||
if (!matchId) {
|
||||
ack?.({ ok: false, message: 'Join a match room before sending events.' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof payload?.message !== 'string') {
|
||||
this.emitError(socket, 'Chat message is required.');
|
||||
ack?.({ ok: false, message: 'Chat message is required.' });
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const { message } = await this.auctionService.appendChatMessage({
|
||||
const { message, created } = await this.auctionService.appendChatMessage({
|
||||
matchId: new mongoose.Types.ObjectId(matchId),
|
||||
clientMessageId: payload.clientMessageId,
|
||||
senderRole: ['owner', 'admin'].includes(socket.data.user?.role ?? '')
|
||||
? 'operator'
|
||||
: undefined,
|
||||
userId: this.resolveSocketUserId(socket),
|
||||
displayName: this.resolveChatDisplayName(socket, payload.displayName),
|
||||
message: payload.message,
|
||||
});
|
||||
this.server
|
||||
.to(matchId)
|
||||
.emit('chat-message', this.serializeChatMessage(message));
|
||||
const serialized = this.serializeChatMessage(message);
|
||||
if (created) this.server.to(matchId).emit('chat-message', serialized);
|
||||
ack?.({ ok: true, message: serialized });
|
||||
} catch (error) {
|
||||
this.emitKnownError(socket, error);
|
||||
if (ack) ack({ ok: false, ...this.resolveErrorPayload(error) });
|
||||
else this.emitKnownError(socket, error);
|
||||
}
|
||||
}
|
||||
|
||||
@SubscribeMessage('chat-reaction')
|
||||
public handleChatReaction(
|
||||
@ConnectedSocket() socket: AuctionSocket,
|
||||
@MessageBody() payload: { kind?: unknown },
|
||||
@Ack() ack?: (response: AuctionReactionReply) => void,
|
||||
) {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) {
|
||||
ack?.({ ok: false, code: 'NOT_JOINED' });
|
||||
return;
|
||||
}
|
||||
if (
|
||||
typeof payload?.kind !== 'string' ||
|
||||
!Object.hasOwn(REACTION_KINDS, payload.kind)
|
||||
) {
|
||||
ack?.({ ok: false, code: 'INVALID_REACTION' });
|
||||
return;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (
|
||||
socket.data.auctionReactionSentAt !== undefined &&
|
||||
now - socket.data.auctionReactionSentAt < 400
|
||||
) {
|
||||
ack?.({ ok: false, code: 'REACTION_RATE_LIMITED' });
|
||||
return;
|
||||
}
|
||||
socket.data.auctionReactionSentAt = now;
|
||||
const reaction: AuctionReactionEvent = {
|
||||
id: randomUUID(),
|
||||
kind: payload.kind as AuctionReactionKind,
|
||||
displayName: Array.from(this.resolveChatDisplayName(socket))
|
||||
.slice(0, 40)
|
||||
.join(''),
|
||||
userId: this.resolveSocketUserId(socket)?.toString(),
|
||||
sentAt: now,
|
||||
};
|
||||
// The room adapter fans out to all viewers. Reactions never enter the
|
||||
// persisted message history, so reconnects do not replay old animations.
|
||||
this.server.to(matchId).emit('chat-reaction', reaction);
|
||||
ack?.({ ok: true, reaction });
|
||||
}
|
||||
|
||||
private requireJoinedMatchId(socket: AuctionSocket): string | null {
|
||||
const matchId = this.getSocketMatchId(socket);
|
||||
if (!matchId) {
|
||||
|
||||
@@ -156,6 +156,11 @@ describe('AuctionService', () => {
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.replaceProperty(process, 'env', { ...process.env });
|
||||
delete process.env.AUCTION_REQUIRE_CAPTAIN_AUTH;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.useRealTimers();
|
||||
@@ -210,8 +215,7 @@ describe('AuctionService', () => {
|
||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists auction history with a summary projection and short local cache', async () => {
|
||||
const nowSpy = jest.spyOn(Date, 'now').mockReturnValue(1000);
|
||||
it('reads committed history on every node without retaining a local cache', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const match = {
|
||||
@@ -237,7 +241,7 @@ describe('AuctionService', () => {
|
||||
const historySort = jest.fn().mockReturnValue({ limit: historyLimit });
|
||||
const historySelect = jest.fn().mockReturnValue({ sort: historySort });
|
||||
const historyFind = jest.fn().mockReturnValue({ select: historySelect });
|
||||
const { service } = createService({
|
||||
const models = {
|
||||
auctionHistory: {
|
||||
find: historyFind,
|
||||
},
|
||||
@@ -246,7 +250,9 @@ describe('AuctionService', () => {
|
||||
select: jest.fn().mockResolvedValue(match),
|
||||
}),
|
||||
},
|
||||
});
|
||||
};
|
||||
const { service } = createService(models);
|
||||
const otherNode = createService(models).service;
|
||||
|
||||
await expect(
|
||||
service.listHistory({ matchId, communityId }),
|
||||
@@ -266,7 +272,7 @@ describe('AuctionService', () => {
|
||||
]);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
|
||||
expect(historyFind).toHaveBeenCalledTimes(1);
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
expect(historySelect).toHaveBeenCalledWith({
|
||||
_id: 0,
|
||||
action: 1,
|
||||
@@ -276,9 +282,17 @@ describe('AuctionService', () => {
|
||||
expect(historySort).toHaveBeenCalledWith({ sequence: -1 });
|
||||
expect(historyLimit).toHaveBeenCalledWith(100);
|
||||
|
||||
nowSpy.mockReturnValue(3101);
|
||||
await service.listHistory({ matchId, communityId });
|
||||
expect(historyFind).toHaveBeenCalledTimes(2);
|
||||
historyExec.mockResolvedValue([
|
||||
{ action: 'undo', sequence: 5, takenAt: new Date() },
|
||||
historyRows[1],
|
||||
]);
|
||||
const [firstNodeHistory, secondNodeHistory] = await Promise.all([
|
||||
service.listHistory({ matchId, communityId }),
|
||||
otherNode.listHistory({ matchId, communityId }),
|
||||
]);
|
||||
expect(firstNodeHistory.map(({ sequence }) => sequence)).toEqual([5, 3]);
|
||||
expect(secondNodeHistory).toEqual(firstNodeHistory);
|
||||
expect(historyFind).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
|
||||
it('starts an auction without reserving tournament codes before teams are complete', async () => {
|
||||
@@ -1055,6 +1069,113 @@ describe('AuctionService', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe.each(['realtime', 'redis-fallback', 'legacy'] as const)(
|
||||
'%s bid authorization',
|
||||
(path) => {
|
||||
it.each([
|
||||
[undefined, 'guest'],
|
||||
[undefined, 'other-user'],
|
||||
['false', 'other-user'],
|
||||
['true', 'guest'],
|
||||
['true', 'other-user'],
|
||||
['true', 'captain'],
|
||||
] as const)('checks auth=%s for %s', async (auth, actor) => {
|
||||
if (auth !== undefined) process.env.AUCTION_REQUIRE_CAPTAIN_AUTH = auth;
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
const playerUserId = new mongoose.Types.ObjectId();
|
||||
const bidderUserId =
|
||||
actor === 'guest'
|
||||
? undefined
|
||||
: actor === 'captain'
|
||||
? captainUserId
|
||||
: new mongoose.Types.ObjectId();
|
||||
const team = { teamIndex: 2, captainUserId, points: 1000, members: [] };
|
||||
const auction = {
|
||||
_id: new mongoose.Types.ObjectId(),
|
||||
matchId,
|
||||
auctionEngineVersion: path === 'legacy' ? undefined : 'redis-v1',
|
||||
phase: 'bidding',
|
||||
teams: [team],
|
||||
currentBid: 0,
|
||||
bidExtensionSeconds: 5,
|
||||
bids: [],
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
toObject: () => ({ matchId, teams: [team], phase: 'bidding' }),
|
||||
};
|
||||
const {
|
||||
service,
|
||||
auctionRedisCommandService,
|
||||
auctionRedisStateReaderService,
|
||||
} = createService({
|
||||
auction: { findOne: jest.fn().mockResolvedValue(auction) },
|
||||
});
|
||||
const state = {
|
||||
auctionLifecycleId: 'life-1',
|
||||
currentBidRoundPlayerUserId: playerUserId.toString(),
|
||||
phase: 'bidding',
|
||||
revision: 2,
|
||||
auctionTeams: [
|
||||
{
|
||||
teamIndex: 2,
|
||||
captainUserId: captainUserId.toString(),
|
||||
remainingBidPointAmount: 1000,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
};
|
||||
auctionRedisStateReaderService.readAuctionStateView.mockResolvedValue(
|
||||
state,
|
||||
);
|
||||
if (path === 'realtime') {
|
||||
auctionRedisStateReaderService.readBidContext.mockResolvedValue({
|
||||
...state,
|
||||
bidderTeamCaptainUserId: captainUserId.toString(),
|
||||
});
|
||||
}
|
||||
|
||||
const result = service.placeBidDelta({
|
||||
matchId,
|
||||
teamIndex: 2,
|
||||
amount: 20,
|
||||
bidderUserId,
|
||||
bidRequestId: 'auth-mode-bid',
|
||||
});
|
||||
if (auth === 'true' && actor !== 'captain') {
|
||||
await expect(result).rejects.toThrow(
|
||||
actor === 'guest'
|
||||
? '팀장 계정으로 로그인해야 입찰할 수 있습니다.'
|
||||
: '해당 팀의 팀장만 입찰할 수 있습니다.',
|
||||
);
|
||||
expect(auctionRedisCommandService.placeBid).not.toHaveBeenCalled();
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
|
||||
await expect(result).resolves.toBeDefined();
|
||||
if (path === 'legacy') {
|
||||
expect(auction.bids).toEqual([
|
||||
expect.objectContaining({
|
||||
teamIndex: 2,
|
||||
amount: 20,
|
||||
bidderUserId: captainUserId,
|
||||
}),
|
||||
]);
|
||||
expect(auction.save).toHaveBeenCalledTimes(1);
|
||||
} else {
|
||||
expect(auctionRedisCommandService.placeBid).toHaveBeenCalledWith(
|
||||
matchId.toString(),
|
||||
expect.objectContaining({
|
||||
bidderTeamIndex: 2,
|
||||
bidPointAmount: 20,
|
||||
bidderUserId: captainUserId.toString(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it('places bids through Redis for redis-v1 auctions', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const captainUserId = new mongoose.Types.ObjectId();
|
||||
@@ -1747,9 +1868,17 @@ describe('AuctionService', () => {
|
||||
chatMessages: oldMessages,
|
||||
save: jest.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
const findOneAndUpdate = jest.fn().mockImplementation((_filter, update) => {
|
||||
auction.chatMessages = [
|
||||
...auction.chatMessages,
|
||||
...update.$push.chatMessages.$each,
|
||||
].slice(-200);
|
||||
return auction;
|
||||
});
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
findOneAndUpdate,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1770,7 +1899,54 @@ describe('AuctionService', () => {
|
||||
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);
|
||||
expect(auction.save).not.toHaveBeenCalled();
|
||||
expect(appended.created).toBe(true);
|
||||
expect(findOneAndUpdate).toHaveBeenCalledWith(
|
||||
{ matchId, 'chatMessages.id': { $ne: appended.message.id } },
|
||||
{ $push: { chatMessages: { $each: [appended.message], $slice: -200 } } },
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
});
|
||||
|
||||
it('returns the saved message on retry without appending or broadcasting it again', async () => {
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const clientMessageId = '0589e8a4-bccd-4ccd-a3ae-28f117401e79';
|
||||
const saved = {
|
||||
id: `${userId.toString()}:${clientMessageId}`,
|
||||
clientMessageId,
|
||||
userId,
|
||||
displayName: '팀장',
|
||||
message: '확인했습니다',
|
||||
sentAt: new Date(),
|
||||
};
|
||||
const findOneAndUpdate = jest.fn().mockResolvedValue(null);
|
||||
const auction = { matchId, chatMessages: [saved] };
|
||||
const { service } = createService({
|
||||
auction: {
|
||||
findOneAndUpdate,
|
||||
findOne: jest.fn().mockResolvedValue(auction),
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
service.appendChatMessage({
|
||||
matchId,
|
||||
userId,
|
||||
clientMessageId,
|
||||
message: '확인했습니다',
|
||||
}),
|
||||
).resolves.toEqual({ auction, message: saved, created: false });
|
||||
expect(findOneAndUpdate.mock.calls[0][0]['chatMessages.id']).toEqual({
|
||||
$ne: saved.id,
|
||||
});
|
||||
await expect(
|
||||
service.appendChatMessage({
|
||||
matchId,
|
||||
userId,
|
||||
clientMessageId,
|
||||
message: '다른 메시지',
|
||||
}),
|
||||
).rejects.toThrow('Chat message conflicts with an earlier request.');
|
||||
});
|
||||
|
||||
it('rejects blank and overly long chat messages', async () => {
|
||||
|
||||
@@ -10,12 +10,14 @@ import {
|
||||
Optional,
|
||||
} from '@nestjs/common';
|
||||
import { randomUUID } from 'crypto';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import {
|
||||
AuctionLifecycleLock,
|
||||
AuctionLifecycleBusyError,
|
||||
} from './auction-lifecycle-lock';
|
||||
import { AUCTION_OPTIONAL_PROJECTION_FIELDS } from './auction-projection';
|
||||
import { AuctionEventBusService } from './auction-event-bus.service';
|
||||
import { isAuctionCaptainAuthRequired } from './auction-bid-auth';
|
||||
import { performance } from 'perf_hooks';
|
||||
import mongoose from 'mongoose';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
@@ -68,8 +70,6 @@ const AUCTION_MAX_STORED_ACTION_REQUEST_RESULT_COUNT = 500;
|
||||
const AUCTION_ACTION_REQUEST_REPLAY_WINDOW_MS = 5 * 60 * 1000;
|
||||
const AUCTION_ACTION_REQUEST_LEASE_DURATION_MS = 15 * 1000;
|
||||
const AUCTION_HISTORY_LIST_LIMIT = 100;
|
||||
const AUCTION_HISTORY_LIST_CACHE_TTL_MS = 2 * 1000;
|
||||
const AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES = 256;
|
||||
|
||||
interface StartAuctionParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
@@ -142,6 +142,8 @@ type RedisActionRequestContext =
|
||||
|
||||
interface AppendChatMessageParams {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
clientMessageId?: string;
|
||||
senderRole?: 'operator';
|
||||
userId?: mongoose.Types.ObjectId;
|
||||
displayName?: string;
|
||||
message: string;
|
||||
@@ -160,11 +162,6 @@ interface AuctionHistorySummaryRecord {
|
||||
takenAt: Date;
|
||||
}
|
||||
|
||||
interface AuctionHistoryListCacheEntry {
|
||||
entries: AuctionHistoryView[];
|
||||
expiresAtTimestampMS: number;
|
||||
}
|
||||
|
||||
export type AuctionStateResponse = AuctionDocument | Record<string, unknown>;
|
||||
|
||||
export interface AuctionBidDeltaResponse {
|
||||
@@ -208,10 +205,6 @@ function isMongoDuplicateKeyError(error: unknown): boolean {
|
||||
@Injectable()
|
||||
export class AuctionService {
|
||||
private readonly logger = new Logger(AuctionService.name);
|
||||
private readonly auctionHistoryListCache = new Map<
|
||||
string,
|
||||
AuctionHistoryListCacheEntry
|
||||
>();
|
||||
|
||||
constructor(
|
||||
private readonly connectionService: ConnectionService,
|
||||
@@ -576,6 +569,12 @@ export class AuctionService {
|
||||
}
|
||||
}
|
||||
|
||||
public getRealtimeIdentity(
|
||||
matchId: string,
|
||||
): Promise<AuctionStateIdentity | null> {
|
||||
return this.auctionRedisStateReaderService.readLiveStateIdentity(matchId);
|
||||
}
|
||||
|
||||
private async getStateByMatchIdOnce(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
): Promise<AuctionStateResponse> {
|
||||
@@ -666,26 +665,57 @@ export class AuctionService {
|
||||
public async appendChatMessage(params: AppendChatMessageParams): Promise<{
|
||||
auction: AuctionDocument;
|
||||
message: AuctionChatMessage;
|
||||
created: boolean;
|
||||
}> {
|
||||
const auction = await this.getByMatchId(params.matchId);
|
||||
const messageText = this.normalizeChatMessage(params.message);
|
||||
if (
|
||||
params.clientMessageId !== undefined &&
|
||||
!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
|
||||
params.clientMessageId,
|
||||
)
|
||||
) {
|
||||
throw new BadRequestException('Invalid chat message id.');
|
||||
}
|
||||
// A retry keeps its ID. The conditional push is atomic, including when
|
||||
// the first request is still saving after the client has timed out.
|
||||
const id = params.clientMessageId
|
||||
? `${params.userId?.toString() ?? 'guest'}:${params.clientMessageId}`
|
||||
: randomUUID();
|
||||
const message: AuctionChatMessage = {
|
||||
id: randomUUID(),
|
||||
id,
|
||||
clientMessageId: params.clientMessageId,
|
||||
senderRole: params.senderRole,
|
||||
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);
|
||||
}
|
||||
const AuctionModel = await this.connectionService.getModel('auction');
|
||||
const auction = await AuctionModel.findOneAndUpdate(
|
||||
{ matchId: params.matchId, 'chatMessages.id': { $ne: id } },
|
||||
{
|
||||
$push: {
|
||||
chatMessages: {
|
||||
$each: [message],
|
||||
$slice: -AUCTION_CHAT_MAX_MESSAGES,
|
||||
},
|
||||
},
|
||||
},
|
||||
{ returnDocument: 'after' },
|
||||
);
|
||||
if (auction) return { auction, message, created: true };
|
||||
|
||||
await auction.save();
|
||||
return { auction, message };
|
||||
const existingAuction = await this.getByMatchId(params.matchId);
|
||||
const existing = existingAuction.chatMessages.find(
|
||||
(entry) => entry.id === id,
|
||||
);
|
||||
if (!existing || existing.message !== messageText) {
|
||||
throw new BadRequestException(
|
||||
'Chat message conflicts with an earlier request.',
|
||||
);
|
||||
}
|
||||
return { auction: existingAuction, message: existing, created: false };
|
||||
}
|
||||
|
||||
public async listHistory(params: {
|
||||
@@ -703,10 +733,6 @@ export class AuctionService {
|
||||
throw new BadRequestException('Match does not belong to this community.');
|
||||
}
|
||||
|
||||
const cacheKey = this.buildAuctionHistoryListCacheKey(params);
|
||||
const cachedHistory = this.getCachedAuctionHistoryList(cacheKey);
|
||||
if (cachedHistory) return cachedHistory;
|
||||
|
||||
const entries = (await AuctionHistoryModel.find({ matchId: params.matchId })
|
||||
.select({ _id: 0, action: 1, sequence: 1, takenAt: 1 })
|
||||
.sort({ sequence: -1 })
|
||||
@@ -720,49 +746,9 @@ export class AuctionService {
|
||||
actionLabel: this.formatHistoryActionLabel(entry.action),
|
||||
takenAt: entry.takenAt,
|
||||
}));
|
||||
this.setCachedAuctionHistoryList(cacheKey, history);
|
||||
return history;
|
||||
}
|
||||
|
||||
private buildAuctionHistoryListCacheKey(params: {
|
||||
matchId: mongoose.Types.ObjectId;
|
||||
communityId: mongoose.Types.ObjectId;
|
||||
}): string {
|
||||
return `${params.communityId.toString()}:${params.matchId.toString()}`;
|
||||
}
|
||||
|
||||
private getCachedAuctionHistoryList(
|
||||
cacheKey: string,
|
||||
): AuctionHistoryView[] | null {
|
||||
const cached = this.auctionHistoryListCache.get(cacheKey);
|
||||
if (!cached) return null;
|
||||
if (cached.expiresAtTimestampMS <= Date.now()) {
|
||||
this.auctionHistoryListCache.delete(cacheKey);
|
||||
return null;
|
||||
}
|
||||
return cached.entries;
|
||||
}
|
||||
|
||||
private setCachedAuctionHistoryList(
|
||||
cacheKey: string,
|
||||
entries: AuctionHistoryView[],
|
||||
): void {
|
||||
if (
|
||||
!this.auctionHistoryListCache.has(cacheKey) &&
|
||||
this.auctionHistoryListCache.size >=
|
||||
AUCTION_HISTORY_LIST_CACHE_MAX_ENTRIES
|
||||
) {
|
||||
const oldestKey = this.auctionHistoryListCache.keys().next().value as
|
||||
| string
|
||||
| undefined;
|
||||
if (oldestKey) this.auctionHistoryListCache.delete(oldestKey);
|
||||
}
|
||||
this.auctionHistoryListCache.set(cacheKey, {
|
||||
entries,
|
||||
expiresAtTimestampMS: Date.now() + AUCTION_HISTORY_LIST_CACHE_TTL_MS,
|
||||
});
|
||||
}
|
||||
|
||||
public async openBidding(
|
||||
matchId: mongoose.Types.ObjectId,
|
||||
actionRequest: AuctionStructureActionRequestParams = {},
|
||||
@@ -2921,7 +2907,13 @@ export class AuctionService {
|
||||
bidderUserId: mongoose.Types.ObjectId | undefined,
|
||||
captainUserId: string,
|
||||
) {
|
||||
if (bidderUserId && bidderUserId.toString() !== captainUserId) {
|
||||
if (!isAuctionCaptainAuthRequired()) return;
|
||||
if (!bidderUserId) {
|
||||
throw new ForbiddenException(
|
||||
'팀장 계정으로 로그인해야 입찰할 수 있습니다.',
|
||||
);
|
||||
}
|
||||
if (bidderUserId.toString() !== captainUserId) {
|
||||
throw new ForbiddenException('해당 팀의 팀장만 입찰할 수 있습니다.');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,17 +30,23 @@ function makeService(
|
||||
|
||||
describe('AuctionRedisStateReaderService', () => {
|
||||
it('reads live state identity', async () => {
|
||||
const { service, sendCommand } = makeService([['life-1', '7']]);
|
||||
const { service, sendCommand } = makeService([
|
||||
['life-1', '7', '3', 'transition-1'],
|
||||
]);
|
||||
|
||||
await expect(service.readLiveStateIdentity('match-1')).resolves.toEqual({
|
||||
auctionLifecycleId: 'life-1',
|
||||
revision: 7,
|
||||
matchSideEffectRevision: 3,
|
||||
matchSideEffectTransitionId: 'transition-1',
|
||||
});
|
||||
expect(sendCommand).toHaveBeenCalledWith([
|
||||
'HMGET',
|
||||
'auction:match-1:liveAuctionState',
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -118,7 +124,9 @@ describe('AuctionRedisStateReaderService', () => {
|
||||
|
||||
expect(view).toMatchObject({
|
||||
auctionBidHistory: [{ bidPointAmount: 100, bidderTeamIndex: 2 }],
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
auctionLifecycleId: 'life-1',
|
||||
matchId: 'match-1',
|
||||
auctionTeams: [{ teamIndex: 1 }],
|
||||
canPlaceBidInCurrentBidRound: false,
|
||||
currentHighestBidderTeamIndex: 2,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { AuctionStateIdentity } from '@lolympus/contracts';
|
||||
import { buildAuctionRedisKeys } from './auction-redis.keys';
|
||||
import { AuctionRedisService } from './auction-redis.service';
|
||||
import { assembleAuctionViewFromRedisState } from './auction-redis.state';
|
||||
@@ -17,10 +18,7 @@ const NUMERIC_LIVE_STATE_FIELDS = new Set([
|
||||
'revision',
|
||||
]);
|
||||
|
||||
export interface AuctionRedisLiveStateIdentity {
|
||||
auctionLifecycleId?: string;
|
||||
revision?: number;
|
||||
}
|
||||
export type AuctionRedisLiveStateIdentity = AuctionStateIdentity;
|
||||
|
||||
export interface AuctionRedisBidContext {
|
||||
auctionLifecycleId: string;
|
||||
@@ -49,6 +47,8 @@ export class AuctionRedisStateReaderService {
|
||||
keys.liveStateKey,
|
||||
'auctionLifecycleId',
|
||||
'revision',
|
||||
'matchSideEffectRevision',
|
||||
'matchSideEffectTransitionId',
|
||||
]);
|
||||
if (!Array.isArray(reply)) return null;
|
||||
const auctionLifecycleId =
|
||||
@@ -61,6 +61,12 @@ export class AuctionRedisStateReaderService {
|
||||
return {
|
||||
auctionLifecycleId,
|
||||
revision: Number.isFinite(revision) ? revision : undefined,
|
||||
matchSideEffectRevision:
|
||||
reply[2] !== null && Number.isFinite(Number(reply[2]))
|
||||
? Number(reply[2])
|
||||
: undefined,
|
||||
matchSideEffectTransitionId:
|
||||
typeof reply[3] === 'string' && reply[3] ? reply[3] : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -147,6 +153,7 @@ export class AuctionRedisStateReaderService {
|
||||
structureState: parseJsonRecord(structureStateJson),
|
||||
});
|
||||
view.matchId = matchId;
|
||||
view.auctionEngineVersion = 'redis-v1';
|
||||
if (options.includeInternalLiveStateFields) {
|
||||
view.redisInternalPhase = liveState.phase;
|
||||
}
|
||||
|
||||
@@ -86,10 +86,11 @@ export class CommunityStatsController {
|
||||
@Query('to') to?: string,
|
||||
@Query('championId') championId?: string,
|
||||
@Query('q') query?: string,
|
||||
@Query('lane') lane?: string,
|
||||
) {
|
||||
return this.communityStatsService.getLeaderboard({
|
||||
communityId,
|
||||
filters: this.toFilters({ seasonId, from, to, championId, query }),
|
||||
filters: this.toFilters({ seasonId, from, to, championId, query, lane }),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -131,18 +132,24 @@ export class CommunityStatsController {
|
||||
@Query('championId') championId?: string,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('lane') lane?: string,
|
||||
@Query('includePositionCounts') includePositionCounts?: string,
|
||||
) {
|
||||
return this.communityStatsService.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: this.toFilters({
|
||||
seasonId,
|
||||
from,
|
||||
to,
|
||||
championId,
|
||||
cursor,
|
||||
limit,
|
||||
}),
|
||||
filters: {
|
||||
...this.toFilters({
|
||||
seasonId,
|
||||
from,
|
||||
to,
|
||||
championId,
|
||||
cursor,
|
||||
limit,
|
||||
lane,
|
||||
}),
|
||||
includePositionCounts: includePositionCounts === 'true',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -157,7 +164,14 @@ export class CommunityStatsController {
|
||||
format?: CommunityStatsFilters['format'];
|
||||
playerId?: string;
|
||||
cursorMatchId?: string;
|
||||
lane?: string;
|
||||
}): CommunityStatsFilters {
|
||||
if (
|
||||
params.lane !== undefined &&
|
||||
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
|
||||
) {
|
||||
throw new BadRequestException('Invalid lane.');
|
||||
}
|
||||
if (
|
||||
params.query !== undefined &&
|
||||
(typeof params.query !== 'string' || params.query.length > 100)
|
||||
@@ -175,6 +189,7 @@ export class CommunityStatsController {
|
||||
format: params.format,
|
||||
playerId: params.playerId,
|
||||
cursorMatchId: params.cursorMatchId,
|
||||
lane: params.lane as CommunityStatsFilters['lane'],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -320,7 +320,7 @@ describe('CommunityStatsService', () => {
|
||||
expect(set).not.toHaveBeenCalled();
|
||||
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||
expect(setDetail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
|
||||
response,
|
||||
);
|
||||
},
|
||||
@@ -530,7 +530,7 @@ describe('CommunityStatsService', () => {
|
||||
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||
expect(setDetail).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
|
||||
invalidCheckpointResponse,
|
||||
);
|
||||
});
|
||||
@@ -637,7 +637,7 @@ describe('CommunityStatsService', () => {
|
||||
includeTimeline: true,
|
||||
});
|
||||
expect(set).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
|
||||
fallback,
|
||||
60,
|
||||
);
|
||||
@@ -649,7 +649,7 @@ describe('CommunityStatsService', () => {
|
||||
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
|
||||
expect(setDetail).toHaveBeenCalledTimes(1);
|
||||
expect(setDetail).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ field: expect.stringContaining(':r8:') }),
|
||||
expect.objectContaining({ field: expect.stringContaining(':r9:') }),
|
||||
recovered,
|
||||
);
|
||||
});
|
||||
@@ -820,6 +820,73 @@ describe('CommunityStatsService', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('returns independent recent-20 lane windows and counts from records before pagination', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const records = Array.from({ length: 60 }, (_, index) => ({
|
||||
...record(matchId),
|
||||
userId: userId.toString(),
|
||||
gameNumber: index + 1,
|
||||
riotMatchId: `KR_${index}`,
|
||||
gameCreation: index * 1000,
|
||||
teamPosition: index < 25 ? 'MIDDLE' : 'TOP',
|
||||
}));
|
||||
const repository = {
|
||||
findUserRecordFragments: jest
|
||||
.fn()
|
||||
.mockResolvedValue([
|
||||
{ matchId, builderVersion: MATCH_STATS_BUILDER_VERSION, records },
|
||||
]),
|
||||
findDetailsByMatches: jest.fn().mockResolvedValue([]),
|
||||
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||
const cache = {
|
||||
get: jest.fn().mockResolvedValue(null),
|
||||
set: jest.fn().mockResolvedValue(undefined),
|
||||
} as unknown as CommunityStatsCacheService;
|
||||
const service = new CommunityStatsService(
|
||||
{} as ConnectionService,
|
||||
cache,
|
||||
repository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
(service as unknown as { resolveContext: jest.Mock }).resolveContext = jest
|
||||
.fn()
|
||||
.mockResolvedValue({
|
||||
community: {},
|
||||
season: { id: 'all', label: '전체', startedAt: null, endedAt: null },
|
||||
from: null,
|
||||
to: null,
|
||||
});
|
||||
const mid = await service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { limit: 20, lane: 'MIDDLE', includePositionCounts: true },
|
||||
});
|
||||
expect(mid.matches).toHaveLength(20);
|
||||
expect(mid.matches[0].matchId).toBe('KR_24');
|
||||
expect(mid.matches[19].matchId).toBe('KR_5');
|
||||
expect(mid.matches[0].damageShare).toBe(30);
|
||||
expect(mid.positionCounts).toEqual({
|
||||
ALL: 20,
|
||||
TOP: 20,
|
||||
JUNGLE: 0,
|
||||
MIDDLE: 20,
|
||||
BOTTOM: 0,
|
||||
UTILITY: 0,
|
||||
});
|
||||
expect(repository.findUserRecordFragments).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ limit: 0 }),
|
||||
);
|
||||
const all = await service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { limit: 20, includePositionCounts: true },
|
||||
});
|
||||
expect(all.matches.every((game) => game.teamPosition === 'TOP')).toBe(true);
|
||||
expect(all.positionCounts).toEqual(mid.positionCounts);
|
||||
});
|
||||
|
||||
it('coalesces concurrent user internal history cache misses', async () => {
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
MatchStatsUserRecordFragment,
|
||||
} from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import { presentStatsCard, statsDate } from './internal-stats-presentation';
|
||||
import {
|
||||
InternalGameDetail,
|
||||
InternalRecord,
|
||||
@@ -55,7 +56,7 @@ const DEFAULT_LIST_LIMIT = 20;
|
||||
const MAX_LIST_LIMIT = 50;
|
||||
const MAX_MATCH_SCAN = 300;
|
||||
const MIN_HIGHLIGHT_GAMES = 5;
|
||||
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 8;
|
||||
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 9;
|
||||
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
|
||||
|
||||
interface CommunityStatsContext {
|
||||
@@ -139,6 +140,7 @@ export class CommunityStatsService {
|
||||
'projection.formatType': 1,
|
||||
'projection.outcome': 1,
|
||||
'projection.series': 1,
|
||||
'projection.games': 1,
|
||||
})
|
||||
.lean()
|
||||
.exec();
|
||||
@@ -148,6 +150,9 @@ export class CommunityStatsService {
|
||||
this.presentOfficialResult(competition),
|
||||
]),
|
||||
);
|
||||
const sources = new Map(
|
||||
competitions.map((source) => [source.matchId.toString(), source]),
|
||||
);
|
||||
return {
|
||||
...pagination,
|
||||
matches: cards.map(({ card, sourceCompetitionId, sourceRevision }) => {
|
||||
@@ -161,10 +166,20 @@ export class CommunityStatsService {
|
||||
(resultPresentation.type === 'official' &&
|
||||
sourceCompetitionId === resultPresentation.competitionId &&
|
||||
sourceRevision === resultPresentation.sourceRevision);
|
||||
return {
|
||||
const presented = {
|
||||
...(canUseGames ? card : this.adjustCardForRange(card, [])),
|
||||
resultPresentation,
|
||||
};
|
||||
const source = sources.get(card.matchId);
|
||||
return source && canUseGames
|
||||
? presentStatsCard(
|
||||
presented,
|
||||
presentCompetitionDetail({
|
||||
...source,
|
||||
teams: source.teams.map((team) => ({ ...team, members: [] })),
|
||||
}),
|
||||
)
|
||||
: presented;
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -192,7 +207,24 @@ export class CommunityStatsService {
|
||||
return {
|
||||
cards: visible.map((fragment) => ({
|
||||
card: this.adjustCardForRange(
|
||||
fragment.matchCard as unknown as InternalMatchCardView,
|
||||
{
|
||||
...(fragment.matchCard as unknown as InternalMatchCardView),
|
||||
games: (
|
||||
fragment.matchCard as unknown as InternalMatchCardView
|
||||
).games.map((game) => {
|
||||
const detail = fragment.gameDetails?.find(
|
||||
(item) => item.gameNumber === game.gameNumber,
|
||||
);
|
||||
return {
|
||||
...game,
|
||||
analysisAvailability: !detail
|
||||
? ('pending' as const)
|
||||
: detail.rawAvailable === false
|
||||
? ('missing' as const)
|
||||
: ('available' as const),
|
||||
};
|
||||
}),
|
||||
},
|
||||
(fragment.gameDetails ?? []).filter((game) =>
|
||||
this.isGameInRange(game.gameCreation, context),
|
||||
),
|
||||
@@ -226,6 +258,7 @@ export class CommunityStatsService {
|
||||
const records = this.applyChampionFilter(dataset.records, filters);
|
||||
response = {
|
||||
rows: this.buildLeaderboardRows(records),
|
||||
lane: filters.lane,
|
||||
season: dataset.season,
|
||||
};
|
||||
await this.cacheService.set(key, response);
|
||||
@@ -275,6 +308,7 @@ export class CommunityStatsService {
|
||||
|
||||
const response: TeamInsightsResponse = {
|
||||
season: dataset.season,
|
||||
totals: dataset.totals,
|
||||
sideWinRate: {
|
||||
blue: this.percent(blueWins, blueGames),
|
||||
red: this.percent(redWins, redGames),
|
||||
@@ -464,7 +498,18 @@ export class CommunityStatsService {
|
||||
}
|
||||
}
|
||||
const response: InternalMatchDetailResponse = {
|
||||
match,
|
||||
match: presentStatsCard(
|
||||
{
|
||||
...match,
|
||||
games: (match.games ?? []).map((game) => ({
|
||||
...game,
|
||||
analysisAvailability:
|
||||
games.find((linked) => linked.game.gameNumber === game.gameNumber)
|
||||
?.analysisAvailability ?? 'pending',
|
||||
})),
|
||||
},
|
||||
dataset.competition,
|
||||
),
|
||||
competition: dataset.competition,
|
||||
games: games.map(({ game, official, analysisAvailability }) => ({
|
||||
gameNumber: game.gameNumber,
|
||||
@@ -708,11 +753,24 @@ export class CommunityStatsService {
|
||||
});
|
||||
const gameDetails: Array<Pick<InternalGameDetail, 'winnerSide'>> = [];
|
||||
const records: InternalRecord[] = [];
|
||||
const participants = new Set<string>();
|
||||
let matches = 0,
|
||||
analyzedGames = 0;
|
||||
for (const fragment of fragments) {
|
||||
const games = fragment.gameDetails.filter((game) =>
|
||||
this.isGameInRange(game.gameCreation, context),
|
||||
);
|
||||
const gameNumbers = new Set(games.map(({ gameNumber }) => gameNumber));
|
||||
if (games.length) matches += 1;
|
||||
const gameNumbers = new Set(
|
||||
games
|
||||
.filter((game) => game.rawAvailable !== false)
|
||||
.map(({ gameNumber }) => gameNumber),
|
||||
);
|
||||
analyzedGames += gameNumbers.size;
|
||||
const allNumbers = new Set(games.map((game) => game.gameNumber));
|
||||
fragment.records
|
||||
.filter((record) => allNumbers.has(record.gameNumber))
|
||||
.forEach((record) => participants.add(record.userId));
|
||||
gameDetails.push(...games);
|
||||
records.push(
|
||||
...fragment.records.filter(({ gameNumber }) =>
|
||||
@@ -720,7 +778,17 @@ export class CommunityStatsService {
|
||||
),
|
||||
);
|
||||
}
|
||||
return { season: context.season, records, gameDetails };
|
||||
return {
|
||||
season: context.season,
|
||||
records,
|
||||
gameDetails,
|
||||
totals: {
|
||||
matches,
|
||||
games: gameDetails.length,
|
||||
analyzedGames,
|
||||
players: participants.size,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async buildBaseDataset(
|
||||
@@ -850,7 +918,8 @@ export class CommunityStatsService {
|
||||
userId: params.userId,
|
||||
fromGameCreation: context.from?.getTime(),
|
||||
toGameCreation: context.to?.getTime(),
|
||||
limit: MAX_MATCH_SCAN,
|
||||
// The inspector needs the latest 20 of each lane, even in older events.
|
||||
limit: params.filters.includePositionCounts ? 0 : MAX_MATCH_SCAN,
|
||||
};
|
||||
let fragments =
|
||||
await this.matchStatsRepository.findUserRecordFragments(fragmentQuery);
|
||||
@@ -885,8 +954,31 @@ export class CommunityStatsService {
|
||||
};
|
||||
const response: UserInternalHistoryResponse = {
|
||||
season: context.season,
|
||||
...(params.filters.includePositionCounts
|
||||
? {
|
||||
positionCounts: Object.fromEntries(
|
||||
['ALL', 'TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].map(
|
||||
(lane) => [
|
||||
lane,
|
||||
Math.min(
|
||||
20,
|
||||
this.applyChampionFilter(allUserRecords, {
|
||||
championId: params.filters.championId,
|
||||
}).filter(
|
||||
(record) =>
|
||||
lane === 'ALL' || record.teamPosition === lane,
|
||||
).length,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
playerStats: records.length
|
||||
? this.toLeaderboardRow(userId, records)
|
||||
: null,
|
||||
championStats: this.buildUserChampionStats(
|
||||
allUserRecords,
|
||||
this.applyChampionFilter(allUserRecords, { lane: params.filters.lane }),
|
||||
context.season,
|
||||
),
|
||||
summary: this.buildUserSummary(records, visible.length || limit),
|
||||
@@ -913,6 +1005,11 @@ export class CommunityStatsService {
|
||||
fragment.records.filter(
|
||||
(record) =>
|
||||
record.userId === userId &&
|
||||
!fragment.gameDetails?.some(
|
||||
(game) =>
|
||||
game.gameNumber === record.gameNumber &&
|
||||
game.rawAvailable === false,
|
||||
) &&
|
||||
this.isGameInRange(record.gameCreation, context),
|
||||
),
|
||||
)
|
||||
@@ -1129,13 +1226,13 @@ export class CommunityStatsService {
|
||||
const community = await CommunityModel.findById(communityId).exec();
|
||||
if (!community) throw new NotFoundException('Community not found.');
|
||||
const season = this.resolveSeason(community, filters.seasonId);
|
||||
const from = filters.from
|
||||
? new Date(filters.from)
|
||||
let from = filters.from
|
||||
? statsDate(filters.from, false)
|
||||
: season.startedAt
|
||||
? new Date(season.startedAt)
|
||||
: null;
|
||||
const to = filters.to
|
||||
? new Date(filters.to)
|
||||
let to = filters.to
|
||||
? statsDate(filters.to, true)
|
||||
: season.endedAt
|
||||
? new Date(season.endedAt)
|
||||
: null;
|
||||
@@ -1148,6 +1245,11 @@ export class CommunityStatsService {
|
||||
if (from && to && from.getTime() > to.getTime()) {
|
||||
throw new BadRequestException('Invalid date range.');
|
||||
}
|
||||
// A date filter narrows the selected season; it never escapes it.
|
||||
if (season.startedAt && (!from || from < new Date(season.startedAt)))
|
||||
from = new Date(season.startedAt);
|
||||
if (season.endedAt && (!to || to > new Date(season.endedAt)))
|
||||
to = new Date(season.endedAt);
|
||||
return { community, season, from, to };
|
||||
}
|
||||
|
||||
@@ -1419,6 +1521,7 @@ export class CommunityStatsService {
|
||||
return {
|
||||
matchId: record.riotMatchId,
|
||||
internalMatchId: record.matchId,
|
||||
internalMatchTitle: record.title,
|
||||
gameNumber: record.gameNumber,
|
||||
queueId: 0,
|
||||
queueLabel: '내전',
|
||||
@@ -1443,6 +1546,7 @@ export class CommunityStatsService {
|
||||
wardsPlaced: record.wardsPlaced,
|
||||
wardsKilled: record.wardsKilled,
|
||||
damageDealtToChampions: record.damageDealtToChampions,
|
||||
damageShare: record.damageShare,
|
||||
damageTaken: record.damageTaken,
|
||||
goldEarned: record.gold,
|
||||
items: record.items,
|
||||
@@ -1493,8 +1597,11 @@ export class CommunityStatsService {
|
||||
records: InternalRecord[],
|
||||
filters: CommunityStatsFilters,
|
||||
): InternalRecord[] {
|
||||
if (!filters.championId) return records;
|
||||
return records.filter((record) => record.championId === filters.championId);
|
||||
return records.filter(
|
||||
(record) =>
|
||||
(!filters.championId || record.championId === filters.championId) &&
|
||||
(!filters.lane || record.teamPosition === filters.lane),
|
||||
);
|
||||
}
|
||||
|
||||
private isGameInRange(
|
||||
@@ -1533,6 +1640,8 @@ export class CommunityStatsService {
|
||||
summonerName: record.summonerName,
|
||||
championId: record.championId,
|
||||
matchId: record.riotMatchId,
|
||||
internalMatchId: record.matchId,
|
||||
gameNumber: record.gameNumber,
|
||||
isSingleGame: true,
|
||||
};
|
||||
}
|
||||
@@ -1621,7 +1730,7 @@ export class CommunityStatsService {
|
||||
cacheScope,
|
||||
JSON.stringify([
|
||||
MATCH_STATS_BUILDER_VERSION,
|
||||
scope === 'matches' ? 'matches-page-v1' : scope,
|
||||
`${scope}:presentation-v2`,
|
||||
filters.seasonId ?? 'current',
|
||||
filters.from ?? '',
|
||||
filters.to ?? '',
|
||||
@@ -1632,6 +1741,8 @@ export class CommunityStatsService {
|
||||
filters.format ?? '',
|
||||
filters.playerId ?? '',
|
||||
filters.cursorMatchId ?? '',
|
||||
filters.lane ?? '',
|
||||
...(filters.includePositionCounts ? ['position-windows-v1'] : []),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
InternalMatchCompetition,
|
||||
InternalMatchResultPresentation,
|
||||
SeriesId,
|
||||
SeriesProjection,
|
||||
} from '@lolympus/contracts';
|
||||
import type {
|
||||
MatchStatsParticipantCheckpoints,
|
||||
@@ -21,6 +22,7 @@ import type {
|
||||
} from '../match-history/match-history.types';
|
||||
|
||||
export interface CommunityStatsFilters {
|
||||
includePositionCounts?: boolean;
|
||||
seasonId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
@@ -31,6 +33,7 @@ export interface CommunityStatsFilters {
|
||||
format?: 'pair' | 'tournament';
|
||||
playerId?: string;
|
||||
cursorMatchId?: string;
|
||||
lane?: RiotLane;
|
||||
}
|
||||
|
||||
export interface InternalMatchListResponse {
|
||||
@@ -48,6 +51,8 @@ export interface InternalMatchCardView {
|
||||
gameCount: number;
|
||||
winnerTeamIndex?: number;
|
||||
resultPresentation?: InternalMatchResultPresentation;
|
||||
/** Official series only. Historical opponent pairs are not inferred rounds. */
|
||||
series?: SeriesProjection[];
|
||||
seriesResults: Array<{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
@@ -57,6 +62,9 @@ export interface InternalMatchCardView {
|
||||
}>;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
seriesId?: string;
|
||||
ordinal?: number;
|
||||
analysisAvailability?: GameAnalysisAvailability | 'pending';
|
||||
riotMatchId: string | null;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -66,6 +74,7 @@ export interface InternalMatchCardView {
|
||||
}>;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
teamId?: string;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
@@ -77,6 +86,7 @@ export interface InternalMatchCardView {
|
||||
|
||||
export interface LeaderboardResponse {
|
||||
rows: LeaderboardRow[];
|
||||
lane?: RiotLane;
|
||||
season: HistorySeasonDto;
|
||||
matchedUserIds?: string[];
|
||||
}
|
||||
@@ -111,11 +121,19 @@ export interface LeaderHighlight {
|
||||
summonerName: string;
|
||||
championId?: number;
|
||||
matchId?: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
isSingleGame: boolean;
|
||||
}
|
||||
|
||||
export interface TeamInsightsResponse {
|
||||
season: HistorySeasonDto;
|
||||
totals: {
|
||||
matches: number;
|
||||
games: number;
|
||||
analyzedGames: number;
|
||||
players: number;
|
||||
};
|
||||
sideWinRate: {
|
||||
blue: number;
|
||||
red: number;
|
||||
@@ -214,7 +232,9 @@ export interface InternalMatchDetailResponse {
|
||||
}
|
||||
|
||||
export interface UserInternalHistoryResponse {
|
||||
positionCounts?: Record<string, number>;
|
||||
season: HistorySeasonDto;
|
||||
playerStats?: LeaderboardRow | null;
|
||||
championStats: LeaderboardChampionStats;
|
||||
summary: {
|
||||
windowSize: number;
|
||||
|
||||
@@ -0,0 +1,378 @@
|
||||
import { BadRequestException } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import request from 'supertest';
|
||||
import type { Server } from 'node:http';
|
||||
import mongoose from 'mongoose';
|
||||
import { CommunityStatsService } from './community-stats.service';
|
||||
import { CommunityStatsController } from './community-stats.controller';
|
||||
import { ConnectionService } from '../global/database/connection.service';
|
||||
import { CommunityStatsCacheService } from './community-stats-cache.service';
|
||||
import { MatchStatsRepository } from './match-stats.repository';
|
||||
import { MatchStatsService } from './match-stats.service';
|
||||
import {
|
||||
MATCH_STATS_BUILDER_VERSION,
|
||||
type InternalRecord,
|
||||
} from './match-stats.types';
|
||||
import { presentStatsCard, statsDate } from './internal-stats-presentation';
|
||||
|
||||
const communityId = new mongoose.Types.ObjectId();
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
const userId = new mongoose.Types.ObjectId();
|
||||
const start = Date.parse('2026-06-18T12:00:00Z');
|
||||
function record(
|
||||
gameNumber: number,
|
||||
values: Partial<InternalRecord> = {},
|
||||
): InternalRecord {
|
||||
return {
|
||||
matchId: matchId.toString(),
|
||||
title: '여름 내전',
|
||||
scheduledAt: new Date(start),
|
||||
gameNumber,
|
||||
riotMatchId: `KR_${gameNumber}`,
|
||||
gameCreation: start + gameNumber * 1800000,
|
||||
gameDuration: 1800,
|
||||
userId: userId.toString(),
|
||||
summonerName: '선수',
|
||||
tagLine: 'KR1',
|
||||
profileIconId: 1,
|
||||
teamIndex: 1,
|
||||
side: 'blue',
|
||||
championId: 1,
|
||||
teamPosition: 'TOP',
|
||||
kills: 8,
|
||||
deaths: 2,
|
||||
assists: 4,
|
||||
win: true,
|
||||
cs: 240,
|
||||
csPerMin: 8,
|
||||
gold: 12000,
|
||||
gpm: 400,
|
||||
killParticipation: 60,
|
||||
damageShare: 30,
|
||||
visionScore: 12,
|
||||
damageDealtToChampions: 18000,
|
||||
...values,
|
||||
} as InternalRecord;
|
||||
}
|
||||
function fixture() {
|
||||
const records = [
|
||||
record(1),
|
||||
record(2, {
|
||||
teamPosition: 'JUNGLE',
|
||||
championId: 2,
|
||||
kills: 2,
|
||||
deaths: 4,
|
||||
assists: 6,
|
||||
win: false,
|
||||
csPerMin: 4,
|
||||
gpm: 300,
|
||||
killParticipation: 40,
|
||||
}),
|
||||
record(3, { kills: 99 }),
|
||||
record(3, { userId: new mongoose.Types.ObjectId().toString() }),
|
||||
];
|
||||
const fragment = {
|
||||
matchId,
|
||||
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||
records,
|
||||
gameDetails: [1, 2, 3].map((gameNumber) => ({
|
||||
gameNumber,
|
||||
gameCreation: start + gameNumber * 1800000,
|
||||
winnerSide: gameNumber === 2 ? 'red' : 'blue',
|
||||
rawAvailable: gameNumber !== 3,
|
||||
})),
|
||||
};
|
||||
const cache = new Map<string, unknown>();
|
||||
const repository = {
|
||||
findSeasonStats: jest.fn().mockResolvedValue([fragment]),
|
||||
findUserRecordFragments: jest.fn().mockResolvedValue([fragment]),
|
||||
findDetailsByMatches: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const service = new CommunityStatsService(
|
||||
{
|
||||
getModel: async () => ({
|
||||
findById: () => ({
|
||||
exec: async () => ({
|
||||
seasons: [
|
||||
{
|
||||
id: 'june',
|
||||
label: '6월',
|
||||
startedAt: new Date('2026-06-01T00:00:00+09:00'),
|
||||
endedAt: new Date('2026-06-30T23:59:59.999+09:00'),
|
||||
},
|
||||
],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
} as unknown as ConnectionService,
|
||||
{
|
||||
get: async (key: unknown) => cache.get(JSON.stringify(key)),
|
||||
set: async (key: unknown, value: unknown) => {
|
||||
cache.set(JSON.stringify(key), value);
|
||||
},
|
||||
} as unknown as CommunityStatsCacheService,
|
||||
repository as unknown as MatchStatsRepository,
|
||||
{} as MatchStatsService,
|
||||
);
|
||||
jest
|
||||
.spyOn(
|
||||
service as unknown as { repairCommunityFragments: () => Promise<number> },
|
||||
'repairCommunityFragments',
|
||||
)
|
||||
.mockResolvedValue(0);
|
||||
return { service, repository };
|
||||
}
|
||||
|
||||
describe('internal stats API contract', () => {
|
||||
it('serves the scoped player and leaderboard contracts through the HTTP routes', async () => {
|
||||
const { service } = fixture();
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [CommunityStatsController],
|
||||
providers: [{ provide: CommunityStatsService, useValue: service }],
|
||||
}).compile();
|
||||
const app = module.createNestApplication();
|
||||
await app.init();
|
||||
const server: Server = app.getHttpServer();
|
||||
try {
|
||||
const base = `/communities/${communityId.toString()}`;
|
||||
const leaderboard = await request(server)
|
||||
.get(`${base}/internal-stats/leaderboard?seasonId=all&lane=TOP`)
|
||||
.expect(200);
|
||||
expect(leaderboard.body).toMatchObject({
|
||||
lane: 'TOP',
|
||||
rows: [{ games: 1, kda: 6 }],
|
||||
});
|
||||
const player = await request(server)
|
||||
.get(
|
||||
`${base}/users/${userId.toString()}/internal-history?seasonId=all&lane=JUNGLE`,
|
||||
)
|
||||
.expect(200);
|
||||
expect(player.body).toMatchObject({
|
||||
playerStats: { games: 1, kda: 2 },
|
||||
matches: [{ gameNumber: 2 }],
|
||||
});
|
||||
await request(server)
|
||||
.get(`${base}/internal-stats/leaderboard?lane=invalid`)
|
||||
.expect(400);
|
||||
await request(server)
|
||||
.get(`${base}/internal-stats/leaderboard?from=2026-02-30`)
|
||||
.expect(400);
|
||||
await request(server)
|
||||
.get('/communities/invalid/internal-stats/leaderboard')
|
||||
.expect(400);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
});
|
||||
it('searches escaped text across title, team and player without losing date or cursor constraints', async () => {
|
||||
const chain = {
|
||||
select: jest.fn().mockReturnThis(),
|
||||
sort: jest.fn().mockReturnThis(),
|
||||
limit: jest.fn().mockReturnThis(),
|
||||
lean: jest.fn().mockReturnThis(),
|
||||
exec: jest.fn().mockResolvedValue([]),
|
||||
};
|
||||
const find = jest.fn().mockReturnValue(chain);
|
||||
const repository = new MatchStatsRepository({
|
||||
getModel: async () => ({ find }),
|
||||
} as unknown as ConnectionService);
|
||||
await repository.findMatchPage({
|
||||
communityId,
|
||||
query: '팀.*',
|
||||
from: start,
|
||||
cursor: start + 1000,
|
||||
cursorMatchId: matchId.toString(),
|
||||
limit: 4,
|
||||
});
|
||||
expect(find).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
communityId,
|
||||
$and: expect.arrayContaining([
|
||||
{
|
||||
$or: [
|
||||
'matchCard.title',
|
||||
'matchCard.teams.name',
|
||||
'matchCard.teams.members.summonerName',
|
||||
].map((field) => ({
|
||||
[field]: { $regex: '팀\\.\\*', $options: 'i' },
|
||||
})),
|
||||
},
|
||||
]),
|
||||
}),
|
||||
);
|
||||
expect(chain.limit).toHaveBeenCalledWith(4);
|
||||
expect(chain.select).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ 'gameDetails.rawAvailable': 1 }),
|
||||
);
|
||||
});
|
||||
it('recalculates every metric per lane, isolates cached scopes and excludes missing raw data', async () => {
|
||||
const { service } = fixture();
|
||||
const all = await service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { seasonId: 'all' },
|
||||
});
|
||||
const top = await service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { seasonId: 'all', lane: 'TOP' },
|
||||
});
|
||||
const jungle = await service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { seasonId: 'all', lane: 'JUNGLE' },
|
||||
});
|
||||
expect(all.rows).toHaveLength(1);
|
||||
expect(all.rows[0]).toMatchObject({
|
||||
games: 2,
|
||||
totalKills: 10,
|
||||
winRate: 50,
|
||||
avgGoldPerMin: 350,
|
||||
avgCsPerMin: 6,
|
||||
avgKillParticipation: 50,
|
||||
});
|
||||
expect(top).toMatchObject({
|
||||
lane: 'TOP',
|
||||
rows: [
|
||||
{
|
||||
games: 1,
|
||||
kda: 6,
|
||||
winRate: 100,
|
||||
avgGoldPerMin: 400,
|
||||
avgCsPerMin: 8,
|
||||
avgKillParticipation: 60,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(jungle).toMatchObject({
|
||||
lane: 'JUNGLE',
|
||||
rows: [{ games: 1, kda: 2, winRate: 0, avgGoldPerMin: 300 }],
|
||||
});
|
||||
expect(
|
||||
await service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { seasonId: 'all' },
|
||||
}),
|
||||
).toEqual(all);
|
||||
const insight = await service.getTeamInsights({
|
||||
communityId,
|
||||
filters: { seasonId: 'all' },
|
||||
});
|
||||
expect(insight.totals).toEqual({
|
||||
matches: 1,
|
||||
games: 3,
|
||||
analyzedGames: 2,
|
||||
players: 2,
|
||||
});
|
||||
expect(insight.topTeamGpm).toMatchObject({
|
||||
internalMatchId: matchId.toString(),
|
||||
gameNumber: 1,
|
||||
metric: 400,
|
||||
});
|
||||
});
|
||||
it('keeps player summary and matches in the same scope while retaining champion choices', async () => {
|
||||
const { service } = fixture();
|
||||
const history = await service.getUserInternalHistory({
|
||||
communityId,
|
||||
userId,
|
||||
filters: { seasonId: 'all', championId: 1 },
|
||||
});
|
||||
expect(history.playerStats).toMatchObject({ games: 1, kda: 6 });
|
||||
expect(history.matches).toHaveLength(1);
|
||||
expect(history.matches[0]).toMatchObject({
|
||||
internalMatchId: matchId.toString(),
|
||||
internalMatchTitle: '여름 내전',
|
||||
gameNumber: 1,
|
||||
});
|
||||
expect(history.championStats.champions).toHaveLength(2);
|
||||
});
|
||||
it('intersects custom dates with the season and accepts inclusive KST calendar dates', async () => {
|
||||
const { service, repository } = fixture();
|
||||
await service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { seasonId: 'june', from: '2026-05-01', to: '2026-07-31' },
|
||||
});
|
||||
expect(repository.findSeasonStats).toHaveBeenCalledWith({
|
||||
communityId,
|
||||
from: Date.parse('2026-05-31T15:00:00Z'),
|
||||
to: Date.parse('2026-06-30T14:59:59.999Z'),
|
||||
});
|
||||
expect(statsDate('2026-06-18', false)?.toISOString()).toBe(
|
||||
'2026-06-17T15:00:00.000Z',
|
||||
);
|
||||
expect(statsDate('2026-06-18', true)?.toISOString()).toBe(
|
||||
'2026-06-18T14:59:59.999Z',
|
||||
);
|
||||
await expect(
|
||||
service.getLeaderboard({ communityId, filters: { from: '2026-02-30' } }),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
await expect(
|
||||
service.getLeaderboard({
|
||||
communityId,
|
||||
filters: { from: '2026-06-20', to: '2026-06-19' },
|
||||
}),
|
||||
).rejects.toBeInstanceOf(BadRequestException);
|
||||
});
|
||||
it('rejects unsupported lanes at the HTTP controller boundary', () => {
|
||||
const controller = new CommunityStatsController(
|
||||
{} as CommunityStatsService,
|
||||
);
|
||||
expect(() =>
|
||||
(
|
||||
controller as unknown as {
|
||||
toFilters: (params: { lane: string }) => unknown;
|
||||
}
|
||||
).toFilters({ lane: 'SUPPORT' }),
|
||||
).toThrow(BadRequestException);
|
||||
});
|
||||
it('uses official evidence to distinguish rematches and does not invent round identities', () => {
|
||||
type Card = Parameters<typeof presentStatsCard>[0];
|
||||
type Competition = NonNullable<Parameters<typeof presentStatsCard>[1]>;
|
||||
const card = {
|
||||
games: [
|
||||
{ gameNumber: 1, riotMatchId: 'KR_1' },
|
||||
{ gameNumber: 2, riotMatchId: 'KR_2' },
|
||||
{ gameNumber: 3, riotMatchId: 'old' },
|
||||
],
|
||||
teams: [{ teamIndex: 1 }],
|
||||
} as Card;
|
||||
const competition = {
|
||||
teams: [{ displayOrder: 1, teamId: 'a' }],
|
||||
projection: {
|
||||
games: [
|
||||
{
|
||||
displayNumber: 1,
|
||||
ordinal: 1,
|
||||
seriesId: 'upper',
|
||||
evidence: { type: 'riot', riotMatchId: 'KR_1' },
|
||||
},
|
||||
{
|
||||
displayNumber: 2,
|
||||
ordinal: 1,
|
||||
seriesId: 'final',
|
||||
evidence: { type: 'riot', riotMatchId: 'KR_2' },
|
||||
},
|
||||
{
|
||||
displayNumber: 3,
|
||||
ordinal: 2,
|
||||
seriesId: 'final',
|
||||
evidence: { type: 'riot', riotMatchId: 'replacement' },
|
||||
},
|
||||
],
|
||||
series: [
|
||||
{ seriesId: 'upper' },
|
||||
{ seriesId: 'final' },
|
||||
{ seriesId: 'other', status: 'scheduled' },
|
||||
],
|
||||
},
|
||||
} as unknown as Competition;
|
||||
const result = presentStatsCard(card, competition);
|
||||
expect(result.games.map((game) => game.seriesId)).toEqual([
|
||||
'upper',
|
||||
'final',
|
||||
undefined,
|
||||
]);
|
||||
expect(result.series?.map((series) => series.seriesId)).toEqual([
|
||||
'upper',
|
||||
'final',
|
||||
]);
|
||||
expect(result.teams[0].teamId).toBe('a');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { InternalMatchCompetition } from '@lolympus/contracts';
|
||||
import type { InternalMatchCardView } from './community-stats.types';
|
||||
|
||||
/** Attach official identities without merging rematches between the same teams. */
|
||||
export function presentStatsCard(
|
||||
card: InternalMatchCardView,
|
||||
competition?: Pick<InternalMatchCompetition, 'teams' | 'projection'>,
|
||||
): InternalMatchCardView {
|
||||
if (!competition) return card;
|
||||
const officialGames = competition.projection.games ?? [];
|
||||
const games = card.games.map((game) => {
|
||||
const official = officialGames.find(
|
||||
(candidate) =>
|
||||
candidate.displayNumber === game.gameNumber &&
|
||||
(candidate.evidence.type === 'riot'
|
||||
? candidate.evidence.riotMatchId
|
||||
: candidate.evidence.legacyReference) === game.riotMatchId,
|
||||
);
|
||||
return official
|
||||
? { ...game, seriesId: official.seriesId, ordinal: official.ordinal }
|
||||
: game;
|
||||
});
|
||||
const visible = new Set(games.map((game) => game.seriesId));
|
||||
return {
|
||||
...card,
|
||||
games,
|
||||
teams: card.teams?.map((team) => ({
|
||||
...team,
|
||||
teamId: competition.teams.find((t) => t.displayOrder === team.teamIndex)
|
||||
?.teamId,
|
||||
})),
|
||||
series: (competition.projection.series ?? []).filter(
|
||||
(series) =>
|
||||
visible.has(series.seriesId) ||
|
||||
(series.status === 'completed' && series.outcome.type !== 'played'),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
/** Date-only inputs are inclusive Korean calendar days; ISO timestamps remain supported. */
|
||||
export function statsDate(
|
||||
value: string | undefined,
|
||||
end: boolean,
|
||||
): Date | null {
|
||||
if (!value) return null;
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(value)) {
|
||||
const date = new Date(
|
||||
`${value}T${end ? '23:59:59.999' : '00:00:00.000'}+09:00`,
|
||||
);
|
||||
const midnight = new Date(`${value}T00:00:00.000Z`);
|
||||
if (
|
||||
!Number.isFinite(midnight.getTime()) ||
|
||||
midnight.toISOString().slice(0, 10) !== value
|
||||
)
|
||||
return new Date(NaN);
|
||||
return date;
|
||||
}
|
||||
return new Date(value);
|
||||
}
|
||||
@@ -6,7 +6,11 @@ import type { MatchStats, MatchStatsDocument } from '../global/database/schema';
|
||||
export type MatchStatsUserRecordFragment = Pick<
|
||||
MatchStats,
|
||||
'matchId' | 'records' | 'builderVersion'
|
||||
>;
|
||||
> & {
|
||||
gameDetails?: Array<
|
||||
Pick<MatchStats['gameDetails'][number], 'gameNumber' | 'rawAvailable'>
|
||||
>;
|
||||
};
|
||||
|
||||
export type MatchStatsDetailFragment = Pick<
|
||||
MatchStats,
|
||||
@@ -209,10 +213,17 @@ export class MatchStatsRepository {
|
||||
};
|
||||
}
|
||||
if (params.query) {
|
||||
filter['matchCard.title'] = {
|
||||
const search = {
|
||||
$regex: params.query.replace(/[.*+?^$\x7b\x7d()|[\]\\]/g, '\\$&'),
|
||||
$options: 'i',
|
||||
};
|
||||
conditions.push({
|
||||
$or: [
|
||||
{ 'matchCard.title': search },
|
||||
{ 'matchCard.teams.name': search },
|
||||
{ 'matchCard.teams.members.summonerName': search },
|
||||
],
|
||||
});
|
||||
}
|
||||
if (params.format) {
|
||||
filter['matchCard.teams.1'] = { $exists: true };
|
||||
@@ -250,6 +261,7 @@ export class MatchStatsRepository {
|
||||
sourceRevision: 1,
|
||||
'gameDetails.gameNumber': 1,
|
||||
'gameDetails.gameCreation': 1,
|
||||
'gameDetails.rawAvailable': 1,
|
||||
})
|
||||
.sort({ scheduledAt: -1, matchId: -1 })
|
||||
.limit(params.limit)
|
||||
@@ -298,6 +310,8 @@ export class MatchStatsRepository {
|
||||
})
|
||||
.select({
|
||||
_id: 0,
|
||||
matchId: 1,
|
||||
scheduledAt: 1,
|
||||
'records.userId': 1,
|
||||
'records.summonerName': 1,
|
||||
'records.tagLine': 1,
|
||||
@@ -319,6 +333,7 @@ export class MatchStatsRepository {
|
||||
'gameDetails.gameCreation': 1,
|
||||
'gameDetails.gameNumber': 1,
|
||||
'gameDetails.winnerSide': 1,
|
||||
'gameDetails.rawAvailable': 1,
|
||||
})
|
||||
.sort({ scheduledAt: -1 })
|
||||
.lean()
|
||||
@@ -352,7 +367,14 @@ export class MatchStatsRepository {
|
||||
return MatchStatsModel.find(filter)
|
||||
.sort({ scheduledAt: -1 })
|
||||
.limit(params.limit ?? 300)
|
||||
.select({ _id: 0, matchId: 1, records: 1, builderVersion: 1 })
|
||||
.select({
|
||||
_id: 0,
|
||||
matchId: 1,
|
||||
records: 1,
|
||||
builderVersion: 1,
|
||||
'gameDetails.gameNumber': 1,
|
||||
'gameDetails.rawAvailable': 1,
|
||||
})
|
||||
.lean<MatchStatsUserRecordFragment[]>()
|
||||
.exec();
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import { readFile } from 'node:fs/promises';
|
||||
import { resolve } from 'node:path';
|
||||
import { ConnectionService, resolveMongoDbName } from '../connection.service';
|
||||
import type {
|
||||
Community,
|
||||
MatchGameResult,
|
||||
MatchParticipant,
|
||||
MatchSeriesResult,
|
||||
@@ -250,16 +251,17 @@ async function main() {
|
||||
);
|
||||
}
|
||||
|
||||
const match = await MatchModel.create(payload);
|
||||
console.log(`[temp result seed] created=${match._id.toString()}`);
|
||||
console.log(`[temp result seed] route=/match/${match._id.toString()}`);
|
||||
const matchId = new mongoose.Types.ObjectId();
|
||||
await MatchModel.create({ ...payload, _id: matchId });
|
||||
console.log(`[temp result seed] created=${matchId.toString()}`);
|
||||
console.log(`[temp result seed] route=/match/${matchId.toString()}`);
|
||||
} finally {
|
||||
await app.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveCommunity(
|
||||
CommunityModel: mongoose.Model<unknown>,
|
||||
CommunityModel: mongoose.Model<Community>,
|
||||
communityId?: string,
|
||||
): Promise<CommunityLean> {
|
||||
const community = communityId
|
||||
@@ -316,11 +318,11 @@ function buildMatchPayload(
|
||||
description:
|
||||
'결과 페이지 검증용으로 생성된 30명, 6팀, 15경기 완료 임시 데이터입니다.',
|
||||
mapId: 11,
|
||||
status: 'finished',
|
||||
status: 'finished' as const,
|
||||
scheduledAt: options.scheduledAt,
|
||||
maxParticipants: TOTAL_PLAYERS,
|
||||
gameCount: GAME_COUNT_PER_SERIES_GROUP,
|
||||
gameMode: 'round-robin',
|
||||
gameMode: 'round-robin' as const,
|
||||
tournamentCodeIds: [],
|
||||
teamBuiltAt: new Date(options.scheduledAt.getTime() - 30 * 60000),
|
||||
participants,
|
||||
@@ -335,10 +337,10 @@ function buildMatchPayload(
|
||||
resultPollState: {
|
||||
startedAt: new Date(options.scheduledAt.getTime() + 2 * 60 * 60 * 1000),
|
||||
lastPolledAt: now,
|
||||
lastPollOutcome: 'matched',
|
||||
lastPollOutcome: 'matched' as const,
|
||||
matchedCount: games.length,
|
||||
expandedToAllPuuids: true,
|
||||
state: 'complete',
|
||||
state: 'complete' as const,
|
||||
},
|
||||
legacyImported: true,
|
||||
legacyImportSource: {
|
||||
|
||||
@@ -857,6 +857,8 @@ export const AuctionBidRecordSchema = new Schema<AuctionBidRecord>(
|
||||
|
||||
export interface AuctionChatMessage {
|
||||
id: string;
|
||||
clientMessageId?: string;
|
||||
senderRole?: 'operator';
|
||||
userId?: mongoose.Types.ObjectId;
|
||||
displayName: string;
|
||||
message: string;
|
||||
@@ -2255,6 +2257,8 @@ const AuctionBidHistoryEntrySubSchema = new Schema<AuctionBidHistoryEntry>(
|
||||
const AuctionChatMessageSubSchema = new Schema<AuctionChatMessage>(
|
||||
{
|
||||
id: { type: String, required: true },
|
||||
clientMessageId: { type: String, required: false },
|
||||
senderRole: { type: String, enum: ['operator'], required: false },
|
||||
userId: { type: Schema.Types.ObjectId, ref: 'user', required: false },
|
||||
displayName: { type: String, required: true },
|
||||
message: { type: String, required: true },
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { connect } from 'nats';
|
||||
import type { NatsConnection } from 'nats';
|
||||
import { connect, type NatsConnection } from '@nats-io/transport-node';
|
||||
import { SecretModule } from '../secret/secret.module';
|
||||
import { SecretService } from '../secret/secret.service';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
@@ -2,20 +2,21 @@ import { Inject, Injectable, Logger, OnModuleDestroy } from '@nestjs/common';
|
||||
import {
|
||||
AckPolicy,
|
||||
DeliverPolicy,
|
||||
nanos,
|
||||
jetstream,
|
||||
jetstreamManager,
|
||||
ReplayPolicy,
|
||||
RetentionPolicy,
|
||||
StorageType,
|
||||
StringCodec,
|
||||
} from 'nats';
|
||||
import type {
|
||||
ConsumerMessages,
|
||||
JsMsg,
|
||||
Msg,
|
||||
NatsConnection,
|
||||
PubAck,
|
||||
Subscription,
|
||||
} from 'nats';
|
||||
type ConsumerMessages,
|
||||
type JsMsg,
|
||||
type PubAck,
|
||||
} from '@nats-io/jetstream';
|
||||
import {
|
||||
nanos,
|
||||
type Msg,
|
||||
type NatsConnection,
|
||||
type Subscription,
|
||||
} from '@nats-io/transport-node';
|
||||
import { NATS_CLIENT } from './nats.constants';
|
||||
|
||||
export type NatsMessageHandler<T = unknown> = (
|
||||
@@ -64,7 +65,6 @@ const JET_STREAM_CONSUMER_RESTART_DELAY_MILLISECONDS = 1_000;
|
||||
@Injectable()
|
||||
export class NatsService implements OnModuleDestroy {
|
||||
private readonly logger = new Logger(NatsService.name);
|
||||
private readonly stringCodec = StringCodec();
|
||||
private readonly subscriptions = new Set<Subscription>();
|
||||
private readonly jetStreamConsumers = new Set<ConsumerMessages>();
|
||||
private isDestroying = false;
|
||||
@@ -108,10 +108,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
public async publish<T = unknown>(subject: string, data: T): Promise<void> {
|
||||
this.natsClient.publish(
|
||||
subject,
|
||||
this.stringCodec.encode(JSON.stringify(data)),
|
||||
);
|
||||
this.natsClient.publish(subject, JSON.stringify(data));
|
||||
await this.natsClient.flush();
|
||||
}
|
||||
|
||||
@@ -133,19 +130,16 @@ export class NatsService implements OnModuleDestroy {
|
||||
data: T,
|
||||
options?: { messageId?: string; timeoutMs?: number },
|
||||
): Promise<PubAck> {
|
||||
const ack = await this.natsClient
|
||||
.jetstream()
|
||||
.publish(subject, this.stringCodec.encode(JSON.stringify(data)), {
|
||||
msgID: options?.messageId,
|
||||
timeout: options?.timeoutMs ?? 5000,
|
||||
});
|
||||
return ack;
|
||||
return jetstream(this.natsClient).publish(subject, JSON.stringify(data), {
|
||||
msgID: options?.messageId,
|
||||
timeout: options?.timeoutMs ?? 5000,
|
||||
});
|
||||
}
|
||||
|
||||
public async ensureJetStreamStream(
|
||||
options: JetStreamStreamOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const manager = await jetstreamManager(this.natsClient);
|
||||
const config = {
|
||||
name: options.name,
|
||||
subjects: options.subjects,
|
||||
@@ -173,7 +167,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
public async ensureJetStreamConsumer(
|
||||
options: JetStreamConsumerOptions,
|
||||
): Promise<void> {
|
||||
const manager = await this.natsClient.jetstreamManager();
|
||||
const manager = await jetstreamManager(this.natsClient);
|
||||
const config = {
|
||||
durable_name: options.durable,
|
||||
name: options.durable,
|
||||
@@ -206,9 +200,10 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
while (!this.isDestroying) {
|
||||
try {
|
||||
const consumer = await this.natsClient
|
||||
.jetstream()
|
||||
.consumers.get(options.stream, options.durable);
|
||||
const consumer = await jetstream(this.natsClient).consumers.get(
|
||||
options.stream,
|
||||
options.durable,
|
||||
);
|
||||
const messages = await consumer.consume({
|
||||
max_messages: options.maxMessages ?? 10,
|
||||
expires: options.expiresMs ?? 30000,
|
||||
@@ -263,8 +258,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
const decoded = this.stringCodec.decode(msg.data);
|
||||
data = JSON.parse(decoded) as T;
|
||||
data = msg.json<T>();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Failed to decode NATS message on subject="${msg.subject}": ${
|
||||
@@ -292,7 +286,7 @@ export class NatsService implements OnModuleDestroy {
|
||||
): Promise<void> {
|
||||
let data: T;
|
||||
try {
|
||||
data = JSON.parse(msg.string()) as T;
|
||||
data = msg.json<T>();
|
||||
} catch (err) {
|
||||
this.logger.warn(
|
||||
`Terminating undecodable JetStream message subject="${msg.subject}" stream="${options.stream}": ${
|
||||
|
||||
@@ -56,6 +56,7 @@ export class MatchHistoryController {
|
||||
@Query('seasonId') seasonId?: string,
|
||||
@Query('championId') championId?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('lane') lane?: string,
|
||||
) {
|
||||
return this.matchHistoryService.getRecentSummary({
|
||||
communityId,
|
||||
@@ -66,6 +67,7 @@ export class MatchHistoryController {
|
||||
seasonId,
|
||||
championId: this.toNumber(championId),
|
||||
limit: this.toNumber(limit),
|
||||
lane,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -82,6 +84,8 @@ export class MatchHistoryController {
|
||||
@Query('championId') championId?: string,
|
||||
@Query('limit') limit?: string,
|
||||
@Query('cursor') cursor?: string,
|
||||
@Query('lane') lane?: string,
|
||||
@Query('includePositionCounts') includePositionCounts?: string,
|
||||
) {
|
||||
return this.matchHistoryService.getRecentMatches({
|
||||
communityId,
|
||||
@@ -93,6 +97,8 @@ export class MatchHistoryController {
|
||||
championId: this.toNumber(championId),
|
||||
limit: this.toNumber(limit),
|
||||
cursor: this.toNumber(cursor),
|
||||
lane,
|
||||
includePositionCounts: includePositionCounts === 'true',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -5,6 +5,72 @@ import { MatchHistoryService } from './match-history.service';
|
||||
const SEASON_START = Date.parse('2026-01-01T00:00:00Z');
|
||||
|
||||
describe('MatchHistoryService champion filtering', () => {
|
||||
it('selects a lane before limiting and uses only the requested participant, including legacy individualPosition', async () => {
|
||||
const { service, scope, find } = createHarness();
|
||||
const result = await service.getRecentMatches({
|
||||
...scope,
|
||||
filters: { rank: 'solo', lane: 'MIDDLE', limit: 20 },
|
||||
});
|
||||
expect(result.matches.map((game) => game.matchId)).toEqual([
|
||||
'KR_3',
|
||||
'KR_2',
|
||||
'KR_1',
|
||||
]);
|
||||
expect(result.matches.every((game) => game.teamPosition === 'MIDDLE')).toBe(
|
||||
true,
|
||||
);
|
||||
expect(result.matches[0].damageShare).toBe(100);
|
||||
expect(find.mock.calls[0][0]['raw.info.participants']?.$elemMatch).toEqual({
|
||||
puuid: 'player',
|
||||
$or: [
|
||||
{ teamPosition: 'MIDDLE' },
|
||||
{ teamPosition: { $in: ['', null] }, individualPosition: 'MIDDLE' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('combines champion and lane filtering and rejects invalid lanes', async () => {
|
||||
const { service, scope } = createHarness();
|
||||
const result = await service.getRecentMatches({
|
||||
...scope,
|
||||
filters: { rank: 'solo', championId: 1, lane: 'MIDDLE', limit: 20 },
|
||||
});
|
||||
expect(result.matches).toEqual([]);
|
||||
await expect(
|
||||
service.getRecentMatches({ ...scope, filters: { lane: 'unknown' } }),
|
||||
).rejects.toThrow('Invalid lane');
|
||||
});
|
||||
|
||||
it('counts independent lane windows across the season and caps each at twenty', async () => {
|
||||
const { service, scope, aggregate } = createHarness();
|
||||
const result = await service.getRecentMatches({
|
||||
...scope,
|
||||
filters: {
|
||||
rank: 'solo',
|
||||
lane: 'MIDDLE',
|
||||
limit: 20,
|
||||
includePositionCounts: true,
|
||||
},
|
||||
});
|
||||
expect(result.positionCounts).toEqual({
|
||||
ALL: 20,
|
||||
TOP: 20,
|
||||
JUNGLE: 0,
|
||||
MIDDLE: 3,
|
||||
BOTTOM: 0,
|
||||
UTILITY: 0,
|
||||
});
|
||||
expect(aggregate.mock.calls[0][0][0]).toEqual({
|
||||
$match: {
|
||||
participantPuuids: 'player',
|
||||
queueId: { $in: [420] },
|
||||
gameCreation: { $gte: SEASON_START },
|
||||
},
|
||||
});
|
||||
expect(JSON.stringify(aggregate.mock.calls[0][0])).toContain('$$p.puuid');
|
||||
expect(JSON.stringify(aggregate.mock.calls[0][0])).not.toContain('$limit');
|
||||
});
|
||||
|
||||
it('paginates matching games beyond 120 newer games and excludes opponents using the champion', async () => {
|
||||
const harness = createHarness();
|
||||
const filters = { championId: 99, rank: 'solo', limit: 2 };
|
||||
@@ -77,7 +143,14 @@ interface HistoryQuery {
|
||||
queueId: { $in: number[] };
|
||||
gameCreation?: { $gte?: number; $lt?: number };
|
||||
'raw.info.participants'?: {
|
||||
$elemMatch: { puuid: string; championId: number };
|
||||
$elemMatch: {
|
||||
puuid: string;
|
||||
championId?: number;
|
||||
$or?: Array<{
|
||||
teamPosition: string | { $in: (string | null)[] };
|
||||
individualPosition?: string;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -122,7 +195,18 @@ function createHarness() {
|
||||
row.raw.info.participants.some(
|
||||
(entry) =>
|
||||
entry.puuid === participant.puuid &&
|
||||
entry.championId === participant.championId,
|
||||
(participant.championId === undefined ||
|
||||
entry.championId === participant.championId) &&
|
||||
(!participant.$or ||
|
||||
participant.$or.some((condition) =>
|
||||
typeof condition.teamPosition === 'string'
|
||||
? entry.teamPosition === condition.teamPosition
|
||||
: condition.teamPosition.$in.includes(
|
||||
entry.teamPosition ?? null,
|
||||
) &&
|
||||
entry.individualPosition ===
|
||||
condition.individualPosition,
|
||||
)),
|
||||
)),
|
||||
)
|
||||
.sort((a, b) => b.gameCreation - a.gameCreation)
|
||||
@@ -133,6 +217,15 @@ function createHarness() {
|
||||
};
|
||||
return query;
|
||||
});
|
||||
const aggregate = jest.fn<
|
||||
{ exec: () => Promise<Array<{ _id: string; count: number }>> },
|
||||
[unknown[]]
|
||||
>(() => ({
|
||||
exec: async () => [
|
||||
{ _id: 'TOP', count: 127 },
|
||||
{ _id: 'MIDDLE', count: 3 },
|
||||
],
|
||||
}));
|
||||
const models = {
|
||||
user: {
|
||||
find: () => ({
|
||||
@@ -179,7 +272,7 @@ function createHarness() {
|
||||
}),
|
||||
}),
|
||||
},
|
||||
riotMatch: { find },
|
||||
riotMatch: { find, aggregate },
|
||||
};
|
||||
const connection = {
|
||||
getModel: async (name: keyof typeof models) => models[name],
|
||||
@@ -190,6 +283,7 @@ function createHarness() {
|
||||
find,
|
||||
select,
|
||||
returnedCounts,
|
||||
aggregate,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -198,6 +292,9 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
|
||||
const participant = {
|
||||
puuid: 'player',
|
||||
championId,
|
||||
teamPosition:
|
||||
sequence === 2 ? undefined : championId === 99 ? 'MIDDLE' : 'TOP',
|
||||
individualPosition: championId === 99 ? 'MIDDLE' : 'TOP',
|
||||
teamId: 100,
|
||||
win: true,
|
||||
kills: 5,
|
||||
@@ -229,6 +326,7 @@ function storedMatch(sequence: number, championId: number, queueId = 420) {
|
||||
puuid: 'opponent',
|
||||
teamId: 200,
|
||||
championId: 99,
|
||||
teamPosition: 'MIDDLE',
|
||||
win: false,
|
||||
},
|
||||
],
|
||||
|
||||
@@ -53,6 +53,8 @@ interface MatchFilters {
|
||||
championId?: number;
|
||||
limit?: number;
|
||||
cursor?: number;
|
||||
lane?: string;
|
||||
includePositionCounts?: boolean;
|
||||
}
|
||||
|
||||
interface AggregatedChampion {
|
||||
@@ -183,6 +185,7 @@ export class MatchHistoryService {
|
||||
context,
|
||||
queueIds,
|
||||
championId: params.filters.championId,
|
||||
lane: params.filters.lane,
|
||||
limit,
|
||||
});
|
||||
const views = docs
|
||||
@@ -212,6 +215,7 @@ export class MatchHistoryService {
|
||||
context,
|
||||
queueIds,
|
||||
championId: params.filters.championId,
|
||||
lane: params.filters.lane,
|
||||
limit: limit + 1,
|
||||
cursor: params.filters.cursor,
|
||||
});
|
||||
@@ -223,6 +227,15 @@ export class MatchHistoryService {
|
||||
|
||||
return {
|
||||
matches: page,
|
||||
...(params.filters.includePositionCounts
|
||||
? {
|
||||
positionCounts: await this.getPositionCounts(
|
||||
context,
|
||||
queueIds,
|
||||
params.filters.championId,
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
nextCursor:
|
||||
views.length > limit
|
||||
? (page[page.length - 1]?.gameCreation ?? null)
|
||||
@@ -394,7 +407,14 @@ export class MatchHistoryService {
|
||||
limit: number;
|
||||
cursor?: number;
|
||||
championId?: number;
|
||||
lane?: string;
|
||||
}): Promise<RiotMatchDocument[]> {
|
||||
if (
|
||||
params.lane &&
|
||||
!['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'].includes(params.lane)
|
||||
) {
|
||||
throw new BadRequestException('Invalid lane.');
|
||||
}
|
||||
if (params.queueIds.length === 0) return [];
|
||||
const RiotMatchModel = await this.connectionService.getModel('riotMatch');
|
||||
const gameCreation: Record<string, number> = {};
|
||||
@@ -408,12 +428,25 @@ export class MatchHistoryService {
|
||||
queueId: { $in: params.queueIds },
|
||||
};
|
||||
if (Object.keys(gameCreation).length > 0) query.gameCreation = gameCreation;
|
||||
if (params.championId !== undefined) {
|
||||
if (params.championId !== undefined || params.lane) {
|
||||
// Both conditions must match the same participant, before pagination.
|
||||
query['raw.info.participants'] = {
|
||||
$elemMatch: {
|
||||
puuid: params.context.account.puuid,
|
||||
championId: params.championId,
|
||||
...(params.championId !== undefined
|
||||
? { championId: params.championId }
|
||||
: {}),
|
||||
...(params.lane
|
||||
? {
|
||||
$or: [
|
||||
{ teamPosition: params.lane },
|
||||
{
|
||||
teamPosition: { $in: ['', null] },
|
||||
individualPosition: params.lane,
|
||||
},
|
||||
],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -425,6 +458,74 @@ export class MatchHistoryService {
|
||||
.exec();
|
||||
}
|
||||
|
||||
/** Counts independent position windows, without transferring full match payloads. */
|
||||
private async getPositionCounts(
|
||||
context: HistoryContext,
|
||||
queueIds: number[],
|
||||
championId?: number,
|
||||
): Promise<Record<string, number>> {
|
||||
const model = await this.connectionService.getModel('riotMatch');
|
||||
const rows = await model
|
||||
.aggregate<{ _id: string; count: number }>([
|
||||
{
|
||||
$match: {
|
||||
participantPuuids: context.account.puuid,
|
||||
queueId: { $in: queueIds },
|
||||
...(context.seasonStartedAt
|
||||
? { gameCreation: { $gte: context.seasonStartedAt.getTime() } }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
$project: {
|
||||
participant: {
|
||||
$first: {
|
||||
$filter: {
|
||||
input: '$raw.info.participants',
|
||||
as: 'p',
|
||||
cond: { $eq: ['$$p.puuid', context.account.puuid] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
$match: {
|
||||
participant: { $ne: null },
|
||||
...(championId !== undefined
|
||||
? { 'participant.championId': championId }
|
||||
: {}),
|
||||
},
|
||||
},
|
||||
{
|
||||
$group: {
|
||||
_id: {
|
||||
$cond: [
|
||||
{ $in: [{ $ifNull: ['$participant.teamPosition', ''] }, ['']] },
|
||||
'$participant.individualPosition',
|
||||
'$participant.teamPosition',
|
||||
],
|
||||
},
|
||||
count: { $sum: 1 },
|
||||
},
|
||||
},
|
||||
])
|
||||
.exec();
|
||||
const counts: Record<string, number> = {
|
||||
ALL: Math.min(
|
||||
20,
|
||||
rows.reduce((sum, row) => sum + row.count, 0),
|
||||
),
|
||||
};
|
||||
for (const lane of ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY']) {
|
||||
counts[lane] = Math.min(
|
||||
20,
|
||||
rows.find((row) => row._id === lane)?.count ?? 0,
|
||||
);
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
private async aggregateChampionStats(params: {
|
||||
context: HistoryContext;
|
||||
queueIds: number[];
|
||||
@@ -676,6 +777,7 @@ export class MatchHistoryService {
|
||||
wardsPlaced: participant.wardsPlaced,
|
||||
wardsKilled: participant.wardsKilled,
|
||||
damageDealtToChampions: participant.totalDamageDealtToChampions,
|
||||
damageShare: damageShare * 100,
|
||||
damageTaken: participant.totalDamageTaken,
|
||||
goldEarned: participant.goldEarned,
|
||||
items: [
|
||||
|
||||
@@ -103,6 +103,8 @@ export interface RecentSummaryResponse {
|
||||
}
|
||||
|
||||
export interface RecentMatchesResponse {
|
||||
/** Available games in each independent recent-20 window. */
|
||||
positionCounts?: Record<string, number>;
|
||||
matches: RecentMatchView[];
|
||||
nextCursor: number | null;
|
||||
lastFetchedAt: string | null;
|
||||
@@ -136,8 +138,11 @@ export interface RecentMatchTeamParticipantView {
|
||||
}
|
||||
|
||||
export interface RecentMatchView {
|
||||
/** Player champion damage / team champion damage, as a percentage. */
|
||||
damageShare?: number;
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
internalMatchTitle?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
|
||||
@@ -540,7 +540,7 @@ export class TournamentCodeService {
|
||||
): Promise<MatchDocument[]> {
|
||||
const MatchModel = await this.connectionService.getModel('match');
|
||||
const filter: {
|
||||
status: { $in: string[] };
|
||||
status: { $in: MatchDocument['status'][] };
|
||||
communityId?: mongoose.Types.ObjectId;
|
||||
} = {
|
||||
status: { $in: ['team-built', 'in-progress'] },
|
||||
|
||||
@@ -243,7 +243,7 @@ export class CompetitionOutboxProcessor
|
||||
function leaseFilter(event: ClaimedOutboxEvent) {
|
||||
return {
|
||||
_id: event._id,
|
||||
state: 'pending',
|
||||
state: 'pending' as const,
|
||||
attemptCount: event.attemptCount,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import os from 'node:os';
|
||||
import mongoose from 'mongoose';
|
||||
import { AuctionService } from '../src/modules/auction/auction.service';
|
||||
import { AuctionDurabilityScheduler } from '../src/modules/auction/auction-durability.scheduler';
|
||||
@@ -16,7 +17,7 @@ import {
|
||||
} from '../src/modules/global/database/schema';
|
||||
|
||||
let connection: mongoose.Connection;
|
||||
let models: Record<string, mongoose.Model<any>>;
|
||||
let models: ReturnType<typeof createModels>;
|
||||
const redis = {
|
||||
acquireTokenLock: async () => true,
|
||||
releaseTokenLock: async () => true,
|
||||
@@ -27,19 +28,8 @@ const redis = {
|
||||
}),
|
||||
};
|
||||
|
||||
beforeAll(async () => {
|
||||
if (
|
||||
process.env.MONGO_TEST_ISOLATED !== '1' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
|
||||
)
|
||||
throw new Error('Use test:mongodb with an isolated local replica set.');
|
||||
connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, {
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
})
|
||||
.asPromise();
|
||||
models = {
|
||||
function createModels(connection: mongoose.Connection) {
|
||||
return {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
auctionHistory: connection.model(
|
||||
@@ -56,12 +46,29 @@ beforeAll(async () => {
|
||||
AuctionBidRecordSchema,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
if (
|
||||
process.env.MONGO_TEST_ISOLATED !== '1' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith('mongodb://127.0.0.1:')
|
||||
)
|
||||
throw new Error('Use test:mongodb with an isolated local replica set.');
|
||||
connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, {
|
||||
autoIndex: false,
|
||||
autoCreate: false,
|
||||
// NODE-7832: the driver's default OS adapter breaks the Jest handshake.
|
||||
runtimeAdapters: { os },
|
||||
})
|
||||
.asPromise();
|
||||
models = createModels(connection);
|
||||
await Promise.all(
|
||||
Object.values(models).map((model) => model.createCollection()),
|
||||
);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await Promise.all(Object.values(models).map((model) => model.deleteMany({})));
|
||||
await Promise.all(Object.values(models).map((model) => model.deleteMany()));
|
||||
});
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
afterAll(async () => {
|
||||
@@ -84,7 +91,6 @@ async function fixture(reserved: boolean) {
|
||||
participants: [],
|
||||
tournamentCodeIds: reserved ? [codeId] : [],
|
||||
gameSchedule: [],
|
||||
__v: 0,
|
||||
});
|
||||
await models.auction.collection.insertOne({
|
||||
_id: auctionId,
|
||||
@@ -104,7 +110,7 @@ async function fixture(reserved: boolean) {
|
||||
matchId,
|
||||
});
|
||||
const database = {
|
||||
getModel: async (name: string) => models[name],
|
||||
getModel: async (name: keyof typeof models) => models[name],
|
||||
createSession: () => connection.startSession(),
|
||||
};
|
||||
const codes = new TournamentCodeService(database as never, redis as never);
|
||||
@@ -611,10 +617,7 @@ it('reads an uncommitted Match in the provided session when cancelling polling b
|
||||
{ session },
|
||||
);
|
||||
expect(await models.match.findById(created._id)).toBeNull();
|
||||
await f.results.cancelPolling(
|
||||
created._id as mongoose.Types.ObjectId,
|
||||
session,
|
||||
);
|
||||
await f.results.cancelPolling(created._id, session);
|
||||
expect(
|
||||
await models.match.findById(created._id).session(session),
|
||||
).not.toBeNull();
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
* text eol=lf
|
||||
@@ -0,0 +1 @@
|
||||
results/
|
||||
@@ -0,0 +1,13 @@
|
||||
FROM node:26-bookworm-slim
|
||||
RUN npm install --global pnpm@10.4.1
|
||||
WORKDIR /workspace
|
||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||
COPY packages/contracts ./packages/contracts
|
||||
COPY apps/api/package.json ./apps/api/package.json
|
||||
COPY apps/web/package.json ./apps/web/package.json
|
||||
RUN pnpm install --frozen-lockfile --filter api --filter web --ignore-scripts
|
||||
COPY apps/api ./apps/api
|
||||
COPY apps/web/src/api ./apps/web/src/api
|
||||
WORKDIR /workspace/apps/api
|
||||
ENV NODE_ENV=test NEW_RELIC_ENABLED=false
|
||||
CMD ["node", "-r", "ts-node/register/transpile-only", "test/auction-cluster/node.ts"]
|
||||
@@ -0,0 +1,61 @@
|
||||
x-app: &app
|
||||
image: ${COMPOSE_PROJECT_NAME}-app
|
||||
build:
|
||||
context: ../../../..
|
||||
dockerfile: apps/api/test/auction-cluster/Dockerfile
|
||||
environment: &environment
|
||||
MONGO_TEST_URL: mongodb://mongo:27017/auction_cluster?replicaSet=auction_cluster
|
||||
REDIS_TEST_URL: redis://redis-proxy:6379
|
||||
NODE_ENV: test
|
||||
NEW_RELIC_ENABLED: 'false'
|
||||
volumes:
|
||||
- ./results:/results
|
||||
networks: [cluster]
|
||||
mem_limit: 1g
|
||||
|
||||
services:
|
||||
redis:
|
||||
image: redis:8-alpine
|
||||
command: [redis-server, --save, '', --appendonly, 'no']
|
||||
networks: [cluster]
|
||||
mem_limit: 256m
|
||||
mongo:
|
||||
# MongoDB 8+ refuses the test host's Linux 7.0.0 kernel (SERVER-121912).
|
||||
image: ${MONGO_TEST_IMAGE:-mongo:7.0}
|
||||
command:
|
||||
[
|
||||
mongod,
|
||||
--replSet,
|
||||
auction_cluster,
|
||||
--bind_ip_all,
|
||||
--wiredTigerCacheSizeGB,
|
||||
'0.25',
|
||||
]
|
||||
networks: [cluster]
|
||||
mem_limit: 768m
|
||||
redis-proxy:
|
||||
<<: *app
|
||||
command: [node, test/auction-cluster/fault-proxy.mjs]
|
||||
mem_limit: 128m
|
||||
api-a:
|
||||
<<: *app
|
||||
environment:
|
||||
<<: *environment
|
||||
CLUSTER_NODE: api-a
|
||||
api-b:
|
||||
<<: *app
|
||||
environment:
|
||||
<<: *environment
|
||||
CLUSTER_NODE: api-b
|
||||
lb:
|
||||
image: nginx:stable-alpine
|
||||
volumes:
|
||||
- ./nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
networks: [cluster]
|
||||
mem_limit: 128m
|
||||
runner:
|
||||
<<: *app
|
||||
command: [node, test/auction-cluster/run.mjs, verify]
|
||||
|
||||
networks:
|
||||
cluster: {}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { createServer as createTcpServer, connect } from 'node:net';
|
||||
import { createServer as createHttpServer } from 'node:http';
|
||||
|
||||
// Real TCP connections; only connections issuing SUBSCRIBE/PSUBSCRIBE are cut.
|
||||
// Redis commands, TIME and PUBLISH continue through the same proxy.
|
||||
let blocked = false;
|
||||
let dropped = 0;
|
||||
const connections = new Set();
|
||||
createTcpServer((socket) => {
|
||||
const upstream = connect(6379, 'redis');
|
||||
const connection = { socket, upstream, subscriber: false, prefix: '' };
|
||||
connections.add(connection);
|
||||
const close = () => {
|
||||
socket.destroy();
|
||||
upstream.destroy();
|
||||
connections.delete(connection);
|
||||
};
|
||||
socket.on('error', close);
|
||||
upstream.on('error', close);
|
||||
socket.on('close', close);
|
||||
upstream.on('close', close);
|
||||
socket.on('data', (chunk) => {
|
||||
connection.prefix = (connection.prefix + chunk.toString('utf8')).slice(
|
||||
-4096,
|
||||
);
|
||||
if (/\r\n(?:p?subscribe|ssubscribe)\r\n/i.test(connection.prefix)) {
|
||||
connection.subscriber = true;
|
||||
}
|
||||
if (blocked && connection.subscriber) {
|
||||
dropped += 1;
|
||||
close();
|
||||
} else upstream.write(chunk);
|
||||
});
|
||||
upstream.on('data', (chunk) => socket.write(chunk));
|
||||
}).listen(6379, '0.0.0.0');
|
||||
|
||||
createHttpServer((request, response) => {
|
||||
if (request.method === 'POST' && request.url === '/block') {
|
||||
blocked = true;
|
||||
for (const connection of connections) {
|
||||
if (!connection.subscriber) continue;
|
||||
dropped += 1;
|
||||
connection.socket.destroy();
|
||||
connection.upstream.destroy();
|
||||
}
|
||||
} else if (request.method === 'POST' && request.url === '/restore') {
|
||||
blocked = false;
|
||||
} else if (request.url !== '/status') {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader('content-type', 'application/json');
|
||||
response.end(
|
||||
JSON.stringify({
|
||||
blocked,
|
||||
dropped,
|
||||
subscribers: [...connections].filter((c) => c.subscriber).length,
|
||||
}),
|
||||
);
|
||||
}).listen(8081, '0.0.0.0');
|
||||
@@ -0,0 +1,18 @@
|
||||
events {}
|
||||
http {
|
||||
upstream auction {
|
||||
server api-a:3000;
|
||||
server api-b:3000;
|
||||
}
|
||||
server {
|
||||
listen 8080;
|
||||
location / {
|
||||
proxy_pass http://auction;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection "upgrade";
|
||||
proxy_read_timeout 120s;
|
||||
add_header X-Cluster-Upstream $upstream_addr always;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import 'reflect-metadata';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { Body, Controller, Get, Module, Post } from '@nestjs/common';
|
||||
import { NestFactory } from '@nestjs/core';
|
||||
import mongoose from 'mongoose';
|
||||
import { createClient } from 'redis';
|
||||
import type { Namespace } from 'socket.io';
|
||||
import { RedisIoAdapter } from '../../src/redis-io.adapter';
|
||||
import { AuctionController } from '../../src/modules/auction/auction.controller';
|
||||
import { AuctionGateway } from '../../src/modules/auction/auction.gateway';
|
||||
import { AuctionEventBusService } from '../../src/modules/auction/auction-event-bus.service';
|
||||
import { AuctionService } from '../../src/modules/auction/auction.service';
|
||||
import { AuctionBidArchiveService } from '../../src/modules/auction/auction-bid-archive.service';
|
||||
import {
|
||||
AuctionDurabilityScheduler,
|
||||
type AuctionDurabilityPayload,
|
||||
} from '../../src/modules/auction/auction-durability.scheduler';
|
||||
import { AuctionRedisService } from '../../src/modules/auction/redis/auction-redis.service';
|
||||
import { AuctionRedisCommandService } from '../../src/modules/auction/redis/auction-redis-command.service';
|
||||
import { AuctionRedisStateReaderService } from '../../src/modules/auction/redis/auction-redis-state-reader.service';
|
||||
import { AuthService } from '../../src/modules/auth/auth.service';
|
||||
import { JwtService } from '../../src/modules/auth/jwt.service';
|
||||
import { IdentityService } from '../../src/modules/auth/identity.service';
|
||||
import { ConnectionService } from '../../src/modules/global/database/connection.service';
|
||||
import {
|
||||
AuctionSchema,
|
||||
AuctionHistoryEntrySchema,
|
||||
AuctionSideEffectApplicationSchema,
|
||||
MatchSchema,
|
||||
} from '../../src/modules/global/database/schema';
|
||||
|
||||
async function bootstrap() {
|
||||
if (
|
||||
!process.env.MONGO_TEST_URL?.startsWith(
|
||||
'mongodb://mongo:27017/auction_cluster?',
|
||||
) ||
|
||||
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379'
|
||||
) {
|
||||
throw new Error(
|
||||
'This test node only accepts the isolated Compose services.',
|
||||
);
|
||||
}
|
||||
const fixture = JSON.parse(
|
||||
await readFile('/results/fixture.json', 'utf8'),
|
||||
) as { communityId: string };
|
||||
const connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
|
||||
.asPromise();
|
||||
const models = {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
auctionHistory: connection.model(
|
||||
'auctionHistory',
|
||||
AuctionHistoryEntrySchema,
|
||||
),
|
||||
auctionSideEffectApplication: connection.model(
|
||||
'auctionSideEffectApplication',
|
||||
AuctionSideEffectApplicationSchema,
|
||||
),
|
||||
};
|
||||
let releaseCommit: (() => void) | undefined;
|
||||
let commitGate: Promise<void> | undefined;
|
||||
let commitsWaiting = 0;
|
||||
const database = {
|
||||
getModel: async (name: keyof typeof models) => {
|
||||
if (!models[name]) throw new Error(`Unexpected test model: ${name}`);
|
||||
return models[name];
|
||||
},
|
||||
createSession: async () => {
|
||||
const session = await connection.startSession();
|
||||
const commit = session.commitTransaction.bind(session);
|
||||
session.commitTransaction = async () => {
|
||||
if (commitGate) {
|
||||
commitsWaiting += 1;
|
||||
await commitGate;
|
||||
commitsWaiting -= 1;
|
||||
}
|
||||
await commit();
|
||||
};
|
||||
return session;
|
||||
},
|
||||
};
|
||||
const client = createClient({ url: process.env.REDIS_TEST_URL });
|
||||
client.on('error', (error) =>
|
||||
console.error('command-client:', error.message),
|
||||
);
|
||||
await client.connect();
|
||||
const redis = new AuctionRedisService(client);
|
||||
const commands = new AuctionRedisCommandService(redis);
|
||||
const reader = new AuctionRedisStateReaderService(redis);
|
||||
const bus = new AuctionEventBusService();
|
||||
const service = new AuctionService(
|
||||
database as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
redis,
|
||||
commands,
|
||||
reader,
|
||||
bus,
|
||||
);
|
||||
// Explicit draining lets the test hold real Mongo commits and reorder durable
|
||||
// payloads; no in-memory database or fake Redis adapter is involved.
|
||||
const scheduler = new AuctionDurabilityScheduler(
|
||||
database as never,
|
||||
redis,
|
||||
undefined,
|
||||
undefined,
|
||||
undefined,
|
||||
bus,
|
||||
reader,
|
||||
service,
|
||||
);
|
||||
|
||||
@Controller('_cluster')
|
||||
class ControlController {
|
||||
@Get('health') health() {
|
||||
const namespace = Reflect.get(gateway, 'server') as Namespace;
|
||||
return {
|
||||
node: process.env.CLUSTER_NODE,
|
||||
sockets: [...namespace.sockets.keys()],
|
||||
pid: process.pid,
|
||||
commitsWaiting,
|
||||
};
|
||||
}
|
||||
@Post('hold-commit') hold() {
|
||||
if (commitGate) throw new Error('Commit already held');
|
||||
commitGate = new Promise<void>((resolve) => {
|
||||
releaseCommit = resolve;
|
||||
});
|
||||
return { held: true };
|
||||
}
|
||||
@Post('release-commit') release() {
|
||||
releaseCommit?.();
|
||||
commitGate = undefined;
|
||||
releaseCommit = undefined;
|
||||
return { released: true };
|
||||
}
|
||||
@Post('drain') drain() {
|
||||
return scheduler.processDueDurabilityPayloads(100);
|
||||
}
|
||||
@Post('apply') async apply(@Body() payload: AuctionDurabilityPayload) {
|
||||
await scheduler.applyDurabilityPayload(payload);
|
||||
return { applied: true };
|
||||
}
|
||||
}
|
||||
@Module({
|
||||
controllers: [AuctionController, ControlController],
|
||||
providers: [
|
||||
AuctionGateway,
|
||||
{ provide: AuctionService, useValue: service },
|
||||
{ provide: ConnectionService, useValue: database },
|
||||
{ provide: AuctionRedisService, useValue: redis },
|
||||
{ provide: AuctionEventBusService, useValue: bus },
|
||||
{ provide: AuctionBidArchiveService, useValue: {} },
|
||||
{
|
||||
provide: AuthService,
|
||||
useValue: { resolveDevUserById: async () => null },
|
||||
},
|
||||
{ provide: JwtService, useValue: {} },
|
||||
{ provide: IdentityService, useValue: {} },
|
||||
],
|
||||
})
|
||||
class TestModule {}
|
||||
const app = await NestFactory.create(TestModule, {
|
||||
logger: ['error', 'warn'],
|
||||
});
|
||||
// Identity-provider authentication is outside this transport/durability test.
|
||||
// The real controller's RolesGuard still checks this isolated fixture admin.
|
||||
app.use(
|
||||
(
|
||||
request: { user?: unknown },
|
||||
response: { setHeader(name: string, value: string): void },
|
||||
next: () => void,
|
||||
) => {
|
||||
request.user = {
|
||||
role: 'admin',
|
||||
communityId: new mongoose.Types.ObjectId(fixture.communityId),
|
||||
};
|
||||
response.setHeader(
|
||||
'X-Cluster-Node',
|
||||
process.env.CLUSTER_NODE ?? 'unknown',
|
||||
);
|
||||
next();
|
||||
},
|
||||
);
|
||||
const adapter = new RedisIoAdapter(app);
|
||||
await adapter.connectToRedis();
|
||||
app.useWebSocketAdapter(adapter);
|
||||
const gateway = app.get(AuctionGateway);
|
||||
await app.listen(3000, '0.0.0.0');
|
||||
console.log(`cluster node ready: ${process.env.CLUSTER_NODE}`);
|
||||
process.on('SIGTERM', () => {
|
||||
void app
|
||||
.close()
|
||||
.then(() => connection.close())
|
||||
.then(() => process.exit(0));
|
||||
});
|
||||
}
|
||||
void bootstrap().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
@@ -0,0 +1,641 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRequire } from 'node:module';
|
||||
import { readFile, writeFile } from 'node:fs/promises';
|
||||
import { request } from 'node:http';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import mongoose from 'mongoose';
|
||||
import { createClient } from 'redis';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
require('ts-node/register/transpile-only');
|
||||
const {
|
||||
AuctionRedisService,
|
||||
} = require('../../src/modules/auction/redis/auction-redis.service.ts');
|
||||
const {
|
||||
AuctionRedisCommandService,
|
||||
} = require('../../src/modules/auction/redis/auction-redis-command.service.ts');
|
||||
const {
|
||||
AUCTION_DURABILITY_RETRY_QUEUE_KEY,
|
||||
} = require('../../src/modules/auction/redis/auction-redis.keys.ts');
|
||||
const {
|
||||
MatchSchema,
|
||||
AuctionSchema,
|
||||
AuctionHistoryEntrySchema,
|
||||
AuctionSideEffectApplicationSchema,
|
||||
} = require('../../src/modules/global/database/schema.ts');
|
||||
const webRequire = createRequire(
|
||||
new URL('../../../web/package.json', import.meta.url),
|
||||
);
|
||||
const { io } = webRequire('socket.io-client');
|
||||
const { QueryClient, QueryObserver, environmentManager } = webRequire(
|
||||
'@tanstack/react-query',
|
||||
);
|
||||
const {
|
||||
createAuctionHeartbeatMonitor,
|
||||
shouldApplyPolledAuctionState,
|
||||
mergeAuctionState,
|
||||
} = await import('../../../web/src/api/auction-state.ts');
|
||||
const { createAuctionResyncRequester } =
|
||||
await import('../../../web/src/api/auction-resync.ts');
|
||||
const { AUCTION_SAFETY_POLL_INTERVAL_MS } =
|
||||
await import('../../../web/src/api/auction-polling.ts');
|
||||
|
||||
if (
|
||||
process.env.REDIS_TEST_URL !== 'redis://redis-proxy:6379' ||
|
||||
!process.env.MONGO_TEST_URL?.startsWith(
|
||||
'mongodb://mongo:27017/auction_cluster?',
|
||||
)
|
||||
) {
|
||||
throw new Error('Only the isolated Compose services are allowed.');
|
||||
}
|
||||
const redis = createClient({ url: 'redis://redis:6379' });
|
||||
redis.on('error', () => {});
|
||||
await redis.connect();
|
||||
const cleanup = [() => (redis.isOpen ? redis.quit() : undefined)];
|
||||
const report = {
|
||||
startedAt: new Date().toISOString(),
|
||||
checks: [],
|
||||
requests: [],
|
||||
limitation:
|
||||
'Real API processes, Nginx, Redis TCP faults and Mongo transactions; fixture identity replaces the external login provider. Client recovery uses production helpers and QueryObserver, without rendering the React page.',
|
||||
};
|
||||
|
||||
async function until(check, description, timeout = 15_000) {
|
||||
const deadline = Date.now() + timeout;
|
||||
let lastError;
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
const value = await check();
|
||||
if (value) return value;
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
}
|
||||
await delay(50);
|
||||
}
|
||||
throw new Error(
|
||||
`Timed out: ${description}${lastError ? `: ${lastError.message}` : ''}`,
|
||||
);
|
||||
}
|
||||
async function http(url, body) {
|
||||
const started = Date.now();
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request(
|
||||
url,
|
||||
{
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
agent: false,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
},
|
||||
(res) => {
|
||||
let data = '';
|
||||
res.on('data', (chunk) => {
|
||||
data += chunk;
|
||||
});
|
||||
res.on('end', () => {
|
||||
report.requests.push({
|
||||
url,
|
||||
node: res.headers['x-cluster-node'],
|
||||
status: res.statusCode,
|
||||
durationMS: Date.now() - started,
|
||||
});
|
||||
if (res.statusCode < 200 || res.statusCode >= 300)
|
||||
return reject(new Error(`${url}: ${res.statusCode} ${data}`));
|
||||
try {
|
||||
resolve({
|
||||
body: JSON.parse(data),
|
||||
node: res.headers['x-cluster-node'],
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
req.setTimeout(10_000, () =>
|
||||
req.destroy(new Error(`HTTP timeout: ${url}`)),
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end(body === undefined ? undefined : JSON.stringify(body));
|
||||
});
|
||||
}
|
||||
const pass = (name, details = {}) => {
|
||||
report.checks.push({ name, passed: true, ...details });
|
||||
console.log(`PASS ${name} ${JSON.stringify(details)}`);
|
||||
};
|
||||
|
||||
async function initialize() {
|
||||
const admin = new mongoose.mongo.MongoClient(
|
||||
'mongodb://mongo:27017/?directConnection=true',
|
||||
{ serverSelectionTimeoutMS: 1000 },
|
||||
);
|
||||
await until(
|
||||
async () => {
|
||||
await admin.connect();
|
||||
return true;
|
||||
},
|
||||
'Mongo startup',
|
||||
60_000,
|
||||
);
|
||||
await admin.db('admin').command({
|
||||
replSetInitiate: {
|
||||
_id: 'auction_cluster',
|
||||
members: [{ _id: 0, host: 'mongo:27017' }],
|
||||
},
|
||||
});
|
||||
await until(
|
||||
async () =>
|
||||
(await admin.db('admin').command({ hello: 1 })).isWritablePrimary,
|
||||
'Mongo primary',
|
||||
60_000,
|
||||
);
|
||||
const build = await admin.db('admin').command({ buildInfo: 1 });
|
||||
await admin.close();
|
||||
const connection = await mongoose
|
||||
.createConnection(process.env.MONGO_TEST_URL, { autoIndex: false })
|
||||
.asPromise();
|
||||
try {
|
||||
const models = {
|
||||
match: connection.model('match', MatchSchema),
|
||||
auction: connection.model('auction', AuctionSchema),
|
||||
history: connection.model('auctionHistory', AuctionHistoryEntrySchema),
|
||||
sideEffects: connection.model(
|
||||
'auctionSideEffectApplication',
|
||||
AuctionSideEffectApplicationSchema,
|
||||
),
|
||||
};
|
||||
await Promise.all(
|
||||
Object.values(models).map((model) => model.createCollection()),
|
||||
);
|
||||
await models.history.createIndexes();
|
||||
const matchId = new mongoose.Types.ObjectId(),
|
||||
communityId = new mongoose.Types.ObjectId(),
|
||||
auctionId = new mongoose.Types.ObjectId();
|
||||
const lifecycle = `cluster:${matchId}`;
|
||||
const playerA = new mongoose.Types.ObjectId(),
|
||||
playerB = new mongoose.Types.ObjectId(),
|
||||
captain = new mongoose.Types.ObjectId();
|
||||
const structure = {
|
||||
auctionPlayerOrder: [
|
||||
{ userId: playerA.toString() },
|
||||
{ userId: playerB.toString() },
|
||||
],
|
||||
auctionTeams: [
|
||||
{
|
||||
teamIndex: 1,
|
||||
captainUserId: captain.toString(),
|
||||
remainingBidPointAmount: 1000,
|
||||
members: [],
|
||||
},
|
||||
],
|
||||
currentAuctionPlayerOrderIndex: 0,
|
||||
currentAuctionRound: 1,
|
||||
passedAuctionPlayerQueue: [],
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
bidRoundExtensionSeconds: 5,
|
||||
initialTeamBidPointAmount: 1000,
|
||||
topTierAuctionPriorityThreshold: 'NONE',
|
||||
manualTopTierAuctionPriorityUserIds: [],
|
||||
};
|
||||
await models.match.collection.insertOne({
|
||||
_id: matchId,
|
||||
communityId,
|
||||
title: 'Isolated cluster test',
|
||||
participants: [],
|
||||
teams: [],
|
||||
status: 'team-building',
|
||||
scheduledAt: new Date(),
|
||||
});
|
||||
await models.auction.collection.insertOne({
|
||||
_id: auctionId,
|
||||
matchId,
|
||||
auctionEngineVersion: 'redis-v1',
|
||||
auctionLifecycleId: lifecycle,
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
currentAuctionHistorySequence: 0,
|
||||
chatMessages: [],
|
||||
...structure,
|
||||
});
|
||||
const commands = new AuctionRedisCommandService(
|
||||
new AuctionRedisService(redis),
|
||||
);
|
||||
await commands.hydrateState(matchId.toString(), {
|
||||
matchId: matchId.toString(),
|
||||
auctionLifecycleId: lifecycle,
|
||||
phase: 'presenting',
|
||||
revision: 0,
|
||||
auctionHistorySequence: 0,
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
structureStateJson: JSON.stringify(structure),
|
||||
liveStatePatch: {
|
||||
currentAuctionPlayerOrderIndex: 0,
|
||||
currentBidRoundPlayerUserId: playerA.toString(),
|
||||
currentBidRoundId: 'initial',
|
||||
currentHighestBidPointAmount: 0,
|
||||
currentHighestBidderTeamIndex: -1,
|
||||
maximumBidRoundDurationSeconds: 600,
|
||||
bidRoundExtensionSeconds: 5,
|
||||
'team:1:captainUserId': captain.toString(),
|
||||
'team:1:remainingBidPointAmount': 1000,
|
||||
'team:1:assignedAuctionTeamMemberCount': 1,
|
||||
},
|
||||
});
|
||||
const fixture = {
|
||||
matchId: matchId.toString(),
|
||||
communityId: communityId.toString(),
|
||||
auctionId: auctionId.toString(),
|
||||
lifecycle,
|
||||
mongoVersion: build.version,
|
||||
redisVersion: (await redis.info('server')).match(
|
||||
/redis_version:([^\r\n]+)/,
|
||||
)?.[1],
|
||||
};
|
||||
await writeFile('/results/fixture.json', JSON.stringify(fixture, null, 2));
|
||||
console.log(
|
||||
`Initialized isolated MongoDB ${build.version} and Redis ${fixture.redisVersion}`,
|
||||
);
|
||||
} finally {
|
||||
await connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function verify() {
|
||||
const fixture = JSON.parse(await readFile('/results/fixture.json', 'utf8'));
|
||||
report.versions = {
|
||||
node: process.version,
|
||||
mongo: fixture.mongoVersion,
|
||||
redis: fixture.redisVersion,
|
||||
};
|
||||
const route = `/communities/${fixture.communityId}/matches/${fixture.matchId}/auction`;
|
||||
const url = `http://lb:8080${route}`;
|
||||
await until(
|
||||
async () => (await http('http://api-a:3000/_cluster/health')).body.node,
|
||||
'API A startup',
|
||||
60_000,
|
||||
);
|
||||
await until(
|
||||
async () => (await http('http://api-b:3000/_cluster/health')).body.node,
|
||||
'API B startup',
|
||||
60_000,
|
||||
);
|
||||
const routedNodes = new Set();
|
||||
for (let i = 0; i < 4; i += 1) routedNodes.add((await http(url)).node);
|
||||
assert.deepEqual([...routedNodes].sort(), ['api-a', 'api-b']);
|
||||
pass('Nginx routes real HTTP requests to both API processes');
|
||||
|
||||
async function connectViewer() {
|
||||
const socket = io('http://lb:8080/auction', {
|
||||
transports: ['websocket'],
|
||||
autoConnect: false,
|
||||
reconnection: false,
|
||||
});
|
||||
const viewer = {
|
||||
socket,
|
||||
state: null,
|
||||
states: [],
|
||||
histories: [],
|
||||
errors: [],
|
||||
};
|
||||
socket.on('state', (state) => {
|
||||
viewer.state = state;
|
||||
viewer.states.push(state);
|
||||
});
|
||||
socket.on('error', (error) => viewer.errors.push(error));
|
||||
socket.on('connect_error', (error) => viewer.errors.push(error.message));
|
||||
socket.on('history-updated', (event) => {
|
||||
void http(`${url}/history`)
|
||||
.then(({ body, node }) => viewer.histories.push({ event, body, node }))
|
||||
.catch((error) => viewer.errors.push(error.message));
|
||||
});
|
||||
cleanup.push(() => socket.disconnect());
|
||||
socket.connect();
|
||||
await until(
|
||||
() => socket.connected,
|
||||
`socket connect: ${viewer.errors.join(',')}`,
|
||||
);
|
||||
const ack = await socket
|
||||
.timeout(5000)
|
||||
.emitWithAck('join', { matchId: fixture.matchId });
|
||||
assert.equal(ack.ok, true);
|
||||
assert.equal(viewer.state.matchId, fixture.matchId);
|
||||
assert.equal(viewer.state.auctionEngineVersion, 'redis-v1');
|
||||
const health = await Promise.all(
|
||||
['api-a', 'api-b'].map((node) =>
|
||||
http(`http://${node}:3000/_cluster/health`),
|
||||
),
|
||||
);
|
||||
viewer.node = health.find((entry) =>
|
||||
entry.body.sockets.includes(socket.id),
|
||||
).body.node;
|
||||
return viewer;
|
||||
}
|
||||
const one = await connectViewer(),
|
||||
two = await connectViewer();
|
||||
assert.notEqual(one.node, two.node);
|
||||
const a = one.node === 'api-a' ? one : two;
|
||||
const b = one.node === 'api-b' ? one : two;
|
||||
const initialRevision = a.state.revision;
|
||||
const revisionFor = (sequence) => initialRevision + sequence;
|
||||
assert.equal(b.state.revision, initialRevision);
|
||||
pass('WebSocket viewers join different nodes through Nginx', {
|
||||
nodes: [one.node, two.node],
|
||||
});
|
||||
|
||||
const sequences = async () =>
|
||||
(await http(`${url}/history`)).body.map((entry) => entry.sequence);
|
||||
const action = async (viewer, name) => {
|
||||
const ack = await viewer.socket
|
||||
.timeout(5000)
|
||||
.emitWithAck(name, { auctionActionRequestId: randomUUID() });
|
||||
assert.equal(ack.ok, true, JSON.stringify(ack));
|
||||
};
|
||||
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
|
||||
await action(a, 'open-bidding');
|
||||
await until(
|
||||
() =>
|
||||
a.state.revision === revisionFor(1) &&
|
||||
b.state.revision === revisionFor(1),
|
||||
'cross-node full state',
|
||||
);
|
||||
assert.equal(a.histories.length + b.histories.length, 0);
|
||||
await http('http://api-a:3000/_cluster/hold-commit', {});
|
||||
const pendingDrain = http('http://api-a:3000/_cluster/drain', {});
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://api-a:3000/_cluster/health')).body.commitsWaiting ===
|
||||
1,
|
||||
'real Mongo commit barrier',
|
||||
);
|
||||
for (let i = 0; i < 4; i += 1) assert.deepEqual(await sequences(), []);
|
||||
assert.equal(a.histories.length + b.histories.length, 0);
|
||||
await http('http://api-a:3000/_cluster/release-commit', {});
|
||||
assert.equal((await pendingDrain).body.applied, 1);
|
||||
await until(
|
||||
() => a.histories.length === 1 && b.histories.length === 1,
|
||||
'post-commit history event on both nodes',
|
||||
);
|
||||
for (const viewer of [a, b])
|
||||
assert.deepEqual(
|
||||
viewer.histories[0].body.map((entry) => entry.sequence),
|
||||
[1],
|
||||
);
|
||||
pass(
|
||||
'History notification crosses nodes only after a real Mongo transaction commits',
|
||||
);
|
||||
|
||||
await action(a, 'passed');
|
||||
await action(b, 'next');
|
||||
await until(
|
||||
() =>
|
||||
a.state.revision === revisionFor(3) &&
|
||||
b.state.revision === revisionFor(3),
|
||||
'state fanout in both directions',
|
||||
);
|
||||
const keys = await redis.zRange(AUCTION_DURABILITY_RETRY_QUEUE_KEY, 0, -1);
|
||||
const queued = await Promise.all(
|
||||
keys.map(async (key) => ({
|
||||
key,
|
||||
payload: JSON.parse(await redis.hGet(key, 'payloadJson')),
|
||||
})),
|
||||
);
|
||||
const third = queued.find(
|
||||
({ payload }) => payload.auctionHistorySequence === 3,
|
||||
);
|
||||
const second = queued.find(
|
||||
({ payload }) => payload.auctionHistorySequence === 2,
|
||||
);
|
||||
assert.ok(third && second);
|
||||
await http('http://api-b:3000/_cluster/apply', third.payload);
|
||||
assert.deepEqual(await sequences(), [3, 1]);
|
||||
const previousEvents = b.histories.length;
|
||||
await http('http://api-a:3000/_cluster/apply', second.payload);
|
||||
await until(
|
||||
() =>
|
||||
b.histories.length > previousEvents &&
|
||||
b.histories.at(-1).body.some((entry) => entry.sequence === 2),
|
||||
'late append history refresh',
|
||||
);
|
||||
assert.deepEqual(await sequences(), [3, 2, 1]);
|
||||
for (const item of queued) {
|
||||
await redis.zRem(AUCTION_DURABILITY_RETRY_QUEUE_KEY, item.key);
|
||||
await redis.del(item.key);
|
||||
}
|
||||
pass(
|
||||
'A delayed history append refreshes another node with the same maximum sequence',
|
||||
{ maximumSequence: 3 },
|
||||
);
|
||||
|
||||
const undo = await http(`${url}/undo`, {
|
||||
sequence: 1,
|
||||
auctionActionRequestId: randomUUID(),
|
||||
});
|
||||
assert.equal(undo.body.auctionEngineVersion, 'redis-v1');
|
||||
assert.equal(undo.body.revision, revisionFor(4));
|
||||
assert.deepEqual(await sequences(), [3, 2, 1]);
|
||||
await http('http://api-b:3000/_cluster/drain', {});
|
||||
await until(
|
||||
async () => JSON.stringify(await sequences()) === '[4,1]',
|
||||
'durable Undo history',
|
||||
);
|
||||
await until(
|
||||
() => b.histories.at(-1)?.body[0]?.sequence === 4,
|
||||
'Undo history event',
|
||||
);
|
||||
pass('Undo increases sequence and replaces history on every node', {
|
||||
sequence: 4,
|
||||
history: [4, 1],
|
||||
});
|
||||
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
|
||||
'Redis subscriptions',
|
||||
);
|
||||
await http('http://redis-proxy:8081/block', {});
|
||||
console.log(
|
||||
'FAULT Pub/Sub TCP connections blocked; Redis commands and HTTP stay available',
|
||||
);
|
||||
await delay(500);
|
||||
assert.equal(
|
||||
(await http('http://api-a:3000/_cluster/health')).body.node,
|
||||
'api-a',
|
||||
);
|
||||
assert.equal(
|
||||
(await http('http://api-b:3000/_cluster/health')).body.node,
|
||||
'api-b',
|
||||
);
|
||||
assert.equal(a.socket.connected && b.socket.connected, true);
|
||||
const timestamp = await b.socket
|
||||
.timeout(3000)
|
||||
.emitWithAck('time-sync', { sequence: 1 });
|
||||
assert.equal(timestamp.ok, true);
|
||||
pass(
|
||||
'Both API processes and socket clock sync survive Pub/Sub-only TCP disconnection',
|
||||
);
|
||||
|
||||
environmentManager.setIsServer(() => false);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false, gcTime: Infinity } },
|
||||
});
|
||||
cleanup.push(() => queryClient.clear());
|
||||
let stateByHttp = b.state,
|
||||
historyByHttp,
|
||||
statePolls = 0,
|
||||
historyPolls = 0;
|
||||
const pollingStarted = Date.now();
|
||||
const stateObserver = new QueryObserver(queryClient, {
|
||||
queryKey: ['auction', fixture.matchId],
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
queryFn: async () => {
|
||||
statePolls += 1;
|
||||
return (await http(url)).body;
|
||||
},
|
||||
});
|
||||
const historyObserver = new QueryObserver(queryClient, {
|
||||
queryKey: ['auction-history', fixture.matchId],
|
||||
refetchInterval: AUCTION_SAFETY_POLL_INTERVAL_MS,
|
||||
queryFn: async () => {
|
||||
historyPolls += 1;
|
||||
return (await http(`${url}/history`)).body;
|
||||
},
|
||||
});
|
||||
cleanup.push(
|
||||
stateObserver.subscribe((result) => {
|
||||
if (
|
||||
result.data &&
|
||||
shouldApplyPolledAuctionState(stateByHttp, result.data, fixture.matchId)
|
||||
)
|
||||
stateByHttp = mergeAuctionState(stateByHttp, result.data);
|
||||
}),
|
||||
);
|
||||
cleanup.push(
|
||||
historyObserver.subscribe((result) => {
|
||||
if (result.data) historyByHttp = result.data;
|
||||
}),
|
||||
);
|
||||
await until(
|
||||
() =>
|
||||
stateByHttp.revision === revisionFor(4) &&
|
||||
historyByHttp?.[0]?.sequence === 4,
|
||||
'baseline HTTP reads',
|
||||
);
|
||||
const beforeHistoryEvents = b.histories.length;
|
||||
await action(a, 'open-bidding');
|
||||
await http('http://api-a:3000/_cluster/drain', {});
|
||||
await delay(250);
|
||||
assert.equal(b.state.revision, revisionFor(4));
|
||||
assert.equal(b.histories.length, beforeHistoryEvents);
|
||||
assert.equal(a.state.revision, revisionFor(5));
|
||||
// Do not run heartbeat recovery yet: verify the independent 30-second safety
|
||||
// route even if the client identity checker fails to notice a missed event.
|
||||
console.log(
|
||||
'WAIT Real 30-second HTTP safety polling with Pub/Sub still blocked',
|
||||
);
|
||||
await until(
|
||||
() =>
|
||||
stateByHttp.revision === revisionFor(5) &&
|
||||
historyByHttp?.[0]?.sequence === 5,
|
||||
'30-second HTTP safety fallback',
|
||||
35_000,
|
||||
);
|
||||
assert.ok(Date.now() - pollingStarted >= 29_000);
|
||||
pass(
|
||||
'Real 30-second HTTP polls repair missed state and history through Nginx',
|
||||
{ elapsedMS: Date.now() - pollingStarted, statePolls, historyPolls },
|
||||
);
|
||||
|
||||
const monitor = createAuctionHeartbeatMonitor();
|
||||
const heartbeat = async (sequence) => {
|
||||
const ack = await b.socket
|
||||
.timeout(3000)
|
||||
.emitWithAck('time-sync', { sequence });
|
||||
assert.equal(ack.ok, true);
|
||||
return monitor.inspect(b.state, ack.auctionState);
|
||||
};
|
||||
assert.equal((await heartbeat(2)).needsResync, false);
|
||||
await delay(10_000);
|
||||
assert.equal((await heartbeat(3)).needsResync, true);
|
||||
let resyncs = 0;
|
||||
const requester = createAuctionResyncRequester(
|
||||
async () => {
|
||||
resyncs += 1;
|
||||
return b.socket.timeout(3000).emitWithAck('resync', {});
|
||||
},
|
||||
(state) => {
|
||||
b.state = state;
|
||||
},
|
||||
);
|
||||
await requester.request(revisionFor(5), fixture.lifecycle);
|
||||
assert.equal(b.state.revision, revisionFor(5));
|
||||
assert.equal(resyncs, 1);
|
||||
pass(
|
||||
'Two real heartbeats detect a persistent gap and private socket resync works during Pub/Sub outage',
|
||||
{ resyncs },
|
||||
);
|
||||
|
||||
await http('http://redis-proxy:8081/restore', {});
|
||||
await until(
|
||||
async () =>
|
||||
(await http('http://redis-proxy:8081/status')).body.subscribers >= 2,
|
||||
'Pub/Sub resubscription',
|
||||
20_000,
|
||||
);
|
||||
await action(a, 'passed');
|
||||
await http('http://api-a:3000/_cluster/drain', {});
|
||||
await until(
|
||||
() =>
|
||||
b.state.revision === revisionFor(6) &&
|
||||
b.histories.at(-1)?.body[0]?.sequence === 6,
|
||||
'events after Pub/Sub restoration',
|
||||
);
|
||||
pass(
|
||||
'Cross-node state and history events recover after restoring the TCP path',
|
||||
);
|
||||
const fault = (await http('http://redis-proxy:8081/status')).body;
|
||||
report.fault = fault;
|
||||
const previousId = b.socket.id;
|
||||
b.socket.disconnect();
|
||||
b.socket.connect();
|
||||
await until(
|
||||
() => b.socket.connected && b.socket.id !== previousId,
|
||||
'socket reconnect through Nginx',
|
||||
);
|
||||
assert.equal(
|
||||
(
|
||||
await b.socket
|
||||
.timeout(5000)
|
||||
.emitWithAck('join', { matchId: fixture.matchId })
|
||||
).ok,
|
||||
true,
|
||||
);
|
||||
await until(
|
||||
() => b.state.revision === revisionFor(6),
|
||||
'reconnect full state',
|
||||
);
|
||||
pass('A reconnected viewer receives the latest snapshot through Nginx');
|
||||
}
|
||||
|
||||
try {
|
||||
if (process.argv[2] === 'init') await initialize();
|
||||
else {
|
||||
await verify();
|
||||
report.passed = true;
|
||||
}
|
||||
} catch (error) {
|
||||
report.passed = false;
|
||||
report.failure = { message: error.message, stack: error.stack };
|
||||
console.error(error);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (process.argv[2] !== 'init') {
|
||||
await http('http://redis-proxy:8081/restore', {}).catch(() => {});
|
||||
report.finishedAt = new Date().toISOString();
|
||||
await writeFile('/results/report.json', JSON.stringify(report, null, 2));
|
||||
}
|
||||
for (const close of cleanup.reverse()) {
|
||||
try {
|
||||
await close();
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
#!/bin/sh
|
||||
# From the repository root: sh apps/api/test/auction-cluster/run.sh
|
||||
# Requires Docker Compose. No host ports or production credentials are used.
|
||||
# Results and container logs remain in this directory's ignored results/ folder.
|
||||
# Authentication uses a fixture admin; client recovery uses the production
|
||||
# helpers and QueryObserver without rendering React. MongoDB 7 is the default
|
||||
# for the test host's kernel; set MONGO_TEST_IMAGE on a compatible host to match
|
||||
# the production database version.
|
||||
set -eu
|
||||
cd "$(dirname "$0")"
|
||||
export COMPOSE_PROJECT_NAME="${COMPOSE_PROJECT_NAME:-lolympus-auction-cluster-$(date +%s)}"
|
||||
case "$COMPOSE_PROJECT_NAME" in
|
||||
lolympus-auction-cluster-*) ;;
|
||||
*) echo 'Refusing to use a Compose project outside the auction-cluster test prefix.' >&2; exit 1 ;;
|
||||
esac
|
||||
mkdir -p results
|
||||
cleanup() {
|
||||
docker compose logs --no-color api-a api-b redis-proxy > results/containers.log 2>&1 || true
|
||||
docker compose down --volumes --remove-orphans
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
docker compose build runner
|
||||
docker compose up -d redis mongo redis-proxy
|
||||
docker compose run --rm runner node test/auction-cluster/run.mjs init
|
||||
docker compose up -d api-a api-b lb
|
||||
docker compose run --rm runner node test/auction-cluster/run.mjs verify
|
||||
@@ -324,7 +324,13 @@ describe('Community Hash response cache', () => {
|
||||
|
||||
it('does not share an old in-flight detail request after invalidation or overwrite the fresh response', async () => {
|
||||
const service = new CommunityStatsService(
|
||||
{} as never,
|
||||
{
|
||||
getModel: async () => ({
|
||||
findOne: () => ({
|
||||
select: () => ({ lean: () => ({ exec: async () => null }) }),
|
||||
}),
|
||||
}),
|
||||
} as never,
|
||||
cache,
|
||||
{} as never,
|
||||
{} as never,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>내전 전적 개선 시안 · LOLYMPUS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/design-previews/internal-stats/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>선수 정보 시안 02 · LOLYMPUS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/design-previews/player-information-v2/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>선수 정보 개선 시안 · LOLYMPUS</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/design-previews/player-information/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -19,5 +19,15 @@ export default defineConfig([
|
||||
ecmaVersion: 2020,
|
||||
globals: globals.browser,
|
||||
},
|
||||
rules: {
|
||||
// Product policy: information stays visible; use sections, links and pagination.
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
{
|
||||
selector: 'JSXOpeningElement[name.name="details"], JSXOpeningElement[name.name="summary"]',
|
||||
message: 'LOLYMPUS does not use disclosure/accordion UI. Keep content visible in a section, or use a dedicated route for a separate task.',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
])
|
||||
@@ -24,7 +24,7 @@
|
||||
"@azure/msal-browser": "^5.8.0",
|
||||
"@azure/msal-react": "^5.3.1",
|
||||
"@lolympus/contracts": "workspace:*",
|
||||
"@newrelic/browser-agent": "^1.318.0",
|
||||
"@newrelic/browser-agent": "^1.324.1",
|
||||
"@stylexjs/stylex": "0.19.1",
|
||||
"@tanstack/react-query": "^5.100.1",
|
||||
"lucide-react": "^1.14.0",
|
||||
@@ -35,20 +35,20 @@
|
||||
"socket.io-client": "^4.8.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.39.4",
|
||||
"@tailwindcss/vite": "^4.2.2",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/vite": "^4.3.5",
|
||||
"@types/node": "^26.1.1",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^9.39.4",
|
||||
"eslint-plugin-react-hooks": "^7.0.1",
|
||||
"@vitejs/plugin-react": "^6.3.0",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
"globals": "^17.4.0",
|
||||
"tailwindcss": "^4.2.2",
|
||||
"tailwindcss": "^4.3.5",
|
||||
"typescript": "~6.0.2",
|
||||
"typescript-eslint": "^8.58.0",
|
||||
"vite": "^8.1.5",
|
||||
"vite": "^8.3.8",
|
||||
"wrangler": "^4.114.0"
|
||||
}
|
||||
}
|
||||
+69
-79
@@ -23,16 +23,18 @@ import MatchTeamProgressPage from "./pages/MatchTeamProgressPage";
|
||||
import AuctionPage from "./pages/AuctionPage";
|
||||
import UserHistoryPage from "./pages/UserHistoryPage";
|
||||
import CommunityInternalStatsPage from "./pages/CommunityInternalStatsPage";
|
||||
import CommunityInternalPlayerPage from "./pages/CommunityInternalPlayerPage";
|
||||
import InternalMatchDetailPage from "./pages/InternalMatchDetailPage";
|
||||
import LegacyImportPage from "./pages/admin/LegacyImportPage";
|
||||
import LegacyMatchesPage from "./pages/admin/LegacyMatchesPage";
|
||||
import MatchAdminPage from "./pages/admin/MatchAdminPage";
|
||||
import TournamentCodesPage from "./pages/admin/TournamentCodesPage";
|
||||
import { PlainPage, Tooltip, pageWidthClass } from "./ui";
|
||||
import "./components/app-header.css";
|
||||
|
||||
|
||||
const NAV_ICON_BUTTON_CLASS =
|
||||
"grid size-10 shrink-0 place-items-center rounded-field text-content-muted transition-colors hover:bg-sunken-strong hover:text-content md:size-11";
|
||||
"lts-header-icon-button";
|
||||
|
||||
function MsalHeaderActions() {
|
||||
const { accounts, instance } = useMsal();
|
||||
@@ -41,7 +43,7 @@ function MsalHeaderActions() {
|
||||
if (!account) {
|
||||
return (
|
||||
<Link
|
||||
className="inline-flex h-10 items-center whitespace-nowrap rounded-full border border-line-strong px-3.5 text-sm font-semibold text-content transition-colors hover:bg-sunken md:h-11 md:px-4 md:text-[15px]"
|
||||
className="inline-flex h-8 items-center whitespace-nowrap rounded-full border border-line px-3 text-[13px] font-medium text-content-muted transition-colors hover:bg-sunken hover:text-content"
|
||||
to="/login"
|
||||
>
|
||||
로그인
|
||||
@@ -63,7 +65,7 @@ function MsalHeaderActions() {
|
||||
aria-label={`${name} 로그아웃`}
|
||||
onClick={() => void instance.logoutRedirect()}
|
||||
>
|
||||
<LogOut className="size-[18px] md:size-5" aria-hidden="true" />
|
||||
<LogOut className="size-[18px]" aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
@@ -81,11 +83,11 @@ function ThemeToggle() {
|
||||
<Tooltip content={label} placement="below">
|
||||
<button
|
||||
type="button"
|
||||
className={NAV_ICON_BUTTON_CLASS}
|
||||
className={`${NAV_ICON_BUTTON_CLASS} lts-header-theme-toggle`}
|
||||
aria-label={label}
|
||||
onClick={() => setTheme(nextTheme)}
|
||||
>
|
||||
<Icon className="size-[18px] md:size-5" aria-hidden="true" />
|
||||
<Icon className="size-[18px]" aria-hidden="true" />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
@@ -111,11 +113,7 @@ function PrimaryNavLink({
|
||||
<Link
|
||||
to={to}
|
||||
aria-current={current}
|
||||
className={`relative inline-flex h-full items-center whitespace-nowrap px-2.5 text-base font-semibold transition-colors focus-visible:-outline-offset-2 sm:px-4 md:px-7 md:text-xl ${
|
||||
current
|
||||
? "text-content-strong after:absolute after:inset-x-2.5 after:bottom-0 after:h-[3px] after:rounded-t-full after:bg-primary sm:after:inset-x-4 md:after:inset-x-7"
|
||||
: "text-content-subtle hover:text-content-strong"
|
||||
}`}
|
||||
className="lts-primary-nav-link"
|
||||
>
|
||||
{children}
|
||||
</Link>
|
||||
@@ -138,67 +136,55 @@ function AppHeader() {
|
||||
const adminPath = `/admin/communities/${DEFAULT_COMMUNITY_ID}`;
|
||||
|
||||
return (
|
||||
<>
|
||||
<header className="h-(--app-header-row-height) shrink-0 border-b border-line bg-card dark:bg-ink">
|
||||
<div
|
||||
className={`${pageWidthClass("xl")} grid h-full grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center sm:gap-x-3`}
|
||||
<header
|
||||
className={`lts-app-header${DEFAULT_COMMUNITY_ID ? "" : " lts-app-header--without-nav"}`}
|
||||
>
|
||||
<div className="lts-app-header-inner">
|
||||
<Link
|
||||
className="lts-header-brand"
|
||||
to="/"
|
||||
aria-label={`${communityLabel} 홈`}
|
||||
>
|
||||
<Link
|
||||
className="col-start-2 row-start-1 flex h-full items-center text-content-strong"
|
||||
to="/"
|
||||
aria-label={`${communityLabel} 홈`}
|
||||
>
|
||||
<span className="max-w-32 truncate text-xl font-extrabold tracking-[-0.02em] md:max-w-48 md:text-[22px]">
|
||||
{communityLabel}
|
||||
</span>
|
||||
</Link>
|
||||
<div className="contents sm:col-start-3 sm:row-start-1 sm:flex sm:min-w-0 sm:items-center sm:justify-end sm:gap-1 lg:gap-2">
|
||||
<div className="col-start-1 row-start-1 justify-self-start sm:shrink-0">
|
||||
<ThemeToggle />
|
||||
</div>
|
||||
{isMsalConfigured && (
|
||||
<div className="col-start-3 row-start-1 min-w-0 justify-self-end sm:shrink-0">
|
||||
<MsalHeaderActions />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
{DEFAULT_COMMUNITY_ID && (
|
||||
<nav
|
||||
aria-label="주 메뉴"
|
||||
className="sticky top-0 z-50 flex h-(--app-header-nav-height) shrink-0 justify-center gap-0.5 border-b border-line bg-card sm:gap-2 md:gap-5 dark:bg-ink"
|
||||
>
|
||||
<PrimaryNavLink to="/">홈</PrimaryNavLink>
|
||||
<PrimaryNavLink
|
||||
to="/inhouse"
|
||||
sectionPaths={isTournamentMatch ? undefined : ["/match/*"]}
|
||||
>
|
||||
내전
|
||||
</PrimaryNavLink>
|
||||
<PrimaryNavLink
|
||||
to="/tournaments"
|
||||
sectionPaths={isTournamentMatch ? ["/match/*"] : undefined}
|
||||
>
|
||||
멸망전
|
||||
</PrimaryNavLink>
|
||||
<PrimaryNavLink
|
||||
to={statsPath}
|
||||
sectionPaths={[`${statsPath}/*`, "/users/:userId/history"]}
|
||||
>
|
||||
전적
|
||||
</PrimaryNavLink>
|
||||
{canManage && (
|
||||
<span className="lts-header-brand-name">{communityLabel}</span>
|
||||
<span className="lts-header-brand-tagline">TOURNAMENT</span>
|
||||
</Link>
|
||||
{DEFAULT_COMMUNITY_ID && (
|
||||
<nav aria-label="주 메뉴" className="lts-primary-nav">
|
||||
<PrimaryNavLink to="/">홈</PrimaryNavLink>
|
||||
<PrimaryNavLink
|
||||
to={`${adminPath}/matches`}
|
||||
sectionPaths={[`${adminPath}/*`]}
|
||||
to="/inhouse"
|
||||
sectionPaths={isTournamentMatch ? undefined : ["/match/*"]}
|
||||
>
|
||||
운영
|
||||
내전
|
||||
</PrimaryNavLink>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
</>
|
||||
<PrimaryNavLink
|
||||
to="/tournaments"
|
||||
sectionPaths={isTournamentMatch ? ["/match/*"] : undefined}
|
||||
>
|
||||
멸망전
|
||||
</PrimaryNavLink>
|
||||
<PrimaryNavLink
|
||||
to={statsPath}
|
||||
sectionPaths={[`${statsPath}/*`, "/users/:userId/history"]}
|
||||
>
|
||||
전적
|
||||
</PrimaryNavLink>
|
||||
{canManage && (
|
||||
<PrimaryNavLink
|
||||
to={`${adminPath}/matches`}
|
||||
sectionPaths={[`${adminPath}/*`]}
|
||||
>
|
||||
운영
|
||||
</PrimaryNavLink>
|
||||
)}
|
||||
</nav>
|
||||
)}
|
||||
<div className="lts-header-actions">
|
||||
<ThemeToggle />
|
||||
{isMsalConfigured && <MsalHeaderActions />}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -206,26 +192,29 @@ function AppFooter() {
|
||||
return (
|
||||
<footer className="border-t border-line">
|
||||
<div
|
||||
className={`${pageWidthClass("xl")} flex flex-col gap-3 py-8 text-xs text-content-subtle`}
|
||||
className={`${pageWidthClass("xl")} flex flex-col items-center gap-4 py-10 text-center text-xs text-content-subtle sm:py-12`}
|
||||
>
|
||||
<nav
|
||||
aria-label="정책"
|
||||
className="flex items-center gap-4 font-semibold text-content-muted"
|
||||
className="flex flex-wrap items-center justify-center gap-x-6 gap-y-2 font-semibold text-content-muted"
|
||||
>
|
||||
<Link to="/terms" className="hover:text-content">
|
||||
<Link to="/terms" className="inline-flex min-h-8 items-center hover:text-content">
|
||||
서비스 이용약관
|
||||
</Link>
|
||||
<Link to="/privacy" className="hover:text-content">
|
||||
<Link to="/privacy" className="inline-flex min-h-8 items-center font-bold hover:text-content">
|
||||
개인정보처리방침
|
||||
</Link>
|
||||
</nav>
|
||||
<p className="max-w-4xl leading-relaxed">
|
||||
© 2026 LOLYMPUS. LOLYMPUS is not endorsed by Riot Games and does not
|
||||
reflect the views or opinions of Riot Games or anyone officially
|
||||
involved in producing or managing League of Legends. League of Legends
|
||||
and Riot Games are trademarks or registered trademarks of Riot Games,
|
||||
Inc. League of Legends © Riot Games, Inc.
|
||||
</p>
|
||||
<div className="w-full max-w-4xl space-y-1 leading-relaxed">
|
||||
<p className="text-balance">
|
||||
LOLYMPUS is not endorsed by Riot Games and does not reflect the views
|
||||
or opinions of Riot Games or anyone officially involved in producing
|
||||
or managing League of Legends. League of Legends and Riot Games are
|
||||
trademarks or registered trademarks of Riot Games, Inc. League of
|
||||
Legends © Riot Games, Inc.
|
||||
</p>
|
||||
<p>© 2026 LOLYMPUS.</p>
|
||||
</div>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
@@ -289,7 +278,7 @@ function App() {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<div
|
||||
className={`lts-app-shell flex min-h-screen flex-col bg-body ${DEFAULT_COMMUNITY_ID ? "" : "[--app-header-nav-height:0px]"}`}
|
||||
className={`lts-app-shell flex min-h-screen flex-col bg-body ${DEFAULT_COMMUNITY_ID ? "" : "lts-app-shell--without-nav"}`}
|
||||
>
|
||||
<AppHeader />
|
||||
|
||||
@@ -321,6 +310,7 @@ function App() {
|
||||
path="/communities/:cid/internal-stats"
|
||||
element={<CommunityInternalStatsPage />}
|
||||
/>
|
||||
<Route path="/communities/:cid/internal-stats/players/:userId" element={<CommunityInternalPlayerPage />} />
|
||||
<Route
|
||||
path="/communities/:cid/internal-stats/match/:matchId"
|
||||
element={<InternalMatchDetailPage />}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { ApiAuctionChatMessage } from "./types.ts";
|
||||
|
||||
export interface ChatMessagePayload {
|
||||
displayName?: string;
|
||||
message: string;
|
||||
clientMessageId: string;
|
||||
}
|
||||
|
||||
export interface ChatMessageReply {
|
||||
ok?: boolean;
|
||||
message?: ApiAuctionChatMessage | string;
|
||||
}
|
||||
|
||||
export async function sendAuctionChatMessage(
|
||||
send: (() => Promise<ChatMessageReply>) | undefined,
|
||||
): Promise<ApiAuctionChatMessage> {
|
||||
if (!send) throw new Error("연결이 끊겼습니다. 연결 후 다시 보내 주세요.");
|
||||
let reply: ChatMessageReply;
|
||||
try {
|
||||
reply = await send();
|
||||
} catch {
|
||||
throw new Error("전송을 확인하지 못했습니다. 다시 보내 주세요.");
|
||||
}
|
||||
if (reply?.ok && typeof reply.message === "object" && reply.message?.id) {
|
||||
return reply.message;
|
||||
}
|
||||
if (reply?.message === "Chat message must be 300 characters or less.") {
|
||||
throw new Error("메시지는 300자까지 보낼 수 있습니다.");
|
||||
}
|
||||
throw new Error("메시지를 보내지 못했습니다. 다시 보내 주세요.");
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
export const AUCTION_SAFETY_POLL_INTERVAL_MS = 30_000;
|
||||
|
||||
/** Supplements the fixed safety poll without restarting its timer. */
|
||||
export function startAuctionRecoveryPolling(
|
||||
refetch: () => void,
|
||||
isVisible = () => document.visibilityState === 'visible',
|
||||
): () => void {
|
||||
const timer = setInterval(() => {
|
||||
if (isVisible()) refetch();
|
||||
}, 5000);
|
||||
return () => clearInterval(timer);
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type {
|
||||
AuctionReactionEvent,
|
||||
AuctionReactionKind,
|
||||
AuctionReactionReply,
|
||||
} from "@lolympus/contracts";
|
||||
|
||||
export const AUCTION_REACTIONS: Record<
|
||||
AuctionReactionKind,
|
||||
{ emoji: string; label: string }
|
||||
> = {
|
||||
"thumbs-up": { emoji: "👍", label: "좋아요" },
|
||||
heart: { emoji: "❤️", label: "하트" },
|
||||
clap: { emoji: "👏", label: "박수" },
|
||||
laugh: { emoji: "😂", label: "웃음" },
|
||||
wow: { emoji: "😮", label: "놀람" },
|
||||
sad: { emoji: "😢", label: "아쉬움" },
|
||||
fire: { emoji: "🔥", label: "불꽃" },
|
||||
celebrate: { emoji: "🎉", label: "축하" },
|
||||
eyes: { emoji: "👀", label: "관심" },
|
||||
thinking: { emoji: "🤔", label: "고민" },
|
||||
"skull-crossbones": { emoji: "☠️", label: "해골과 뼈" },
|
||||
poop: { emoji: "💩", label: "똥" },
|
||||
pray: { emoji: "🙏", label: "간절함" },
|
||||
"sweat-smile": { emoji: "😅", label: "식은땀" },
|
||||
money: { emoji: "💸", label: "플렉스" },
|
||||
trophy: { emoji: "🏆", label: "우승각" },
|
||||
};
|
||||
|
||||
export const REACTION_LIFETIME_MS = 3200;
|
||||
export const MAX_VISIBLE_REACTIONS = 16;
|
||||
export type ActiveAuctionReaction = AuctionReactionEvent & {
|
||||
receivedAt: number;
|
||||
};
|
||||
|
||||
export function isAuctionReaction(
|
||||
value: unknown,
|
||||
): value is AuctionReactionEvent {
|
||||
if (!value || typeof value !== "object") return false;
|
||||
const reaction = value as Partial<AuctionReactionEvent>;
|
||||
return (
|
||||
typeof reaction.id === "string" &&
|
||||
reaction.id.length > 0 &&
|
||||
reaction.id.length <= 100 &&
|
||||
typeof reaction.kind === "string" &&
|
||||
Object.hasOwn(AUCTION_REACTIONS, reaction.kind) &&
|
||||
typeof reaction.displayName === "string" &&
|
||||
reaction.displayName.length <= 160 &&
|
||||
typeof reaction.sentAt === "number" &&
|
||||
Number.isFinite(reaction.sentAt)
|
||||
);
|
||||
}
|
||||
|
||||
export function appendAuctionReaction(
|
||||
current: ActiveAuctionReaction[],
|
||||
incoming: AuctionReactionEvent,
|
||||
now = Date.now(),
|
||||
): ActiveAuctionReaction[] {
|
||||
const active = current.filter(
|
||||
(reaction) => now - reaction.receivedAt < REACTION_LIFETIME_MS,
|
||||
);
|
||||
if (active.some((reaction) => reaction.id === incoming.id)) return active;
|
||||
return [...active, { ...incoming, receivedAt: now }].slice(
|
||||
-MAX_VISIBLE_REACTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
export async function sendAuctionReaction(
|
||||
send: (() => Promise<AuctionReactionReply>) | undefined,
|
||||
): Promise<AuctionReactionEvent> {
|
||||
if (!send) throw new Error("연결되면 반응을 보낼 수 있습니다.");
|
||||
let reply: AuctionReactionReply;
|
||||
try {
|
||||
reply = await send();
|
||||
} catch {
|
||||
throw new Error("반응을 보내지 못했습니다. 잠시 후 다시 눌러 주세요.");
|
||||
}
|
||||
if (reply?.ok && isAuctionReaction(reply.reaction)) return reply.reaction;
|
||||
if (reply?.code === "REACTION_RATE_LIMITED")
|
||||
throw new Error("조금만 기다렸다가 다시 눌러 주세요.");
|
||||
throw new Error("반응을 보내지 못했습니다. 잠시 후 다시 눌러 주세요.");
|
||||
}
|
||||
@@ -27,6 +27,7 @@ export function createAuctionResyncRequester(
|
||||
fetchState: () => Promise<AuctionResyncReply>,
|
||||
applyState: (state: ApiAuction) => void,
|
||||
wait = waitForRetry,
|
||||
onFailure?: () => void,
|
||||
) {
|
||||
let pending: Promise<void> | undefined;
|
||||
let controller = new AbortController();
|
||||
@@ -67,6 +68,7 @@ export function createAuctionResyncRequester(
|
||||
}
|
||||
if (attempt < 2 && !signal.aborted) await wait(retryAfterMS, signal);
|
||||
}
|
||||
if (!signal.aborted) onFailure?.();
|
||||
})().finally(() => {
|
||||
if (!signal.aborted) pending = undefined;
|
||||
});
|
||||
|
||||
@@ -1,4 +1,69 @@
|
||||
import type { ApiAuction } from "./types";
|
||||
import type { AuctionStateIdentity } from "@lolympus/contracts";
|
||||
|
||||
export function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const amount = Number(
|
||||
auction.currentHighestBidPointAmount ?? auction.currentBid ?? 0,
|
||||
);
|
||||
return Number.isFinite(amount) ? Math.max(0, amount) : 0;
|
||||
}
|
||||
|
||||
export function shouldResyncForAuctionIdentity(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null,
|
||||
): boolean {
|
||||
if (!current) return true;
|
||||
// Completed runtimes expire while their archived Mongo state remains valid.
|
||||
if (!identity) {
|
||||
return (
|
||||
current.auctionEngineVersion === "redis-v1" &&
|
||||
current.phase !== "complete"
|
||||
);
|
||||
}
|
||||
if (identity.auctionLifecycleId !== current.auctionLifecycleId) return true;
|
||||
if ((identity.revision ?? -1) > (current.revision ?? -1)) return true;
|
||||
// A delayed heartbeat must not undo a newer state already received by socket.
|
||||
if ((identity.revision ?? -1) < (current.revision ?? -1)) return false;
|
||||
return (
|
||||
(identity.matchSideEffectRevision ?? -1) >
|
||||
(current.matchSideEffectRevision ?? -1)
|
||||
);
|
||||
}
|
||||
|
||||
export function createAuctionHeartbeatMonitor() {
|
||||
let pendingIdentity: AuctionStateIdentity | null | undefined;
|
||||
let consecutiveFailures = 0;
|
||||
return {
|
||||
reset() {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures = 0;
|
||||
},
|
||||
recordFailure(): boolean {
|
||||
pendingIdentity = undefined;
|
||||
consecutiveFailures += 1;
|
||||
return consecutiveFailures >= 2;
|
||||
},
|
||||
inspect(
|
||||
current: ApiAuction | null,
|
||||
identity: AuctionStateIdentity | null | undefined,
|
||||
) {
|
||||
consecutiveFailures = 0;
|
||||
const previousIdentity = pendingIdentity;
|
||||
const isCurrent =
|
||||
identity === undefined ||
|
||||
!shouldResyncForAuctionIdentity(current, identity);
|
||||
pendingIdentity = undefined;
|
||||
if (isCurrent) return { isCurrent: true, needsResync: false };
|
||||
// Bids received since the first heartbeat may have closed that gap, even
|
||||
// when this heartbeat observes another newer bid still in transit.
|
||||
const needsResync =
|
||||
previousIdentity !== undefined &&
|
||||
shouldResyncForAuctionIdentity(current, previousIdentity);
|
||||
if (!needsResync) pendingIdentity = identity;
|
||||
return { isCurrent: false, needsResync };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export interface BidDeltaPayload {
|
||||
currentBidRoundId?: string;
|
||||
|
||||
@@ -56,6 +56,7 @@ import type {
|
||||
MeResponse,
|
||||
RiotQueueGroup,
|
||||
RiotRankFilter,
|
||||
RiotLane,
|
||||
RebuildLegacyMatchesResponse,
|
||||
TournamentCodeBulkUploadResponse,
|
||||
TournamentCodeListResponse,
|
||||
@@ -84,6 +85,7 @@ interface MatchesPageQueryOptions extends MatchesQueryOptions {
|
||||
}
|
||||
|
||||
export interface UserHistoryFilters {
|
||||
lane?: RiotLane;
|
||||
queueGroup?: RiotQueueGroup;
|
||||
rank?: RiotRankFilter;
|
||||
seasonId?: string;
|
||||
@@ -91,6 +93,7 @@ export interface UserHistoryFilters {
|
||||
}
|
||||
|
||||
export interface CommunityInternalStatsFilters {
|
||||
lane?: RiotLane;
|
||||
seasonId?: string;
|
||||
from?: string;
|
||||
to?: string;
|
||||
@@ -420,10 +423,10 @@ export function useAuction(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuction>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction`,
|
||||
{ auth: 'none' },
|
||||
{ auth: 'none', signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId),
|
||||
retry: false,
|
||||
@@ -438,9 +441,10 @@ export function useAuctionHistory(
|
||||
) {
|
||||
return useQuery({
|
||||
queryKey: ['auction-history', communityId, matchId ?? null],
|
||||
queryFn: () =>
|
||||
queryFn: ({ signal }) =>
|
||||
apiFetch<ApiAuctionHistoryEntry[]>(
|
||||
`/communities/${communityId}/matches/${matchId}/auction/history`,
|
||||
{ signal },
|
||||
),
|
||||
enabled: Boolean(communityId && matchId && (options.enabled ?? true)),
|
||||
retry: false,
|
||||
@@ -559,6 +563,7 @@ function createUserHistoryPath(
|
||||
const searchParams = new URLSearchParams();
|
||||
if (filters.queueGroup) searchParams.set('queueGroup', filters.queueGroup);
|
||||
if (filters.rank) searchParams.set('rank', filters.rank);
|
||||
if (filters.lane) searchParams.set('lane', filters.lane);
|
||||
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
|
||||
if (filters.championId)
|
||||
searchParams.set('championId', String(filters.championId));
|
||||
@@ -569,7 +574,8 @@ function createUserHistoryPath(
|
||||
}
|
||||
|
||||
const queryString = searchParams.toString();
|
||||
return `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
|
||||
const path = `/communities/${communityId}/users/${userId}/${resource}${queryString ? `?${queryString}` : ''}`;
|
||||
return path;
|
||||
}
|
||||
|
||||
export function useUserHistoryProfile(
|
||||
@@ -695,6 +701,7 @@ function createCommunityInternalStatsPath(
|
||||
extra: Record<string, string | number | null | undefined> = {},
|
||||
) {
|
||||
const searchParams = new URLSearchParams();
|
||||
if (filters.lane) searchParams.set('lane', filters.lane);
|
||||
if (filters.seasonId) searchParams.set('seasonId', filters.seasonId);
|
||||
if (filters.from) searchParams.set('from', filters.from);
|
||||
if (filters.to) searchParams.set('to', filters.to);
|
||||
@@ -757,6 +764,7 @@ export function useCommunityLeaderboard(
|
||||
queryKey: [
|
||||
'community-internal-stats-leaderboard',
|
||||
communityId,
|
||||
filters.lane ?? null,
|
||||
filters.seasonId ?? null,
|
||||
filters.from ?? null,
|
||||
filters.to ?? null,
|
||||
@@ -838,6 +846,7 @@ export function useUserInternalHistory(
|
||||
queryKey: [
|
||||
'user-internal-history',
|
||||
communityId,
|
||||
filters.lane ?? null,
|
||||
userId ?? null,
|
||||
filters.seasonId ?? null,
|
||||
filters.championId ?? null,
|
||||
|
||||
@@ -81,6 +81,7 @@ export interface AuctionTeamView {
|
||||
name: string;
|
||||
captainUserId: string;
|
||||
captainName: string;
|
||||
captain?: ParticipantView;
|
||||
points: number;
|
||||
members: (AuctionPlayerView & {
|
||||
assignedPosition: Position;
|
||||
@@ -253,13 +254,16 @@ function mapAuctionTeamToView(
|
||||
playerLookup: Map<string, AuctionPlayerView>,
|
||||
participantLookup: Map<string, ParticipantView>,
|
||||
): AuctionTeamView {
|
||||
const captain =
|
||||
participantLookup.get(team.captainUserId) ??
|
||||
playerLookup.get(team.captainUserId);
|
||||
|
||||
return {
|
||||
teamIndex: team.teamIndex,
|
||||
name: teamIndexLabel(team.teamIndex),
|
||||
captainUserId: team.captainUserId,
|
||||
captainName:
|
||||
participantLookup.get(team.captainUserId)?.summonerName ??
|
||||
`User ${team.captainUserId.slice(-4)}`,
|
||||
captainName: captain?.summonerName ?? `User ${team.captainUserId.slice(-4)}`,
|
||||
captain,
|
||||
points: team.points,
|
||||
members: team.members.map((member) => {
|
||||
const participant = participantLookup.get(member.userId);
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
InternalMatchCompetition,
|
||||
InternalMatchResultPresentation,
|
||||
SeriesId,
|
||||
SeriesProjection,
|
||||
MatchEventType,
|
||||
RecentMatchParticipantRank,
|
||||
MatchGameMode,
|
||||
@@ -184,6 +185,8 @@ export interface ApiAuctionBid {
|
||||
|
||||
export interface ApiAuctionChatMessage {
|
||||
id: string;
|
||||
clientMessageId?: string;
|
||||
senderRole?: 'operator';
|
||||
userId?: string;
|
||||
displayName: string;
|
||||
message: string;
|
||||
@@ -193,6 +196,7 @@ export interface ApiAuctionChatMessage {
|
||||
export interface ApiAuction {
|
||||
_id: string;
|
||||
matchId: string;
|
||||
auctionEngineVersion?: 'legacy-renamed' | 'redis-v1';
|
||||
phase: AuctionPhase;
|
||||
teams?: ApiAuctionTeam[];
|
||||
auctionTeams: ApiAuctionTeam[];
|
||||
@@ -564,8 +568,11 @@ export interface ApiRecentMatchTeam {
|
||||
}
|
||||
|
||||
export interface ApiRecentMatchView {
|
||||
/** Champion damage as a percentage of team champion damage. */
|
||||
damageShare?: number;
|
||||
matchId: string;
|
||||
internalMatchId?: string;
|
||||
internalMatchTitle?: string;
|
||||
gameNumber?: number;
|
||||
queueId: number;
|
||||
queueLabel: string;
|
||||
@@ -601,6 +608,7 @@ export interface ApiRecentMatchView {
|
||||
}
|
||||
|
||||
export interface ApiRecentMatchesResponse {
|
||||
positionCounts?: Record<string, number>;
|
||||
matches: ApiRecentMatchView[];
|
||||
nextCursor: number | null;
|
||||
lastFetchedAt: string | null;
|
||||
@@ -615,6 +623,7 @@ export interface ApiInternalMatchCard {
|
||||
gameCount: number;
|
||||
winnerTeamIndex?: number;
|
||||
resultPresentation?: InternalMatchResultPresentation;
|
||||
series?: SeriesProjection[];
|
||||
seriesResults: Array<{
|
||||
teamAIndex: number;
|
||||
teamBIndex: number;
|
||||
@@ -624,6 +633,9 @@ export interface ApiInternalMatchCard {
|
||||
}>;
|
||||
games: Array<{
|
||||
gameNumber: number;
|
||||
seriesId?: string;
|
||||
ordinal?: number;
|
||||
analysisAvailability?: GameAnalysisAvailability | 'pending';
|
||||
riotMatchId: string | null;
|
||||
blueTeamIndex: number;
|
||||
redTeamIndex: number;
|
||||
@@ -633,6 +645,7 @@ export interface ApiInternalMatchCard {
|
||||
}>;
|
||||
teams: Array<{
|
||||
teamIndex: number;
|
||||
teamId?: string;
|
||||
name: string;
|
||||
members: Array<{
|
||||
userId: string;
|
||||
@@ -673,6 +686,7 @@ export interface ApiLeaderboardRow {
|
||||
|
||||
export interface ApiLeaderboardResponse {
|
||||
rows: ApiLeaderboardRow[];
|
||||
lane?: RiotLane;
|
||||
season: ApiHistorySeason;
|
||||
matchedUserIds?: string[];
|
||||
}
|
||||
@@ -683,11 +697,14 @@ export interface ApiLeaderHighlight {
|
||||
summonerName: string;
|
||||
championId?: number;
|
||||
matchId?: string;
|
||||
internalMatchId?: string;
|
||||
gameNumber?: number;
|
||||
isSingleGame: boolean;
|
||||
}
|
||||
|
||||
export interface ApiTeamInsightsResponse {
|
||||
season: ApiHistorySeason;
|
||||
totals?: { matches: number; games: number; analyzedGames: number; players: number };
|
||||
sideWinRate: {
|
||||
blue: number;
|
||||
red: number;
|
||||
@@ -822,6 +839,8 @@ export interface ApiInternalMatchDetailResponse {
|
||||
}
|
||||
|
||||
export interface ApiUserInternalHistoryResponse {
|
||||
positionCounts?: Record<string, number>;
|
||||
playerStats?: ApiLeaderboardRow | null;
|
||||
season: ApiHistorySeason;
|
||||
championStats: ApiChampionStatsResponse;
|
||||
summary: ApiRecentSummaryResponse;
|
||||
|
||||
@@ -2,10 +2,18 @@ import { InteractionStatus } from '@azure/msal-browser';
|
||||
import { useMsal } from '@azure/msal-react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { io, type Socket } from 'socket.io-client';
|
||||
import type {
|
||||
AuctionHistoryUpdatedEvent,
|
||||
AuctionReactionKind,
|
||||
AuctionReactionReply,
|
||||
AuctionStateIdentity,
|
||||
} from '@lolympus/contracts';
|
||||
import { appendAuctionReaction, isAuctionReaction, REACTION_LIFETIME_MS, sendAuctionReaction, type ActiveAuctionReaction } from './auction-reactions';
|
||||
import { API_BASE_URL, useAuthUserId } from '../config';
|
||||
import { acquireAccessToken } from '../lib/auth/token-provider';
|
||||
import { isMsalConfigured } from '../lib/auth/msal.config';
|
||||
import type { ApiAuction, ApiAuctionChatMessage, Position } from './types';
|
||||
import { sendAuctionChatMessage, type ChatMessagePayload, type ChatMessageReply } from './auction-chat';
|
||||
import {
|
||||
createAuctionResyncRequester,
|
||||
type AuctionResyncReply,
|
||||
@@ -16,6 +24,8 @@ import {
|
||||
shouldResyncForBidDelta,
|
||||
shouldApplyPolledAuctionState,
|
||||
mergeAuctionState,
|
||||
resolveCurrentBidPointAmount,
|
||||
createAuctionHeartbeatMonitor,
|
||||
type BidDeltaPayload,
|
||||
} from './auction-state';
|
||||
import { resolveAuctionActionRejection } from './auction-action-retry';
|
||||
@@ -44,11 +54,6 @@ interface BidPayload {
|
||||
clientObservedCurrentBidRoundPlayerUserId?: string;
|
||||
}
|
||||
|
||||
interface ChatMessagePayload {
|
||||
displayName?: string;
|
||||
message: string;
|
||||
}
|
||||
|
||||
interface AuctionActionPayload {
|
||||
auctionActionRequestId?: string;
|
||||
clientObservedAuctionLifecycleId?: string;
|
||||
@@ -107,6 +112,8 @@ interface BidAckPayload {
|
||||
}
|
||||
|
||||
interface TimeSyncAckPayload {
|
||||
auctionState?: AuctionStateIdentity | null;
|
||||
auctionStateUnavailable?: boolean;
|
||||
clientSentAtTimestampMS?: number;
|
||||
currentServerTimestampMS?: number;
|
||||
ok?: boolean;
|
||||
@@ -171,10 +178,35 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const timeSyncSequenceRef = useRef(0);
|
||||
const hasSyncedServerTimeRef = useRef(false);
|
||||
const latestAuctionRef = useRef<ApiAuction | null>(null);
|
||||
const synchronizedSocketRef = useRef<Socket | null>(null);
|
||||
const heartbeatMonitorRef = useRef(createAuctionHeartbeatMonitor());
|
||||
const cancelledLifecycleIdsRef = useRef(new Set<string>());
|
||||
const latestConfirmedBidPointAmountRef = useRef(0);
|
||||
const [auction, setAuction] = useState<ApiAuction | null>(null);
|
||||
const [chatMessages, setChatMessages] = useState<ApiAuctionChatMessage[]>([]);
|
||||
const [reactionState, setReactionState] = useState<{ key: string; items: ActiveAuctionReaction[] }>({ key: '', items: [] });
|
||||
const seenReactionsRef = useRef(new Set<string>());
|
||||
const receiveReaction = useCallback((value: unknown, key: string) => {
|
||||
if (!isAuctionReaction(value) || seenReactionsRef.current.has(value.id)) return;
|
||||
seenReactionsRef.current.add(value.id);
|
||||
if (seenReactionsRef.current.size > 128) {
|
||||
seenReactionsRef.current.delete(seenReactionsRef.current.values().next().value!);
|
||||
}
|
||||
setReactionState((current) => ({
|
||||
key, items: appendAuctionReaction(current.key === key ? current.items : [], value),
|
||||
}));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (reactionState.items.length === 0) return;
|
||||
const expiresAt = reactionState.items[0].receivedAt + REACTION_LIFETIME_MS;
|
||||
const timer = setTimeout(() => {
|
||||
setReactionState((current) => ({ ...current, items: current.items.filter(
|
||||
(reaction) => Date.now() - reaction.receivedAt < REACTION_LIFETIME_MS,
|
||||
) }));
|
||||
}, Math.max(0, expiresAt - Date.now()) + 16);
|
||||
return () => clearTimeout(timer);
|
||||
}, [reactionState]);
|
||||
const [pendingBidRequests, setPendingBidRequests] = useState<
|
||||
Record<string, { amount: number; teamIndex: number }>
|
||||
>({});
|
||||
@@ -186,6 +218,11 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
key: string;
|
||||
status: ConnectionStatus;
|
||||
}>({ key: '', status: 'idle' });
|
||||
const [synchronizationState, setSynchronizationState] = useState({
|
||||
key: '',
|
||||
ready: false,
|
||||
});
|
||||
const [historyUpdateState, setHistoryUpdateState] = useState({ key: '', count: 0 });
|
||||
const [errorState, setErrorState] = useState<{
|
||||
key: string;
|
||||
message: string | null;
|
||||
@@ -313,15 +350,32 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
timeSyncTimeoutsRef.current = {};
|
||||
}
|
||||
|
||||
function requestServerTimeSync(socket: Socket) {
|
||||
const markSynchronized = useCallback(
|
||||
(socket: Socket, key: string, ready: boolean) => {
|
||||
if (socketRef.current !== socket) return;
|
||||
setSynchronizationState((current) =>
|
||||
current.key === key && current.ready === ready ? current : { key, ready },
|
||||
);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const requestServerTimeSync = useCallback((socket: Socket, key: string) => {
|
||||
if (!socket.connected) return;
|
||||
|
||||
const recordFailure = () => {
|
||||
if (socketRef.current === socket && heartbeatMonitorRef.current.recordFailure()) {
|
||||
markSynchronized(socket, key, false);
|
||||
}
|
||||
};
|
||||
|
||||
const sequence = timeSyncSequenceRef.current + 1;
|
||||
timeSyncSequenceRef.current = sequence;
|
||||
const clientSentAtTimestampMS = Date.now();
|
||||
|
||||
timeSyncTimeoutsRef.current[sequence] = setTimeout(() => {
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
recordFailure();
|
||||
}, TIME_SYNC_TIMEOUT_MS);
|
||||
|
||||
socket.emit(
|
||||
@@ -333,15 +387,35 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
if (!timeoutId) return;
|
||||
clearTimeout(timeoutId);
|
||||
delete timeSyncTimeoutsRef.current[sequence];
|
||||
if (socketRef.current !== socket) return;
|
||||
|
||||
if (
|
||||
!ack?.ok ||
|
||||
ack.sequence !== sequence ||
|
||||
typeof ack.currentServerTimestampMS !== 'number'
|
||||
) {
|
||||
recordFailure();
|
||||
return;
|
||||
}
|
||||
|
||||
if (ack.auctionStateUnavailable) {
|
||||
recordFailure();
|
||||
} else {
|
||||
const inspection = heartbeatMonitorRef.current.inspect(
|
||||
latestAuctionRef.current,
|
||||
ack.auctionState,
|
||||
);
|
||||
if (inspection.needsResync) {
|
||||
markSynchronized(socket, key, false);
|
||||
void resyncRequesterRef.current?.request(
|
||||
ack.auctionState?.revision,
|
||||
ack.auctionState?.auctionLifecycleId,
|
||||
);
|
||||
} else if (inspection.isCurrent) {
|
||||
markSynchronized(socket, key, synchronizedSocketRef.current === socket);
|
||||
}
|
||||
}
|
||||
|
||||
const totalRoundTripDurationMS = Math.max(
|
||||
0,
|
||||
clientReceivedAtTimestampMS - clientSentAtTimestampMS,
|
||||
@@ -370,7 +444,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}, [markSynchronized]);
|
||||
|
||||
function captureBidLatencyDiagnostics(ack?: BidAckPayload) {
|
||||
if (!ack?.bidDiagnostics && !ack?.bidServerTiming) return;
|
||||
@@ -451,6 +525,8 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
const activeConnectionKey = connectionKey;
|
||||
const cancelledLifecycleIds = cancelledLifecycleIdsRef.current;
|
||||
let disposed = false;
|
||||
let removeResumeListeners = () => {};
|
||||
let hasReceivedSnapshot = false;
|
||||
|
||||
void (async () => {
|
||||
const accessToken = await acquireAccessToken().catch((error) => {
|
||||
@@ -469,7 +545,16 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
|
||||
socketRef.current = socket;
|
||||
const notifyHistoryUpdated = () => {
|
||||
setHistoryUpdateState((current) => ({
|
||||
key: activeConnectionKey,
|
||||
count: current.key === activeConnectionKey ? current.count + 1 : 1,
|
||||
}));
|
||||
};
|
||||
const receiveAuctionState = (nextAuction: ApiAuction, source: string) => {
|
||||
if (
|
||||
disposed || socketRef.current !== socket || nextAuction.matchId !== matchId
|
||||
) return;
|
||||
const previousRevision = latestAuctionRef.current?.revision ?? -1;
|
||||
const didApplyState = commitAuctionState(nextAuction, source);
|
||||
if (didApplyState && (nextAuction.revision ?? 0) > previousRevision) {
|
||||
@@ -480,6 +565,13 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
setChatMessages(mergeChatMessages([], nextAuction.chatMessages));
|
||||
}
|
||||
if (didApplyState) {
|
||||
if (hasReceivedSnapshot && synchronizedSocketRef.current !== socket) {
|
||||
notifyHistoryUpdated();
|
||||
}
|
||||
hasReceivedSnapshot = true;
|
||||
synchronizedSocketRef.current = socket;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, true);
|
||||
setError(null);
|
||||
}
|
||||
};
|
||||
@@ -494,27 +586,45 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
(state) => {
|
||||
receiveAuctionState(state, 'socket-resync');
|
||||
},
|
||||
undefined,
|
||||
() => markSynchronized(socket, activeConnectionKey, false),
|
||||
);
|
||||
resyncRequesterRef.current = resyncRequester;
|
||||
|
||||
socket.on('connect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({
|
||||
key: activeConnectionKey,
|
||||
status: 'connected',
|
||||
});
|
||||
setError(null);
|
||||
socket.emit('join', { matchId });
|
||||
requestServerTimeSync(socket);
|
||||
void socket.timeout(3000).emitWithAck('join', { matchId })
|
||||
.then((reply: { ok?: boolean }) => {
|
||||
if (!reply?.ok && synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
}).catch(() => {
|
||||
if (synchronizedSocketRef.current !== socket) {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
}
|
||||
});
|
||||
requestServerTimeSync(socket, activeConnectionKey);
|
||||
if (timeSyncIntervalRef.current) {
|
||||
clearInterval(timeSyncIntervalRef.current);
|
||||
}
|
||||
timeSyncIntervalRef.current = setInterval(
|
||||
() => requestServerTimeSync(socket),
|
||||
() => requestServerTimeSync(socket, activeConnectionKey),
|
||||
TIME_SYNC_INTERVAL_MS,
|
||||
);
|
||||
});
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
synchronizedSocketRef.current = null;
|
||||
heartbeatMonitorRef.current.reset();
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setReactionState({ key: activeConnectionKey, items: [] });
|
||||
resyncRequester.cancel();
|
||||
clearTimeSyncTimers();
|
||||
setConnectionState({
|
||||
@@ -523,6 +633,34 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
});
|
||||
});
|
||||
|
||||
socket.on('connect_error', (error: Error) => {
|
||||
markSynchronized(socket, activeConnectionKey, false);
|
||||
setConnectionState({ key: activeConnectionKey, status: 'error' });
|
||||
if (!socket.active) setError(resolveAuctionErrorMessage(error.message));
|
||||
});
|
||||
|
||||
socket.on('history-updated', (event: AuctionHistoryUpdatedEvent) => {
|
||||
if (event.matchId !== matchId) return;
|
||||
const lifecycle = latestAuctionRef.current?.auctionLifecycleId;
|
||||
if (lifecycle && lifecycle !== event.auctionLifecycleId) return;
|
||||
// Older append retries may fill a gap without increasing the maximum
|
||||
// sequence. Every committed-history notification refreshes the list.
|
||||
notifyHistoryUpdated();
|
||||
});
|
||||
|
||||
const resyncAfterResume = () => {
|
||||
if (document.visibilityState === 'visible' && socket.connected) {
|
||||
notifyHistoryUpdated();
|
||||
void resyncRequester.request();
|
||||
}
|
||||
};
|
||||
document.addEventListener('visibilitychange', resyncAfterResume);
|
||||
window.addEventListener('online', resyncAfterResume);
|
||||
removeResumeListeners = () => {
|
||||
document.removeEventListener('visibilitychange', resyncAfterResume);
|
||||
window.removeEventListener('online', resyncAfterResume);
|
||||
};
|
||||
|
||||
socket.on('state-pending', () => {
|
||||
void resyncRequester.request();
|
||||
});
|
||||
@@ -538,6 +676,9 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
socket.on('chat-message', (message: ApiAuctionChatMessage) => {
|
||||
setChatMessages((current) => mergeChatMessages(current, [message]));
|
||||
});
|
||||
socket.on('chat-reaction', (reaction: unknown) => {
|
||||
receiveReaction(reaction, activeConnectionKey);
|
||||
});
|
||||
|
||||
socket.on('bid', (payload: BidDeltaPayload) => {
|
||||
applyFallbackServerTimestamp(payload?.currentServerTimestampMS);
|
||||
@@ -648,6 +789,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
|
||||
return () => {
|
||||
disposed = true;
|
||||
removeResumeListeners();
|
||||
resyncRequesterRef.current?.cancel();
|
||||
resyncRequesterRef.current = null;
|
||||
const socket = socketRef.current;
|
||||
@@ -664,6 +806,7 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
pendingBidTimeoutsRef.current = {};
|
||||
pendingActionTimeoutsRef.current = {};
|
||||
latestAuctionRef.current = null;
|
||||
synchronizedSocketRef.current = null;
|
||||
cancelledLifecycleIds.clear();
|
||||
latestConfirmedBidPointAmountRef.current = 0;
|
||||
hasSyncedServerTimeRef.current = false;
|
||||
@@ -681,26 +824,12 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
commitBidDelta,
|
||||
connectionKey,
|
||||
matchId,
|
||||
receiveReaction,
|
||||
markSynchronized,
|
||||
requestServerTimeSync,
|
||||
setError,
|
||||
]);
|
||||
|
||||
function emit(eventName: string, payload?: unknown) {
|
||||
const socket = socketRef.current;
|
||||
if (!socket || !socket.connected) {
|
||||
setError('소켓이 아직 연결되지 않았습니다.');
|
||||
return;
|
||||
}
|
||||
|
||||
setError(null);
|
||||
|
||||
if (payload === undefined) {
|
||||
socket.emit(eventName);
|
||||
return;
|
||||
}
|
||||
|
||||
socket.emit(eventName, payload);
|
||||
}
|
||||
|
||||
function buildAuctionActionPayload(): AuctionActionPayload {
|
||||
const currentAuction = latestAuctionRef.current ?? auction;
|
||||
return {
|
||||
@@ -889,12 +1018,19 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
return {
|
||||
auction: visibleAuction,
|
||||
chatMessages: visibleAuction ? chatMessages : [],
|
||||
reactions: visibleAuction && visibleConnectionStatus === 'connected' && reactionState.key === connectionKey
|
||||
? reactionState.items : [],
|
||||
isAuctionActionPending: Object.keys(pendingActionRequests).length > 0,
|
||||
isBidPending: Object.keys(pendingBidRequests).length > 0,
|
||||
pendingActionRequests,
|
||||
pendingBidRequests,
|
||||
resetAt,
|
||||
connectionStatus: visibleConnectionStatus,
|
||||
isSynchronized:
|
||||
synchronizationState.key === connectionKey &&
|
||||
synchronizationState.ready && visibleConnectionStatus === 'connected',
|
||||
historyUpdateCount:
|
||||
historyUpdateState.key === connectionKey ? historyUpdateState.count : 0,
|
||||
error: visibleError,
|
||||
bidLatencyDiagnostics,
|
||||
serverRoundTripMs: matchId ? serverRoundTripMs : null,
|
||||
@@ -989,8 +1125,22 @@ export function useAuctionSocket(matchId: string | undefined) {
|
||||
next() {
|
||||
emitAuctionAction('next', buildAuctionActionPayload());
|
||||
},
|
||||
sendChatMessage(payload: ChatMessagePayload) {
|
||||
emit('chat-message', payload);
|
||||
async sendReaction(kind: AuctionReactionKind) {
|
||||
const socket = socketRef.current;
|
||||
const reaction = await sendAuctionReaction(socket?.connected
|
||||
? () => socket.volatile.timeout(3000).emitWithAck('chat-reaction', { kind }) as Promise<AuctionReactionReply>
|
||||
: undefined);
|
||||
if (socketRef.current === socket && connectionKey) receiveReaction(reaction, connectionKey);
|
||||
},
|
||||
async sendChatMessage(payload: ChatMessagePayload) {
|
||||
const socket = socketRef.current;
|
||||
const message = await sendAuctionChatMessage(socket?.connected
|
||||
? () => socket.timeout(8000).emitWithAck('chat-message', payload) as Promise<ChatMessageReply>
|
||||
: undefined);
|
||||
if (socketRef.current === socket) {
|
||||
setChatMessages((current) => mergeChatMessages(current, [message]));
|
||||
}
|
||||
return message;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1002,15 +1152,6 @@ function createClientRequestId(): string {
|
||||
return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
|
||||
}
|
||||
|
||||
function resolveCurrentBidPointAmount(auction: ApiAuction): number {
|
||||
const bidPointAmount = Math.max(
|
||||
Number(auction.currentHighestBidPointAmount),
|
||||
Number(auction.currentBid),
|
||||
0,
|
||||
);
|
||||
return Number.isFinite(bidPointAmount) ? bidPointAmount : 0;
|
||||
}
|
||||
|
||||
// [AUCTION-DEBUG] 아래 텔레메트리 헬퍼들과 호출부는 조사 종료 후 제거 대상.
|
||||
type AuctionTelemetryAttributes = Record<
|
||||
string,
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 13 13" shape-rendering="crispEdges">
|
||||
<path fill="#2b1b12" d="M0 0h5v1h-5zM8 0h5v1h-5zM0 1h1v1h-1zM4 1h1v1h-1zM8 1h1v1h-1zM12 1h1v1h-1zM1 2h1v1h-1zM5 2h1v1h-1zM7 2h1v1h-1zM11 2h1v1h-1zM2 3h1v1h-1zM6 3h1v1h-1zM10 3h1v1h-1zM4 4h5v1h-5zM2 5h2v1h-2zM9 5h2v1h-2zM1 6h1v1h-1zM6 6h1v1h-1zM11 6h1v1h-1zM1 7h1v1h-1zM5 7h2v1h-2zM11 7h1v1h-1zM1 8h1v1h-1zM6 8h1v1h-1zM11 8h1v1h-1zM1 9h1v1h-1zM6 9h1v1h-1zM11 9h1v1h-1zM1 10h1v1h-1zM5 10h3v1h-3zM11 10h1v1h-1zM2 11h2v1h-2zM9 11h2v1h-2zM4 12h5v1h-5z"/>
|
||||
<path fill="#fff4a8" d="M4 5h1v1h-1zM2 6h1v1h-1zM2 7h1v1h-1z"/>
|
||||
<path fill="#ffd91a" d="M5 5h3v1h-3zM3 6h3v1h-3zM7 6h3v1h-3zM3 7h2v1h-2zM7 7h3v1h-3zM2 8h4v1h-4zM7 8h3v1h-3zM2 9h4v1h-4zM7 9h3v1h-3zM2 10h3v1h-3zM8 10h2v1h-2zM4 11h4v1h-4z"/>
|
||||
<path fill="#f08a24" d="M8 5h1v1h-1zM10 6h1v1h-1zM10 7h1v1h-1zM10 8h1v1h-1zM10 9h1v1h-1zM10 10h1v1h-1zM8 11h1v1h-1z"/>
|
||||
<path fill="#e5372b" d="M3 1h1v1h-1zM9 1h1v1h-1zM4 2h1v1h-1zM8 2h1v1h-1zM5 3h1v1h-1zM7 3h1v1h-1z"/>
|
||||
<path fill="#3b6fe0" d="M1 1h2v1h-2zM10 1h2v1h-2zM2 2h2v1h-2zM9 2h2v1h-2zM3 3h2v1h-2zM8 3h2v1h-2z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,6 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" shape-rendering="crispEdges">
|
||||
<path fill="#2b1b12" d="M2 0h11v1h-11zM0 1h3v1h-3zM12 1h3v1h-3zM0 2h1v1h-1zM2 2h1v1h-1zM7 2h1v1h-1zM12 2h1v1h-1zM14 2h1v1h-1zM0 3h1v1h-1zM2 3h1v1h-1zM6 3h2v1h-2zM12 3h1v1h-1zM14 3h1v1h-1zM0 4h1v1h-1zM2 4h1v1h-1zM7 4h1v1h-1zM12 4h1v1h-1zM14 4h1v1h-1zM0 5h3v1h-3zM7 5h1v1h-1zM12 5h3v1h-3zM2 6h1v1h-1zM6 6h3v1h-3zM12 6h1v1h-1zM3 7h1v1h-1zM11 7h1v1h-1zM4 8h1v1h-1zM10 8h1v1h-1zM5 9h1v1h-1zM9 9h1v1h-1zM6 10h1v1h-1zM8 10h1v1h-1zM6 11h1v1h-1zM8 11h1v1h-1zM4 12h2v1h-2zM9 12h2v1h-2zM3 13h1v1h-1zM11 13h1v1h-1zM3 14h9v1h-9z"/>
|
||||
<path fill="#fff4a8" d="M3 1h1v1h-1zM3 2h1v1h-1zM3 3h1v1h-1zM3 4h1v1h-1zM3 5h1v1h-1zM3 6h1v1h-1zM4 13h1v1h-1z"/>
|
||||
<path fill="#ffd91a" d="M4 1h7v1h-7zM4 2h3v1h-3zM8 2h3v1h-3zM4 3h2v1h-2zM8 3h3v1h-3zM4 4h3v1h-3zM8 4h3v1h-3zM4 5h3v1h-3zM8 5h3v1h-3zM4 6h2v1h-2zM9 6h2v1h-2zM4 7h6v1h-6zM5 8h4v1h-4zM6 9h2v1h-2zM7 10h1v1h-1zM6 12h2v1h-2zM5 13h5v1h-5z"/>
|
||||
<path fill="#f08a24" d="M11 1h1v1h-1zM11 2h1v1h-1zM11 3h1v1h-1zM11 4h1v1h-1zM11 5h1v1h-1zM11 6h1v1h-1zM10 7h1v1h-1zM9 8h1v1h-1zM8 9h1v1h-1zM7 11h1v1h-1zM8 12h1v1h-1zM10 13h1v1h-1z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,8 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 15" shape-rendering="crispEdges">
|
||||
<path fill="#2b1b12" d="M2 0h11v1h-11zM0 1h3v1h-3zM12 1h3v1h-3zM0 2h1v1h-1zM2 2h1v1h-1zM12 2h1v1h-1zM14 2h1v1h-1zM0 3h1v1h-1zM2 3h1v1h-1zM12 3h1v1h-1zM14 3h1v1h-1zM0 4h1v1h-1zM2 4h1v1h-1zM12 4h1v1h-1zM14 4h1v1h-1zM0 5h3v1h-3zM12 5h3v1h-3zM2 6h1v1h-1zM12 6h1v1h-1zM3 7h1v1h-1zM11 7h1v1h-1zM4 8h1v1h-1zM10 8h1v1h-1zM5 9h1v1h-1zM9 9h1v1h-1zM6 10h1v1h-1zM8 10h1v1h-1zM6 11h1v1h-1zM8 11h1v1h-1zM4 12h2v1h-2zM9 12h2v1h-2zM3 13h1v1h-1zM11 13h1v1h-1zM3 14h9v1h-9z"/>
|
||||
<path fill="#fff4a8" d="M3 1h1v1h-1zM3 2h1v1h-1zM3 3h1v1h-1zM3 4h1v1h-1zM3 5h1v1h-1zM3 6h1v1h-1z"/>
|
||||
<path fill="#ffd91a" d="M4 1h7v1h-7zM4 2h3v1h-3zM8 2h3v1h-3zM4 3h2v1h-2zM9 3h2v1h-2zM4 4h3v1h-3zM8 4h3v1h-3zM4 5h7v1h-7zM4 6h7v1h-7zM4 7h6v1h-6zM5 8h4v1h-4zM6 9h2v1h-2zM7 10h1v1h-1zM6 12h2v1h-2z"/>
|
||||
<path fill="#f08a24" d="M11 1h1v1h-1zM11 2h1v1h-1zM11 3h1v1h-1zM11 4h1v1h-1zM11 5h1v1h-1zM11 6h1v1h-1zM10 7h1v1h-1zM9 8h1v1h-1zM8 9h1v1h-1zM7 11h1v1h-1zM8 12h1v1h-1z"/>
|
||||
<path fill="#e5372b" d="M4 13h7v1h-7z"/>
|
||||
<path fill="#ffffff" d="M7 2h1v1h-1zM6 3h3v1h-3zM7 4h1v1h-1z"/>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
@@ -0,0 +1,497 @@
|
||||
import { useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
||||
import { Badge } from "@astryxdesign/core/Badge";
|
||||
import { Button } from "@astryxdesign/core/Button";
|
||||
import {
|
||||
ChatComposer,
|
||||
ChatMessage,
|
||||
ChatMessageBubble,
|
||||
ChatMessageList,
|
||||
ChatMessageMetadata,
|
||||
} from "@astryxdesign/core/Chat";
|
||||
import { StatusDot } from "@astryxdesign/core/StatusDot";
|
||||
import { ArrowDown, RotateCcw, SendHorizontal } from "lucide-react";
|
||||
import type { ApiAuctionChatMessage } from "../api/types";
|
||||
import type { useAuctionSocket } from "../api/useAuctionSocket";
|
||||
import type { AuctionReactionKind } from '@lolympus/contracts';
|
||||
import { AuctionReactionPicker } from './AuctionReactionPicker';
|
||||
import './auction-reactions.css';
|
||||
import "./auction-chat.css";
|
||||
|
||||
type OutgoingMessage = ApiAuctionChatMessage & {
|
||||
clientMessageId: string;
|
||||
status: "sending" | "error";
|
||||
error?: string;
|
||||
};
|
||||
|
||||
type Props = {
|
||||
messages: ApiAuctionChatMessage[];
|
||||
connectionStatus: ReturnType<typeof useAuctionSocket>["connectionStatus"];
|
||||
senderLabel: string;
|
||||
currentUserId?: string;
|
||||
isOperator?: boolean;
|
||||
teams: readonly { captainUserId: string; teamIndex: number }[];
|
||||
onSend: (
|
||||
message: string,
|
||||
clientMessageId: string,
|
||||
) => Promise<ApiAuctionChatMessage>;
|
||||
onReact: (kind: AuctionReactionKind) => Promise<void>;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
const timeFormatter = new Intl.DateTimeFormat("ko-KR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
});
|
||||
|
||||
function resizeInput(input: HTMLTextAreaElement) {
|
||||
input.style.height = "auto";
|
||||
const maxHeight = Number.parseFloat(getComputedStyle(input).maxHeight);
|
||||
input.style.height = `${Math.min(input.scrollHeight, maxHeight)}px`;
|
||||
}
|
||||
|
||||
export function AuctionChatPanel({
|
||||
messages,
|
||||
connectionStatus,
|
||||
senderLabel,
|
||||
currentUserId,
|
||||
isOperator,
|
||||
teams,
|
||||
onSend,
|
||||
onReact,
|
||||
className = "",
|
||||
}: Props) {
|
||||
const titleId = useId();
|
||||
const hintId = useId();
|
||||
const [draft, setDraft] = useState("");
|
||||
const [outbox, setOutbox] = useState<OutgoingMessage[]>([]);
|
||||
const [hasNewMessages, setHasNewMessages] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const contentRef = useRef<HTMLDivElement>(null);
|
||||
const pinnedRef = useRef(true);
|
||||
const lastMessageIdRef = useRef<string | undefined>(undefined);
|
||||
const anchorRef = useRef<{ id: string; offset: number } | null>(null);
|
||||
const sendingRef = useRef(new Set<string>());
|
||||
const [ownRequestIds, setOwnRequestIds] = useState(new Set<string>());
|
||||
const connected = connectionStatus === "connected";
|
||||
const canSend = connected && draft.trim().length > 0 && draft.length <= 300;
|
||||
const status = connected
|
||||
? "연결됨"
|
||||
: connectionStatus === "connecting" || connectionStatus === "idle"
|
||||
? "연결 중"
|
||||
: "연결 끊김";
|
||||
const captainTeams = useMemo(
|
||||
() => new Map(teams.map((team) => [team.captainUserId, team.teamIndex])),
|
||||
[teams],
|
||||
);
|
||||
const ownTeam = currentUserId ? captainTeams.get(currentUserId) : undefined;
|
||||
const ownRole = isOperator
|
||||
? "운영진"
|
||||
: ownTeam !== undefined
|
||||
? `${ownTeam}팀 팀장`
|
||||
: undefined;
|
||||
|
||||
const confirmedRequests = new Set(
|
||||
messages.map((message) => message.clientMessageId),
|
||||
);
|
||||
const visibleMessages = [
|
||||
...messages,
|
||||
...outbox.filter(
|
||||
(message) => !confirmedRequests.has(message.clientMessageId),
|
||||
),
|
||||
].sort((a, b) => Date.parse(a.sentAt) - Date.parse(b.sentAt));
|
||||
const groups: (ApiAuctionChatMessage | OutgoingMessage)[][] = [];
|
||||
for (const message of visibleMessages) {
|
||||
const previousGroup = groups.at(-1);
|
||||
const previous = previousGroup?.at(-1);
|
||||
const sameAuthor =
|
||||
previous &&
|
||||
(message.userId
|
||||
? previous.userId === message.userId
|
||||
: !previous.userId && previous.displayName === message.displayName);
|
||||
if (
|
||||
previous &&
|
||||
sameAuthor &&
|
||||
previous.senderRole === message.senderRole &&
|
||||
!("status" in previous) &&
|
||||
!("status" in message) &&
|
||||
Date.parse(message.sentAt) - Date.parse(previous.sentAt) < 5 * 60_000 &&
|
||||
new Date(message.sentAt).toDateString() ===
|
||||
new Date(previous.sentAt).toDateString()
|
||||
) {
|
||||
previousGroup!.push(message);
|
||||
} else groups.push([message]);
|
||||
}
|
||||
|
||||
function rememberScroll() {
|
||||
const container = scrollRef.current;
|
||||
if (!container) return;
|
||||
pinnedRef.current =
|
||||
container.scrollHeight - container.scrollTop - container.clientHeight <
|
||||
40;
|
||||
if (pinnedRef.current) setHasNewMessages(false);
|
||||
const top = container.getBoundingClientRect().top;
|
||||
const anchor = Array.from(
|
||||
container.querySelectorAll<HTMLElement>("[data-chat-message-id]"),
|
||||
).find((element) => element.getBoundingClientRect().bottom > top);
|
||||
anchorRef.current = anchor
|
||||
? {
|
||||
id: anchor.dataset.chatMessageId!,
|
||||
offset: anchor.getBoundingClientRect().top - top,
|
||||
}
|
||||
: null;
|
||||
}
|
||||
|
||||
function scrollToLatest() {
|
||||
const container = scrollRef.current;
|
||||
if (container) container.scrollTop = container.scrollHeight;
|
||||
pinnedRef.current = true;
|
||||
setHasNewMessages(false);
|
||||
}
|
||||
|
||||
// Track actual message IDs, including when the server's 200-message window
|
||||
// rolls over without changing the list length. Preserve the visible anchor.
|
||||
const latestId = visibleMessages.at(-1)?.id;
|
||||
useLayoutEffect(() => {
|
||||
const container = scrollRef.current;
|
||||
if (!container) return;
|
||||
const isNew = latestId !== lastMessageIdRef.current;
|
||||
lastMessageIdRef.current = latestId;
|
||||
if (pinnedRef.current) container.scrollTop = container.scrollHeight;
|
||||
else if (anchorRef.current) {
|
||||
const anchor = Array.from(
|
||||
container.querySelectorAll<HTMLElement>("[data-chat-message-id]"),
|
||||
).find(
|
||||
(element) => element.dataset.chatMessageId === anchorRef.current?.id,
|
||||
);
|
||||
if (anchor)
|
||||
container.scrollTop +=
|
||||
anchor.getBoundingClientRect().top -
|
||||
container.getBoundingClientRect().top -
|
||||
anchorRef.current.offset;
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (pinnedRef.current) setHasNewMessages(false);
|
||||
else if (isNew) setHasNewMessages(true);
|
||||
// A broadcast can arrive even if its acknowledgement is lost. Retire
|
||||
// confirmed drafts now so they cannot reappear after history rolls over.
|
||||
const confirmed = new Set(
|
||||
messages.map((message) => message.clientMessageId),
|
||||
);
|
||||
setOutbox((current) => {
|
||||
const remaining = current.filter(
|
||||
(message) => !confirmed.has(message.clientMessageId),
|
||||
);
|
||||
return remaining.length === current.length ? current : remaining;
|
||||
});
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [messages, outbox, latestId]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const input = textareaRef.current;
|
||||
if (!input) return;
|
||||
resizeInput(input);
|
||||
}, [draft]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
let inputWidth = 0;
|
||||
let frame = 0;
|
||||
const observer = new ResizeObserver(() => {
|
||||
// Defer writes to the next frame: resizing an observed input inside
|
||||
// the observer callback causes ResizeObserver loop notifications.
|
||||
cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(() => {
|
||||
const input = textareaRef.current;
|
||||
if (input && input.clientWidth !== inputWidth) {
|
||||
inputWidth = input.clientWidth;
|
||||
resizeInput(input);
|
||||
}
|
||||
const container = scrollRef.current;
|
||||
if (container && pinnedRef.current)
|
||||
container.scrollTop = container.scrollHeight;
|
||||
});
|
||||
});
|
||||
if (scrollRef.current) observer.observe(scrollRef.current);
|
||||
if (contentRef.current) observer.observe(contentRef.current);
|
||||
if (textareaRef.current) observer.observe(textareaRef.current);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
cancelAnimationFrame(frame);
|
||||
};
|
||||
}, []);
|
||||
|
||||
async function deliver(message: OutgoingMessage) {
|
||||
if (sendingRef.current.has(message.clientMessageId)) return;
|
||||
sendingRef.current.add(message.clientMessageId);
|
||||
setOutbox((current) =>
|
||||
current.map((entry) =>
|
||||
entry.id === message.id
|
||||
? { ...entry, status: "sending", error: undefined }
|
||||
: entry,
|
||||
),
|
||||
);
|
||||
try {
|
||||
await onSend(message.message, message.clientMessageId);
|
||||
setOutbox((current) =>
|
||||
current.filter((entry) => entry.id !== message.id),
|
||||
);
|
||||
} catch (error) {
|
||||
setOutbox((current) =>
|
||||
current.map((entry) =>
|
||||
entry.id === message.id
|
||||
? {
|
||||
...entry,
|
||||
status: "error",
|
||||
error:
|
||||
error instanceof Error
|
||||
? error.message
|
||||
: "전송하지 못했습니다.",
|
||||
}
|
||||
: entry,
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
sendingRef.current.delete(message.clientMessageId);
|
||||
}
|
||||
}
|
||||
|
||||
function submit(value = draft) {
|
||||
if (!connected || !value.trim() || value.length > 300) return;
|
||||
const clientMessageId = crypto.randomUUID();
|
||||
const message: OutgoingMessage = {
|
||||
id: clientMessageId,
|
||||
clientMessageId,
|
||||
userId: currentUserId,
|
||||
displayName: senderLabel,
|
||||
senderRole: isOperator ? "operator" : undefined,
|
||||
message: value.trim(),
|
||||
sentAt: new Date().toISOString(),
|
||||
status: "sending",
|
||||
};
|
||||
setOwnRequestIds((current) => new Set([...current, clientMessageId]));
|
||||
setOutbox((current) => [...current, message]);
|
||||
setDraft("");
|
||||
pinnedRef.current = true;
|
||||
void deliver(message);
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
|
||||
return (
|
||||
<section
|
||||
className={`auction-chat-panel ${className}`}
|
||||
aria-labelledby={titleId}
|
||||
>
|
||||
<header className="auction-chat-header">
|
||||
<h2 id={titleId}>경매 채팅</h2>
|
||||
<span className="auction-chat-connection" role="status">
|
||||
<StatusDot
|
||||
variant={connected ? "success" : "neutral"}
|
||||
label={status}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
{status}
|
||||
</span>
|
||||
</header>
|
||||
<div className="auction-chat-conversation">
|
||||
<div
|
||||
className="auction-chat-scroll"
|
||||
ref={scrollRef}
|
||||
onScroll={rememberScroll}
|
||||
tabIndex={0}
|
||||
aria-label="경매 대화 내역"
|
||||
>
|
||||
<ChatMessageList
|
||||
ref={contentRef}
|
||||
density="compact"
|
||||
gap={3}
|
||||
aria-label="경매 채팅 메시지"
|
||||
emptyState={
|
||||
<div className="auction-chat-empty">
|
||||
아직 대화가 없습니다.
|
||||
<br />
|
||||
팀장과 운영진에게 메시지를 남겨 보세요.
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{groups.map((group) => {
|
||||
const first = group[0];
|
||||
const last = group[group.length - 1];
|
||||
const own = Boolean(
|
||||
(currentUserId && first.userId === currentUserId) ||
|
||||
(first.clientMessageId &&
|
||||
ownRequestIds.has(first.clientMessageId)),
|
||||
);
|
||||
const team = first.userId
|
||||
? captainTeams.get(first.userId)
|
||||
: undefined;
|
||||
const role =
|
||||
first.senderRole === "operator"
|
||||
? "운영진"
|
||||
: team !== undefined
|
||||
? `${team}팀 팀장`
|
||||
: undefined;
|
||||
const outgoing = "status" in last ? last : undefined;
|
||||
return (
|
||||
<ChatMessage
|
||||
key={first.id}
|
||||
sender={own ? "user" : "assistant"}
|
||||
name={
|
||||
<span className="auction-chat-author">
|
||||
<span
|
||||
className="auction-chat-name"
|
||||
title={first.displayName}
|
||||
>
|
||||
{first.displayName}
|
||||
</span>
|
||||
{role && (
|
||||
<Badge
|
||||
variant={
|
||||
first.senderRole === "operator"
|
||||
? "purple"
|
||||
: "neutral"
|
||||
}
|
||||
label={role}
|
||||
/>
|
||||
)}
|
||||
{own && <span className="auction-chat-self">나</span>}
|
||||
<time
|
||||
dateTime={last.sentAt}
|
||||
title={new Date(last.sentAt).toLocaleString("ko-KR")}
|
||||
>
|
||||
{timeFormatter.format(new Date(last.sentAt))}
|
||||
</time>
|
||||
</span>
|
||||
}
|
||||
metadata={
|
||||
outgoing && (
|
||||
<ChatMessageMetadata
|
||||
timestamp={
|
||||
<span
|
||||
className="auction-chat-delivery"
|
||||
data-failed={outgoing.status === "error"}
|
||||
>
|
||||
{outgoing.status === "sending" ? (
|
||||
<span role="status">전송 중…</span>
|
||||
) : (
|
||||
<>
|
||||
<span role="alert">{outgoing.error}</span>
|
||||
<Button
|
||||
label="다시 보내기"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
isDisabled={!connected}
|
||||
icon={
|
||||
<RotateCcw size={14} aria-hidden="true" />
|
||||
}
|
||||
onClick={() => void deliver(outgoing)}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
>
|
||||
{group.map((message, index) => (
|
||||
<ChatMessageBubble
|
||||
key={message.id}
|
||||
data-chat-message-id={message.id}
|
||||
group={
|
||||
group.length === 1
|
||||
? undefined
|
||||
: index === 0
|
||||
? "first"
|
||||
: index === group.length - 1
|
||||
? "last"
|
||||
: "middle"
|
||||
}
|
||||
>
|
||||
{message.message}
|
||||
</ChatMessageBubble>
|
||||
))}
|
||||
</ChatMessage>
|
||||
);
|
||||
})}
|
||||
</ChatMessageList>
|
||||
</div>
|
||||
{hasNewMessages && (
|
||||
<div className="auction-chat-new-messages">
|
||||
<Button
|
||||
label="새 메시지"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
icon={<ArrowDown size={14} aria-hidden="true" />}
|
||||
onClick={scrollToLatest}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="auction-chat-compose-area">
|
||||
<div className="auction-chat-sender">
|
||||
<span title={senderLabel}>
|
||||
{ownRole ? `${ownRole} · ` : ""}
|
||||
{senderLabel}
|
||||
</span>
|
||||
{draft.length >= 240 && (
|
||||
<span
|
||||
className="auction-chat-count"
|
||||
data-limit={draft.length === 300}
|
||||
>
|
||||
{draft.length}/300
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ChatComposer
|
||||
className="auction-chat-composer"
|
||||
density="compact"
|
||||
elevation="none"
|
||||
value={draft}
|
||||
onChange={setDraft}
|
||||
onSubmit={submit}
|
||||
input={
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={draft}
|
||||
rows={1}
|
||||
maxLength={300}
|
||||
aria-label="경매 채팅 메시지"
|
||||
aria-describedby={hintId}
|
||||
placeholder="메시지 입력"
|
||||
enterKeyHint="send"
|
||||
onChange={(event) => setDraft(event.target.value)}
|
||||
onKeyDown={(event) => {
|
||||
// Product choice: Enter always sends, including during composition.
|
||||
// Shift+Enter retains the existing newline shortcut.
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
submit(event.currentTarget.value);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
}
|
||||
sendActions={<AuctionReactionPicker connected={connected} onReact={onReact} />}
|
||||
sendButton={
|
||||
<Button
|
||||
className="auction-chat-send"
|
||||
label="메시지 전송"
|
||||
variant="primary"
|
||||
size="md"
|
||||
isIconOnly
|
||||
isDisabled={!canSend}
|
||||
onClick={() => submit()}
|
||||
icon={<SendHorizontal size={18} aria-hidden="true" />}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<p className="auction-chat-hint" id={hintId}>
|
||||
{connected
|
||||
? "Enter 전송 · Shift+Enter 줄바꿈"
|
||||
: "연결되면 전송할 수 있습니다. 작성 내용은 유지됩니다."}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { CSSProperties } from "react";
|
||||
import { createPortal } from "react-dom";
|
||||
import {
|
||||
AUCTION_REACTIONS,
|
||||
type ActiveAuctionReaction,
|
||||
} from "../api/auction-reactions";
|
||||
import "./auction-reactions.css";
|
||||
|
||||
function reactionStyle(id: string): CSSProperties {
|
||||
let hash = 0;
|
||||
for (const character of id)
|
||||
hash = (hash * 31 + character.charCodeAt(0)) >>> 0;
|
||||
return {
|
||||
"--reaction-left": `${8 + (hash % 78)}%`,
|
||||
"--reaction-drift": `${(hash % 65) - 32}px`,
|
||||
"--reaction-tilt": `${(hash % 21) - 10}deg`,
|
||||
} as CSSProperties;
|
||||
}
|
||||
|
||||
export function AuctionReactionLayer({
|
||||
reactions,
|
||||
}: {
|
||||
reactions: ActiveAuctionReaction[];
|
||||
}) {
|
||||
if (typeof document === "undefined") return null;
|
||||
const latest = reactions.at(-1);
|
||||
return createPortal(
|
||||
<>
|
||||
<div className="auction-reaction-layer" aria-hidden="true">
|
||||
{reactions.map((reaction) => (
|
||||
<div
|
||||
key={reaction.id}
|
||||
className="auction-floating-reaction"
|
||||
data-reaction-id={reaction.id}
|
||||
style={reactionStyle(reaction.id)}
|
||||
>
|
||||
<span className="auction-floating-emoji">
|
||||
{AUCTION_REACTIONS[reaction.kind].emoji}
|
||||
</span>
|
||||
<span className="auction-floating-name">
|
||||
{reaction.displayName}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<span
|
||||
className="sr-only"
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{latest
|
||||
? `${latest.displayName}님의 ${AUCTION_REACTIONS[latest.kind].label} 반응`
|
||||
: ""}
|
||||
</span>
|
||||
</>,
|
||||
document.body,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { Button } from "@astryxdesign/core/Button";
|
||||
import { Popover } from "@astryxdesign/core/Popover";
|
||||
import { Smile } from "lucide-react";
|
||||
import type { AuctionReactionKind } from "@lolympus/contracts";
|
||||
import { AUCTION_REACTIONS } from "../api/auction-reactions";
|
||||
|
||||
export function AuctionReactionPicker({
|
||||
connected,
|
||||
onReact,
|
||||
}: {
|
||||
connected: boolean;
|
||||
onReact: (kind: AuctionReactionKind) => Promise<void>;
|
||||
}) {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [coolingDown, setCoolingDown] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const coolingDownRef = useRef(false);
|
||||
const requestSequence = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
if (!coolingDown) return;
|
||||
const timer = setTimeout(() => {
|
||||
coolingDownRef.current = false;
|
||||
setCoolingDown(false);
|
||||
}, 450);
|
||||
return () => clearTimeout(timer);
|
||||
}, [coolingDown]);
|
||||
|
||||
const handleReaction = useCallback(
|
||||
async (kind: AuctionReactionKind) => {
|
||||
if (!connected || coolingDownRef.current) return;
|
||||
coolingDownRef.current = true;
|
||||
const sequence = ++requestSequence.current;
|
||||
setCoolingDown(true);
|
||||
setError(null);
|
||||
try {
|
||||
await onReact(kind);
|
||||
} catch (cause) {
|
||||
if (sequence === requestSequence.current) {
|
||||
setError(
|
||||
cause instanceof Error
|
||||
? cause.message
|
||||
: "반응을 보내지 못했습니다.",
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
[connected, onReact],
|
||||
);
|
||||
|
||||
return (
|
||||
<Popover
|
||||
label="이모지 반응"
|
||||
closeButtonLabel="반응 선택 닫기"
|
||||
placement="above"
|
||||
alignment="end"
|
||||
width={260}
|
||||
isOpen={isOpen}
|
||||
onOpenChange={setIsOpen}
|
||||
content={
|
||||
<div className="auction-reaction-picker">
|
||||
<p className="auction-reaction-picker-title">이모지 반응</p>
|
||||
<p className="auction-reaction-picker-description">
|
||||
선택하면 모두에게 보여요
|
||||
</p>
|
||||
<div
|
||||
className="auction-reaction-options"
|
||||
role="group"
|
||||
aria-label="반응 선택"
|
||||
>
|
||||
{(
|
||||
Object.entries(AUCTION_REACTIONS) as [
|
||||
AuctionReactionKind,
|
||||
{ emoji: string; label: string },
|
||||
][]
|
||||
).map(([kind, { emoji, label }]) => (
|
||||
<Button
|
||||
key={kind}
|
||||
label={`${label} 반응 보내기`}
|
||||
variant="ghost"
|
||||
size="lg"
|
||||
isIconOnly
|
||||
isDisabled={!connected || coolingDown}
|
||||
className="auction-reaction-option"
|
||||
onClick={() => void handleReaction(kind)}
|
||||
icon={<span aria-hidden="true">{emoji}</span>}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
{(!connected || error) && (
|
||||
<p className="auction-reaction-error" role="status">
|
||||
{!connected ? "연결되면 반응을 보낼 수 있습니다." : error}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<Button
|
||||
label="이모지 반응"
|
||||
variant="ghost"
|
||||
size="md"
|
||||
isIconOnly
|
||||
className="auction-chat-reaction-trigger"
|
||||
icon={<Smile size={20} aria-hidden="true" />}
|
||||
/>
|
||||
</Popover>
|
||||
);
|
||||
}
|
||||
@@ -11,11 +11,77 @@
|
||||
border-radius: 1.25rem;
|
||||
}
|
||||
|
||||
.lts-hall-player,
|
||||
.lts-hall-portrait {
|
||||
.lts-hall-team-name {
|
||||
position: relative;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
color: var(--lts-gold);
|
||||
filter: drop-shadow(0 0.5px 0 color-mix(in srgb, var(--lts-gold) 20%, transparent));
|
||||
}
|
||||
|
||||
@supports (background-clip: text) or (-webkit-background-clip: text) {
|
||||
.lts-hall-team-name {
|
||||
background-image:
|
||||
linear-gradient(
|
||||
115deg,
|
||||
transparent calc(50% - 9px),
|
||||
color-mix(in srgb, var(--color-brand-gold) 45%, transparent) calc(50% - 5px),
|
||||
color-mix(in srgb, var(--color-brand-gold) 18%, var(--color-palette-white)) 50%,
|
||||
color-mix(in srgb, var(--color-brand-gold) 45%, transparent) calc(50% + 5px),
|
||||
transparent calc(50% + 9px)
|
||||
),
|
||||
linear-gradient(
|
||||
175deg,
|
||||
var(--lts-gold) 0%,
|
||||
color-mix(in srgb, var(--lts-gold) 45%, var(--color-brand-gold)) 28%,
|
||||
var(--color-brand-gold) 39%,
|
||||
color-mix(in srgb, var(--color-brand-gold) 65%, var(--color-palette-white)) 44%,
|
||||
var(--lts-gold) 53%,
|
||||
color-mix(in srgb, var(--lts-gold) 70%, var(--color-brand-gold)) 72%,
|
||||
var(--color-brand-gold) 100%
|
||||
);
|
||||
background-size: 250% 100%, 100% 100%;
|
||||
background-position: 100% 0, 0 0;
|
||||
background-repeat: no-repeat;
|
||||
-webkit-background-clip: text;
|
||||
background-clip: text;
|
||||
color: transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.lts-hall-team-name::before,
|
||||
.lts-hall-team-name::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
pointer-events: none;
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
background: var(--color-brand-gold);
|
||||
clip-path: polygon(50% 0, 62% 37%, 100% 50%, 62% 63%, 50% 100%, 38% 63%, 0 50%, 38% 37%);
|
||||
opacity: 0;
|
||||
transform: scale(0.4) rotate(-15deg);
|
||||
}
|
||||
|
||||
.lts-hall-team-name::before {
|
||||
top: -3px;
|
||||
right: 22%;
|
||||
}
|
||||
|
||||
.lts-hall-team-name::after {
|
||||
top: 45%;
|
||||
right: -5px;
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
|
||||
.lts-hall-player {
|
||||
border-radius: 0.75rem;
|
||||
}
|
||||
|
||||
.lts-hall-portrait {
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.lts-hall-pixel {
|
||||
image-rendering: pixelated;
|
||||
}
|
||||
@@ -25,9 +91,69 @@
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: no-preference) {
|
||||
.lts-hall[data-intro] .lts-hall-team-name {
|
||||
animation: lts-hall-gold-shine 4s cubic-bezier(0.4, 0, 0.2, 1) infinite;
|
||||
}
|
||||
|
||||
.lts-hall[data-intro] .lts-hall-team-name::before,
|
||||
.lts-hall[data-intro] .lts-hall-team-name::after {
|
||||
animation: lts-hall-gold-sparkle 4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.lts-hall[data-intro] .lts-hall-team-name::after {
|
||||
animation-delay: 120ms;
|
||||
}
|
||||
|
||||
.lts-hall:not([data-motion-active]) .lts-hall-team-name,
|
||||
.lts-hall:not([data-motion-active]) .lts-hall-team-name::before,
|
||||
.lts-hall:not([data-motion-active]) .lts-hall-team-name::after {
|
||||
animation-play-state: paused;
|
||||
}
|
||||
|
||||
.lts-hall[data-intro] .lts-hall-portrait img {
|
||||
animation: lts-hall-reveal 110ms linear
|
||||
calc(180ms + var(--lts-hall-order) * 48ms) backwards;
|
||||
animation: lts-hall-reveal 6s linear
|
||||
calc(180ms + var(--lts-hall-order) * 48ms) infinite backwards;
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.lts-hall-team-name {
|
||||
background: none;
|
||||
color: CanvasText;
|
||||
filter: none;
|
||||
}
|
||||
|
||||
.lts-hall-team-name::before,
|
||||
.lts-hall-team-name::after {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes lts-hall-gold-shine {
|
||||
0%,
|
||||
5% {
|
||||
background-position: 100% 0, 0 0;
|
||||
}
|
||||
|
||||
/* Sweep from 0.2s to 0.85s, then leave the gold finish at rest. */
|
||||
21.25%,
|
||||
100% {
|
||||
background-position: 0 0, 0 0;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes lts-hall-gold-sparkle {
|
||||
0%,
|
||||
16.25%,
|
||||
23.25%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: scale(0.4) rotate(-15deg);
|
||||
}
|
||||
|
||||
19.5% {
|
||||
opacity: 0.9;
|
||||
transform: scale(1) rotate(15deg);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +167,9 @@
|
||||
);
|
||||
}
|
||||
|
||||
to {
|
||||
/* Reveal for 110ms, then stay visible for the rest of the six-second cycle. */
|
||||
1.833333%,
|
||||
100% {
|
||||
clip-path: polygon(
|
||||
0 0,
|
||||
calc(100% + var(--lts-hall-slant)) 0,
|
||||
|
||||
@@ -7,7 +7,7 @@ import captainCrown from '../assets/captain-crown.svg';
|
||||
import pixelTrophy from '../assets/pixel-trophy.svg';
|
||||
import { profileIconUrl } from '../lib/ddragon';
|
||||
import { positionLabel } from '../lib/league';
|
||||
import { pageWidthClass } from '../ui/layout';
|
||||
import { pageWidthClass, Skeleton } from '../ui';
|
||||
import './HomeHallOfFame.css';
|
||||
|
||||
const POSITION_ORDER: MatchPosition[] = ['TOP', 'JGL', 'MID', 'ADC', 'SUP'];
|
||||
@@ -20,11 +20,13 @@ export default function HomeHallOfFame({
|
||||
const hallOfFame = useHallOfFame();
|
||||
const sectionRef = useRef<HTMLElement>(null);
|
||||
const [playIntro, setPlayIntro] = useState(false);
|
||||
const [isMotionActive, setIsMotionActive] = useState(false);
|
||||
const isContentReady = introReady && hallOfFame.isSuccess;
|
||||
|
||||
useEffect(() => {
|
||||
const section = sectionRef.current;
|
||||
if (
|
||||
!introReady ||
|
||||
!isContentReady ||
|
||||
!section ||
|
||||
typeof IntersectionObserver === 'undefined' ||
|
||||
window.matchMedia('(prefers-reduced-motion: reduce)').matches
|
||||
@@ -32,15 +34,23 @@ export default function HomeHallOfFame({
|
||||
return;
|
||||
}
|
||||
|
||||
let isInView = false;
|
||||
const updateMotion = () => setIsMotionActive(isInView && !document.hidden);
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry?.isIntersecting) setPlayIntro(true);
|
||||
isInView = entry?.isIntersecting ?? false;
|
||||
if (isInView) setPlayIntro(true);
|
||||
updateMotion();
|
||||
},
|
||||
{ threshold: 0.5 },
|
||||
);
|
||||
observer.observe(section);
|
||||
return () => observer.disconnect();
|
||||
}, [introReady]);
|
||||
document.addEventListener('visibilitychange', updateMotion);
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
document.removeEventListener('visibilitychange', updateMotion);
|
||||
};
|
||||
}, [isContentReady]);
|
||||
|
||||
const featuredMatch = hallOfFame.data?.match;
|
||||
|
||||
@@ -50,11 +60,16 @@ export default function HomeHallOfFame({
|
||||
<section
|
||||
ref={sectionRef}
|
||||
aria-label="명예의 전당"
|
||||
aria-busy={hallOfFame.isPending}
|
||||
className={`${pageWidthClass()} lts-hall grid gap-8 py-6 md:py-8 lg:grid-cols-[minmax(0,1fr)_20rem]`}
|
||||
data-intro={playIntro ? '' : undefined}
|
||||
data-motion-active={isMotionActive ? '' : undefined}
|
||||
>
|
||||
{hallOfFame.isPending ? (
|
||||
<p role="status">명예의 전당을 불러오는 중</p>
|
||||
<>
|
||||
<span role="status" className="sr-only">명예의 전당을 불러오는 중</span>
|
||||
<FeaturedTeamSkeleton />
|
||||
</>
|
||||
) : hallOfFame.isError ? (
|
||||
<p role="status">
|
||||
명예의 전당을 불러오지 못했습니다.{' '}
|
||||
@@ -75,6 +90,37 @@ export default function HomeHallOfFame({
|
||||
);
|
||||
}
|
||||
|
||||
function FeaturedTeamSkeleton() {
|
||||
return (
|
||||
<div className="lts-hall-card flex min-w-0 flex-col gap-4 bg-card p-5 sm:flex-row sm:gap-5">
|
||||
<div className="min-w-0 sm:w-36 sm:shrink-0">
|
||||
<h2 className="text-sm font-semibold text-content-muted">명예의 전당</h2>
|
||||
<div className="mt-2">
|
||||
<Skeleton width="80%" height={30} />
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<Skeleton width="90%" height={16} index={1} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-px bg-line sm:h-auto sm:w-px" aria-hidden="true" />
|
||||
<div className="grid min-w-0 flex-1 gap-1 sm:grid-cols-5 sm:content-center sm:items-start" aria-hidden="true">
|
||||
{POSITION_ORDER.map((position, index) => (
|
||||
<div key={position} className="flex min-w-0 items-center gap-2.5 px-2 py-2 sm:flex-col sm:gap-2 sm:py-3">
|
||||
<div className="size-10 shrink-0 sm:size-13">
|
||||
<Skeleton radius="rounded" index={index} />
|
||||
</div>
|
||||
<div className="min-w-0 flex-1 space-y-1 sm:w-full sm:flex-none sm:[&>div]:mx-auto">
|
||||
<Skeleton width={24} height={16} index={index} />
|
||||
<Skeleton width="80%" height={16} index={index} />
|
||||
<Skeleton width="50%" height={12} index={index} />
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function FeaturedTeam({
|
||||
team,
|
||||
match,
|
||||
@@ -96,7 +142,7 @@ function FeaturedTeam({
|
||||
>
|
||||
명예의 전당
|
||||
</span>
|
||||
<span className="mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
|
||||
<span className="lts-hall-team-name mt-2 block text-2xl leading-tight font-extrabold tracking-tight [overflow-wrap:anywhere]">
|
||||
{team.name}
|
||||
</span>
|
||||
<span className="mt-1 flex items-center gap-1 text-xs font-semibold text-content-muted">
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { UserRound } from "lucide-react";
|
||||
import { useDdragonManifest } from "../api/hooks";
|
||||
import captainCrown from "../assets/captain-crown.svg";
|
||||
import { profileIconUrl } from "../lib/ddragon";
|
||||
|
||||
const AVATAR_SIZE = {
|
||||
sm: "size-7",
|
||||
md: "size-10",
|
||||
} as const;
|
||||
|
||||
const CROWN_SIZE = {
|
||||
sm: "-right-1 -top-1.5 w-4",
|
||||
md: "-right-1.5 -top-2 w-5",
|
||||
} as const;
|
||||
|
||||
/** The adjacent player name labels the portrait; only the captain role is read. */
|
||||
export function SummonerAvatar({
|
||||
profileIconId,
|
||||
isCaptain = false,
|
||||
size = "md",
|
||||
shape = "rounded",
|
||||
}: {
|
||||
profileIconId?: number;
|
||||
isCaptain?: boolean;
|
||||
size?: keyof typeof AVATAR_SIZE;
|
||||
shape?: "circle" | "rounded";
|
||||
}) {
|
||||
const { data: manifest } = useDdragonManifest();
|
||||
const icon = profileIconUrl(manifest, profileIconId ?? 0);
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`relative inline-flex shrink-0 ${AVATAR_SIZE[size]} ${isCaptain ? "z-10" : ""}`}
|
||||
>
|
||||
<span
|
||||
className={`relative grid size-full place-items-center overflow-hidden bg-sunken-strong text-content-muted ring-2 ring-card ${shape === "circle" ? "rounded-full" : "rounded-[0.625rem]"}`}
|
||||
>
|
||||
<UserRound className={size === "sm" ? "size-4" : "size-5"} aria-hidden="true" />
|
||||
<img
|
||||
key={icon}
|
||||
src={icon}
|
||||
alt=""
|
||||
className="absolute inset-0 size-full object-cover"
|
||||
loading="lazy"
|
||||
onError={(event) => {
|
||||
event.currentTarget.hidden = true;
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
{isCaptain && (
|
||||
<img
|
||||
src={captainCrown}
|
||||
alt="팀장"
|
||||
className={`pointer-events-none absolute z-10 rotate-[14deg] [image-rendering:pixelated] ${CROWN_SIZE[size]}`}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
.lts-app-header {
|
||||
position: sticky;
|
||||
top: calc(0px - var(--app-header-row-height));
|
||||
z-index: 50;
|
||||
flex-shrink: 0;
|
||||
background: var(--color-background-body);
|
||||
}
|
||||
|
||||
.lts-app-header-inner {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
grid-template-rows: var(--app-header-row-height) minmax(0, 1fr);
|
||||
height: var(--app-header-height);
|
||||
align-items: center;
|
||||
column-gap: 16px;
|
||||
max-width: 1320px;
|
||||
margin-inline: auto;
|
||||
padding-inline: 16px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.lts-header-brand {
|
||||
grid-column: 1;
|
||||
grid-row: 1;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
flex-direction: column;
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.lts-header-brand-name {
|
||||
overflow: hidden;
|
||||
font-size: 19px;
|
||||
font-weight: 850;
|
||||
line-height: 1.1;
|
||||
letter-spacing: -0.7px;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.lts-header-brand-tagline {
|
||||
margin-top: 5px;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 7px;
|
||||
font-weight: 750;
|
||||
line-height: 1.1;
|
||||
letter-spacing: 2.5px;
|
||||
}
|
||||
|
||||
.lts-header-actions {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.lts-header-icon-button {
|
||||
display: grid;
|
||||
width: 38px;
|
||||
height: 38px;
|
||||
flex-shrink: 0;
|
||||
place-items: center;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 9px;
|
||||
background: var(--color-background-card);
|
||||
color: var(--color-text-secondary);
|
||||
transition: background-color 150ms, color 150ms;
|
||||
}
|
||||
|
||||
.lts-header-theme-toggle {
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
.lts-header-icon-button:hover {
|
||||
background: var(--lts-sunken);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.lts-primary-nav {
|
||||
grid-column: 1 / -1;
|
||||
grid-row: 2;
|
||||
display: flex;
|
||||
height: 100%;
|
||||
align-items: stretch;
|
||||
justify-content: center;
|
||||
gap: clamp(20px, 5vw, 36px);
|
||||
}
|
||||
|
||||
.lts-primary-nav-link {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
min-width: 36px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
white-space: nowrap;
|
||||
transition: color 150ms;
|
||||
}
|
||||
|
||||
.lts-primary-nav-link:hover,
|
||||
.lts-primary-nav-link[aria-current] {
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
|
||||
.lts-primary-nav-link[aria-current]::after {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: -1px;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
border-radius: 3px 3px 0 0;
|
||||
background: var(--color-brand-coral);
|
||||
content: "";
|
||||
}
|
||||
|
||||
.lts-app-header :focus-visible {
|
||||
outline: 2px solid var(--color-win);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
.lts-primary-nav-link:focus-visible {
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.lts-app-shell--without-nav {
|
||||
--app-header-nav-height: 0px;
|
||||
}
|
||||
|
||||
.lts-app-header--without-nav {
|
||||
position: static;
|
||||
}
|
||||
|
||||
.lts-app-header--without-nav .lts-app-header-inner {
|
||||
height: 60px;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
}
|
||||
|
||||
@media (width >= 48rem) {
|
||||
.lts-app-header-inner {
|
||||
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
column-gap: 24px;
|
||||
padding-inline: 24px;
|
||||
}
|
||||
|
||||
.lts-header-brand-name {
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.lts-header-brand-tagline {
|
||||
margin-top: 6px;
|
||||
font-size: 8px;
|
||||
}
|
||||
|
||||
.lts-header-actions {
|
||||
grid-column: 3;
|
||||
}
|
||||
|
||||
.lts-primary-nav {
|
||||
grid-column: 2;
|
||||
grid-row: 1;
|
||||
gap: 36px;
|
||||
}
|
||||
|
||||
.lts-primary-nav-link {
|
||||
min-width: 0;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.lts-app-header--without-nav .lts-app-header-inner {
|
||||
height: 74px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (width >= 80rem) {
|
||||
.lts-app-header-inner {
|
||||
padding-inline: 40px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
.auction-chat-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
color: var(--color-text-primary);
|
||||
background: var(--color-background-card);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-container);
|
||||
}
|
||||
|
||||
.auction-chat-panel .auction-chat-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
flex-shrink: 0;
|
||||
gap: 12px;
|
||||
padding: 12px 14px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
|
||||
.auction-chat-header h2 {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
margin: 0;
|
||||
}
|
||||
.auction-chat-connection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
.auction-chat-conversation {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
.auction-chat-scroll {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 16px 12px;
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
.auction-chat-scroll > .astryx-chat-message-list {
|
||||
min-height: 100%;
|
||||
}
|
||||
.auction-chat-empty {
|
||||
margin: auto;
|
||||
padding: 24px 8px;
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
.auction-chat-author {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 6px;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.auction-chat-name {
|
||||
max-width: 150px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-weight: 600;
|
||||
}
|
||||
.auction-chat-author time,
|
||||
.auction-chat-self {
|
||||
font-size: 11px;
|
||||
font-weight: 400;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.auction-chat-author .astryx-badge {
|
||||
font-size: 10px;
|
||||
padding-inline: 5px;
|
||||
height: 18px;
|
||||
}
|
||||
.auction-chat-panel
|
||||
.astryx-chat-message[data-sender="user"]
|
||||
.auction-chat-author {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
.auction-chat-panel .astryx-chat-message-bubble {
|
||||
padding: 8px 10px;
|
||||
max-width: 100%;
|
||||
font-size: 14px;
|
||||
line-height: 1.6;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.auction-chat-panel
|
||||
.astryx-chat-message[data-sender="assistant"]
|
||||
.astryx-chat-message-bubble {
|
||||
background: var(--color-background-muted);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
.auction-chat-panel
|
||||
.astryx-chat-message[data-sender="user"]
|
||||
.astryx-chat-message-bubble {
|
||||
background: var(--color-accent-muted);
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
.auction-chat-panel .astryx-chat-message > div {
|
||||
max-width: 92%;
|
||||
min-width: 0;
|
||||
}
|
||||
.auction-chat-delivery {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 4px;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.auction-chat-delivery[data-failed="true"] {
|
||||
color: var(--color-text-error);
|
||||
}
|
||||
.auction-chat-new-messages {
|
||||
position: absolute;
|
||||
bottom: 10px;
|
||||
inset-inline: 0;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
pointer-events: none;
|
||||
}
|
||||
.auction-chat-new-messages button {
|
||||
pointer-events: auto;
|
||||
box-shadow: 0 2px 8px var(--color-palette-shadow-light);
|
||||
}
|
||||
.auction-chat-compose-area {
|
||||
flex-shrink: 0;
|
||||
padding: 10px 12px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
.auction-chat-sender {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.auction-chat-sender > span:first-child {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.auction-chat-count {
|
||||
flex-shrink: 0;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.auction-chat-count[data-limit="true"] {
|
||||
color: var(--color-text-error);
|
||||
}
|
||||
/* The Astryx composer keeps its focus/disabled shell; its input and footer
|
||||
slots form one compact row for this sidebar's plain-text editor. */
|
||||
.auction-chat-panel .auction-chat-composer > div {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
align-items: end;
|
||||
gap: 6px;
|
||||
padding: 5px;
|
||||
border-radius: var(--radius-element);
|
||||
background: var(--color-background-card);
|
||||
}
|
||||
.auction-chat-composer textarea {
|
||||
display: block;
|
||||
width: 100%;
|
||||
min-height: 36px;
|
||||
max-height: calc(4lh + 14px);
|
||||
resize: none;
|
||||
border: 0;
|
||||
border-radius: 4px;
|
||||
padding: 7px;
|
||||
background: transparent;
|
||||
color: var(--color-text-primary);
|
||||
font: inherit;
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
outline: none;
|
||||
}
|
||||
.auction-chat-composer textarea::placeholder {
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.auction-chat-panel .auction-chat-send {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
min-width: 36px;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.auction-chat-panel .auction-chat-send:disabled {
|
||||
opacity: 1;
|
||||
background: var(--color-background-muted);
|
||||
color: var(--color-text-disabled);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
.auction-chat-hint {
|
||||
margin: 6px 0 0;
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 10px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@media (pointer: coarse), (max-width: 639px) {
|
||||
.auction-chat-panel .auction-chat-send {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
.auction-chat-composer textarea {
|
||||
min-height: 44px;
|
||||
max-height: calc(4lh + 22px);
|
||||
padding-block: 11px;
|
||||
font-size: 16px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,598 @@
|
||||
import { useId, useState, type KeyboardEvent, type ReactNode } from "react";
|
||||
import { Link } from "react-router";
|
||||
import { ArrowUpRight } from "lucide-react";
|
||||
import { Tooltip } from "@astryxdesign/core/Tooltip";
|
||||
import type { AuctionPlayerView } from "../../api/mappers";
|
||||
import type {
|
||||
ApiRecentMatchView,
|
||||
ApiTierInfo,
|
||||
DdragonManifest,
|
||||
} from "../../api/types";
|
||||
import { DEFAULT_COMMUNITY_ID } from "../../config";
|
||||
import {
|
||||
championDisplayName,
|
||||
championIconUrl,
|
||||
profileIconUrl,
|
||||
} from "../../lib/ddragon";
|
||||
import { POSITION_ORDER, positionIcon, positionLabel } from "../../lib/league";
|
||||
import { LANE_LABELS } from "../../lib/riot-history";
|
||||
import { internalMatchGamePath } from "../../lib/internal-match-routes";
|
||||
import { RankBadge } from "../RankBadge";
|
||||
import { formatRankDetail } from "../rankBadgeUtils";
|
||||
import {
|
||||
metricLabel,
|
||||
POSITION_LANES,
|
||||
selectProfileGames,
|
||||
summarizeProfileGames,
|
||||
type PositionFilter,
|
||||
type ProfileQueue,
|
||||
} from "./stats";
|
||||
import { useProfileHistory } from "./useProfileHistory";
|
||||
import { useProfileManifest } from "./useProfileManifest";
|
||||
import "./profile.css";
|
||||
|
||||
const POSITIONS: PositionFilter[] = ["ALL", ...POSITION_ORDER];
|
||||
const QUEUES: ProfileQueue[] = ["internal", "solo"];
|
||||
const queueName = (queue: ProfileQueue) =>
|
||||
queue === "internal" ? "내전" : "솔로랭크";
|
||||
const positionName = (position: PositionFilter) =>
|
||||
position === "ALL" ? "전체" : positionLabel[position];
|
||||
const dateLabel = (timestamp: number) =>
|
||||
new Intl.DateTimeFormat("ko-KR", { month: "2-digit", day: "2-digit" })
|
||||
.format(timestamp)
|
||||
.replace(/\.$/, "");
|
||||
type Summary = ReturnType<typeof summarizeProfileGames>;
|
||||
type Manifest = DdragonManifest | undefined;
|
||||
|
||||
function moveTab<T extends string>(
|
||||
event: KeyboardEvent<HTMLButtonElement>,
|
||||
values: T[],
|
||||
current: T,
|
||||
select: (value: T) => void,
|
||||
prefix: string,
|
||||
) {
|
||||
if (
|
||||
event.altKey ||
|
||||
event.ctrlKey ||
|
||||
event.metaKey ||
|
||||
!["ArrowLeft", "ArrowRight", "Home", "End"].includes(event.key)
|
||||
)
|
||||
return;
|
||||
event.preventDefault();
|
||||
const index = values.indexOf(current);
|
||||
const next =
|
||||
event.key === "Home"
|
||||
? values[0]
|
||||
: event.key === "End"
|
||||
? values[values.length - 1]
|
||||
: values[
|
||||
(index + (event.key === "ArrowRight" ? 1 : -1) + values.length) %
|
||||
values.length
|
||||
];
|
||||
select(next);
|
||||
document.getElementById(`${prefix}-${next}`)?.focus();
|
||||
}
|
||||
|
||||
function Portrait({
|
||||
championId,
|
||||
manifest,
|
||||
}: {
|
||||
championId: number;
|
||||
manifest: Manifest;
|
||||
}) {
|
||||
const src = championIconUrl(manifest, championId);
|
||||
return (
|
||||
<span className="ap-champion-portrait">
|
||||
{src && <img src={src} alt="" loading="lazy" />}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ChampionGroup({
|
||||
summary,
|
||||
manifest,
|
||||
}: {
|
||||
summary: NonNullable<Summary>;
|
||||
manifest: Manifest;
|
||||
}) {
|
||||
return (
|
||||
<div className="ap-champions">
|
||||
<h3>최근 챔피언</h3>
|
||||
<div className="ap-avatar-group" aria-label="최근 사용 챔피언">
|
||||
{summary.champions.slice(0, 10).map((champion) => {
|
||||
const name =
|
||||
championDisplayName(manifest, champion.championId) ??
|
||||
`챔피언 ${champion.championId}`;
|
||||
const description = `${name} · ${champion.games}경기 · ${champion.wins}승 ${champion.games - champion.wins}패 · 승률 ${Math.round((champion.wins / champion.games) * 100)}%`;
|
||||
return (
|
||||
<Tooltip
|
||||
content={description}
|
||||
placement="below"
|
||||
key={champion.championId}
|
||||
>
|
||||
<span
|
||||
className="ap-avatar"
|
||||
role="img"
|
||||
tabIndex={0}
|
||||
aria-label={description}
|
||||
>
|
||||
<Portrait
|
||||
championId={champion.championId}
|
||||
manifest={manifest}
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Metrics({ summary }: { summary: Summary }) {
|
||||
return (
|
||||
<div className="ap-metrics" aria-label="선택한 포지션의 요약">
|
||||
<div>
|
||||
<span>승률</span>
|
||||
<strong>
|
||||
{summary ? (
|
||||
<>
|
||||
{summary.winRate}
|
||||
<small>%</small>
|
||||
</>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</strong>
|
||||
<p>
|
||||
{summary
|
||||
? `${summary.wins}승 ${summary.losses}패 · ${summary.games}경기`
|
||||
: "기록 없음"}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
<span>KDA</span>
|
||||
<strong data-perfect={summary?.kda === "Perfect"}>
|
||||
{summary?.kda ?? "—"}
|
||||
</strong>
|
||||
<p>{summary?.averageKda ?? "기록 없음"}</p>
|
||||
</div>
|
||||
<div>
|
||||
<span>평균 킬 관여율</span>
|
||||
<strong>
|
||||
{summary?.killParticipation != null ? (
|
||||
<>
|
||||
{Math.round(summary.killParticipation)}
|
||||
<small>%</small>
|
||||
</>
|
||||
) : (
|
||||
"—"
|
||||
)}
|
||||
</strong>
|
||||
<p>팀 처치 참여 비율</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PlayMetrics({
|
||||
summary,
|
||||
position,
|
||||
}: {
|
||||
summary: NonNullable<Summary>;
|
||||
position: PositionFilter;
|
||||
}) {
|
||||
const values = [
|
||||
{ key: "cs", label: "분당 CS", value: metricLabel(summary.csPerMinute, 1) },
|
||||
{
|
||||
key: "damage",
|
||||
label: "팀 내 피해량 비중",
|
||||
value: metricLabel(summary.damageShare, 0, "%"),
|
||||
},
|
||||
{
|
||||
key: "vision",
|
||||
label: "분당 시야 점수",
|
||||
value: metricLabel(summary.visionPerMinute, 2),
|
||||
},
|
||||
];
|
||||
if (position === "SUP") values.unshift(values.splice(2, 1)[0]);
|
||||
return (
|
||||
<section
|
||||
className="ap-play-metrics"
|
||||
aria-label={`${positionName(position)} ${summary.games}경기 평균 플레이 지표`}
|
||||
>
|
||||
<dl>
|
||||
{values.map((metric) => (
|
||||
<div key={metric.key}>
|
||||
<dt>{metric.label}</dt>
|
||||
<dd>{metric.value}</dd>
|
||||
</div>
|
||||
))}
|
||||
</dl>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function RecentGames({
|
||||
games,
|
||||
queue,
|
||||
manifest,
|
||||
historyBackTo,
|
||||
}: {
|
||||
games: ApiRecentMatchView[];
|
||||
queue: ProfileQueue;
|
||||
manifest: Manifest;
|
||||
historyBackTo: string;
|
||||
}) {
|
||||
return (
|
||||
<section className="ap-recent">
|
||||
<div className="ap-section-heading">
|
||||
<h3>최근 {queueName(queue)}</h3>
|
||||
<span>{games.length}경기 · 최신순</span>
|
||||
</div>
|
||||
<div
|
||||
className="ap-game-scroll"
|
||||
tabIndex={0}
|
||||
role="region"
|
||||
aria-label={`${queueName(queue)} 최근 ${games.length}경기 목록`}
|
||||
>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col">경기</th>
|
||||
<th scope="col">K / D / A</th>
|
||||
<th scope="col">CS/분</th>
|
||||
<th scope="col">킬 관여</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{games.map((game) => {
|
||||
const name =
|
||||
championDisplayName(manifest, game.championId) ??
|
||||
`챔피언 ${game.championId}`;
|
||||
const result = game.remake
|
||||
? "다시하기"
|
||||
: game.win
|
||||
? "승리"
|
||||
: "패배";
|
||||
const content = (
|
||||
<>
|
||||
<Portrait championId={game.championId} manifest={manifest} />
|
||||
<div>
|
||||
<strong>
|
||||
<b
|
||||
data-result={
|
||||
game.remake ? "remake" : game.win ? "win" : "loss"
|
||||
}
|
||||
>
|
||||
{result}
|
||||
</b>{" "}
|
||||
{name}
|
||||
</strong>
|
||||
<p>
|
||||
{dateLabel(game.gameCreation)} ·{" "}
|
||||
{LANE_LABELS[game.teamPosition] ?? "포지션 미상"} ·{" "}
|
||||
{Math.floor(game.gameDuration / 60)}분
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
const detailPath =
|
||||
game.internalMatchId && game.gameNumber
|
||||
? internalMatchGamePath(
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
game.internalMatchId,
|
||||
game.gameNumber,
|
||||
)
|
||||
: null;
|
||||
return (
|
||||
<tr key={`${game.matchId}-${game.gameNumber ?? ""}`}>
|
||||
<td>
|
||||
{detailPath ? (
|
||||
<Link
|
||||
to={detailPath}
|
||||
state={{
|
||||
backTo: historyBackTo,
|
||||
backLabel: "경매로 돌아가기",
|
||||
}}
|
||||
className="ap-game-identity"
|
||||
aria-label={`${name} ${result} 내전 상세 보기`}
|
||||
>
|
||||
{content}
|
||||
</Link>
|
||||
) : (
|
||||
<div className="ap-game-identity">{content}</div>
|
||||
)}
|
||||
</td>
|
||||
<td>
|
||||
{game.kills}/{game.deaths}/{game.assists}
|
||||
</td>
|
||||
<td>{metricLabel(game.csPerMin, 1)}</td>
|
||||
<td>{metricLabel(game.killParticipation, 0, "%")}</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function Masteries({
|
||||
player,
|
||||
manifest,
|
||||
}: {
|
||||
player: AuctionPlayerView;
|
||||
manifest: Manifest;
|
||||
}) {
|
||||
if (!player.masteries.length) return null;
|
||||
return (
|
||||
<div className="ap-masteries">
|
||||
<span>누적 숙련도</span>
|
||||
<div className="ap-mastery-icons">
|
||||
{player.masteries.slice(0, 5).map((champion) => {
|
||||
const label = `${championDisplayName(manifest, champion.championId) ?? champion.championId} · Lv.${champion.level} · ${(champion.points / 1000).toFixed(0)}K`;
|
||||
return (
|
||||
<Tooltip
|
||||
content={label}
|
||||
placement="below"
|
||||
key={champion.championId}
|
||||
>
|
||||
<span role="img" aria-label={label} tabIndex={0}>
|
||||
<Portrait
|
||||
championId={champion.championId}
|
||||
manifest={manifest}
|
||||
/>
|
||||
</span>
|
||||
</Tooltip>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<small>포지션 무관</small>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function AuctionPlayerProfile({
|
||||
player,
|
||||
peakTier,
|
||||
historyBackTo,
|
||||
bidStatus,
|
||||
}: {
|
||||
player: AuctionPlayerView;
|
||||
peakTier?: ApiTierInfo;
|
||||
historyBackTo: string;
|
||||
bidStatus?: ReactNode;
|
||||
}) {
|
||||
const prefix = useId();
|
||||
const manifest = useProfileManifest();
|
||||
// The parent keys this component by player, so a new player starts at their preference.
|
||||
const [queue, setQueue] = useState<ProfileQueue>("internal");
|
||||
const [position, setPosition] = useState<PositionFilter>(
|
||||
player.mainPosition ?? "ALL",
|
||||
);
|
||||
const history = useProfileHistory(player.userId, queue, position);
|
||||
const games = selectProfileGames(history.data?.matches ?? [], position);
|
||||
const summary = summarizeProfileGames(games);
|
||||
const preferences = [player.mainPosition, player.subPosition].filter(
|
||||
(value, index, values) => value && values.indexOf(value) === index,
|
||||
);
|
||||
const historyParams = new URLSearchParams({
|
||||
queueGroup: queue === "internal" ? "internal" : "summoners-rift",
|
||||
});
|
||||
if (queue === "solo") historyParams.set("rank", "solo");
|
||||
const historyHref = `/users/${player.userId}/history?${historyParams}`;
|
||||
const loading = !history.data && history.isPending;
|
||||
const unavailable = !history.data && history.isError;
|
||||
const showAll = () => {
|
||||
setPosition("ALL");
|
||||
document.getElementById(`${prefix}-position-ALL`)?.focus();
|
||||
};
|
||||
|
||||
return (
|
||||
<section
|
||||
className="auction-player-profile"
|
||||
aria-label={`${player.summonerName} 선수 정보`}
|
||||
>
|
||||
<header className="ap-identity">
|
||||
<Link
|
||||
to={`/users/${player.userId}/history`}
|
||||
state={{ backTo: historyBackTo }}
|
||||
aria-label={`${player.summonerName} 전체 전적`}
|
||||
>
|
||||
<img
|
||||
className="ap-player-avatar"
|
||||
src={profileIconUrl(manifest, player.profileIconId)}
|
||||
alt=""
|
||||
/>
|
||||
</Link>
|
||||
<div className="ap-player-info">
|
||||
<div className="ap-player-name">
|
||||
<h2>
|
||||
<Link
|
||||
to={`/users/${player.userId}/history`}
|
||||
state={{ backTo: historyBackTo }}
|
||||
>
|
||||
{player.summonerName}
|
||||
</Link>
|
||||
</h2>
|
||||
<span>#{player.tag}</span>
|
||||
</div>
|
||||
<div className="ap-rank">
|
||||
<RankBadge tier={player.tier} />
|
||||
<span>{formatRankDetail(player.tier)}</span>
|
||||
<span className="ap-secondary">현재</span>
|
||||
</div>
|
||||
<p className="ap-peak">
|
||||
기록된 최고 <strong>{formatRankDetail(peakTier)}</strong>
|
||||
</p>
|
||||
<div className="ap-preferences">
|
||||
<span>신청 포지션</span>
|
||||
{preferences.map((preference, index) => (
|
||||
<span
|
||||
className="ap-role-chip"
|
||||
data-primary={index === 0}
|
||||
key={preference}
|
||||
>
|
||||
<img src={positionIcon[preference]} alt="" />
|
||||
{positionLabel[preference]}
|
||||
<small>{index + 1}순위</small>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
{bidStatus}
|
||||
<div className="ap-tabs" role="tablist" aria-label="선수 전적 종류">
|
||||
{QUEUES.map((value) => (
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
key={value}
|
||||
id={`${prefix}-queue-${value}`}
|
||||
aria-selected={queue === value}
|
||||
aria-controls={`${prefix}-queue-panel`}
|
||||
tabIndex={queue === value ? 0 : -1}
|
||||
onClick={() => setQueue(value)}
|
||||
onKeyDown={(event) =>
|
||||
moveTab(event, QUEUES, queue, setQueue, `${prefix}-queue`)
|
||||
}
|
||||
>
|
||||
{queueName(value)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div
|
||||
className="ap-card-body"
|
||||
role="tabpanel"
|
||||
id={`${prefix}-queue-panel`}
|
||||
aria-labelledby={`${prefix}-queue-${queue}`}
|
||||
>
|
||||
<div className="ap-summary-heading">
|
||||
<h3>최근 {queueName(queue)}</h3>
|
||||
<Link to={historyHref} state={{ backTo: historyBackTo }}>
|
||||
전체 전적
|
||||
<ArrowUpRight size={13} aria-hidden="true" />
|
||||
</Link>
|
||||
</div>
|
||||
<div
|
||||
className="ap-position-tabs"
|
||||
role="tablist"
|
||||
aria-label="플레이 포지션"
|
||||
>
|
||||
{POSITIONS.map((value) => {
|
||||
const count =
|
||||
history.data?.positionCounts?.[
|
||||
value === "ALL" ? "ALL" : POSITION_LANES[value]
|
||||
] ??
|
||||
(value === position && history.data ? games.length : undefined);
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="tab"
|
||||
id={`${prefix}-position-${value}`}
|
||||
aria-controls={`${prefix}-position-panel`}
|
||||
aria-selected={position === value}
|
||||
aria-label={`${positionName(value)}${count === undefined ? "" : ` ${count}경기`}`}
|
||||
tabIndex={position === value ? 0 : -1}
|
||||
key={value}
|
||||
onClick={() => setPosition(value)}
|
||||
onKeyDown={(event) =>
|
||||
moveTab(
|
||||
event,
|
||||
POSITIONS,
|
||||
position,
|
||||
setPosition,
|
||||
`${prefix}-position`,
|
||||
)
|
||||
}
|
||||
>
|
||||
<span>
|
||||
{value !== "ALL" && <img src={positionIcon[value]} alt="" />}
|
||||
{positionName(value)}
|
||||
</span>
|
||||
<small>{count ?? "—"}</small>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<div
|
||||
role="tabpanel"
|
||||
id={`${prefix}-position-panel`}
|
||||
aria-labelledby={`${prefix}-position-${position}`}
|
||||
aria-busy={loading}
|
||||
>
|
||||
{loading ? (
|
||||
<div className="ap-loading" role="status">
|
||||
<span />
|
||||
전적을 불러오는 중입니다.
|
||||
</div>
|
||||
) : unavailable ? (
|
||||
<div className="ap-empty" role="alert">
|
||||
<strong>전적을 불러오지 못했습니다.</strong>
|
||||
<p>잠시 후 다시 시도해 주세요.</p>
|
||||
<button type="button" onClick={() => void history.refetch()}>
|
||||
다시 시도
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<p className="ap-sample-context" aria-live="polite">
|
||||
{position === "ALL" ? "전체 포지션" : positionName(position)}{" "}
|
||||
최근 {games.length}경기
|
||||
{games[0] && (
|
||||
<span>
|
||||
{dateLabel(games[games.length - 1].gameCreation)} –{" "}
|
||||
{dateLabel(games[0].gameCreation)}
|
||||
</span>
|
||||
)}
|
||||
</p>
|
||||
<Metrics summary={summary} />
|
||||
{summary && (
|
||||
<>
|
||||
<ChampionGroup summary={summary} manifest={manifest} />
|
||||
<PlayMetrics summary={summary} position={position} />
|
||||
</>
|
||||
)}
|
||||
{games.length ? (
|
||||
<RecentGames
|
||||
key={`${queue}-${position}`}
|
||||
games={games}
|
||||
queue={queue}
|
||||
manifest={manifest}
|
||||
historyBackTo={historyBackTo}
|
||||
/>
|
||||
) : (
|
||||
<div className="ap-empty">
|
||||
<strong>
|
||||
{positionName(position)} 플레이 기록이 없습니다.
|
||||
</strong>
|
||||
<p>포지션별로 최근 20경기까지 집계합니다.</p>
|
||||
{position !== "ALL" && (
|
||||
<button type="button" onClick={showAll}>
|
||||
전체 전적 보기
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
{queue === "solo" && <Masteries player={player} manifest={manifest} />}
|
||||
{history.data && (
|
||||
<p className="ap-data-note">
|
||||
{history.data.season.label} · 지표는 선택한 경기 기준
|
||||
{games.some((game) => game.remake) ? " · 다시하기 제외" : ""}
|
||||
{summary?.games === 1 ? " · 1경기 표본" : ""}
|
||||
</p>
|
||||
)}
|
||||
{history.isError && history.data && (
|
||||
<p className="ap-data-note" role="status">
|
||||
전적 갱신이 지연되어 마지막으로 불러온 기록을 표시합니다.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
# Auction player information — applied v2
|
||||
|
||||
Verified 2026-11-11 on the actual auction route:
|
||||
`http://localhost:5173/match/6a3b94bccb8a54219653f457/auction`.
|
||||
|
||||
## Approved source and implementation
|
||||
|
||||
The selected reference is `src/design-previews/player-information-v2/Preview.tsx`
|
||||
and its CSS. Production uses the separate `AuctionPlayerProfile.tsx`, `profile.css`,
|
||||
and history/statistics helpers; it imports no prototype fixtures.
|
||||
|
||||
The identity header, queue tabs, six position tabs, three summary metrics,
|
||||
overlapping champion avatars, three performance metrics and scrolling game table
|
||||
follow the approved reference. Container queries adapt the card at its actual
|
||||
440 px desktop / 311 px mobile widths. The existing auction bid/status rendering,
|
||||
team cards and chat are preserved.
|
||||
|
||||
## Browser results
|
||||
|
||||
- Initial player is 붕어베이글. Requested first position is 미드 and the selected
|
||||
history position starts at 미드. Internal history: seven actual games, 57% wins,
|
||||
2.96 aggregate KDA, 57% mean kill participation. All portraits loaded.
|
||||
- Solo overall window has 20 games dated October 30–November 7. The independent
|
||||
mid window includes the older October 26 game even though it is outside those
|
||||
overall 20 games. Support independently has 20 games; top/ADC have one each;
|
||||
jungle has zero. No missing games are invented or padded.
|
||||
- Remakes remain in the game list; summary performance excludes them and states
|
||||
that exclusion. The observed overall solo window has 19 completed games plus
|
||||
one remake, so summary wins/losses differ intentionally from the list count.
|
||||
- Support puts vision/minute first. Empty jungle shows dashes and an explicit
|
||||
empty state. Queue/position changes update the sample, metrics and champions
|
||||
together. No champion-count text or disclosure controls were introduced.
|
||||
- The table has all 20 rows, a 228 px viewport and sticky headings. End reaches
|
||||
the final row (scrollTop 565.3 of a 566 px range); changing position resets to 0.
|
||||
- ArrowRight and Home move selection and focus between position tabs. Internal
|
||||
game links retain the match/game route and return-to-auction state.
|
||||
- At 360 px viewport, page scrollWidth is 345 px and card scrollWidth is 311 px:
|
||||
no horizontal overflow. Desktop 1280 px also has no horizontal overflow.
|
||||
Browser viewport override was reset; final state is 내전 / 미드.
|
||||
|
||||
## Evidence
|
||||
|
||||
- Approved source: `src/design-previews/player-information-v2/Preview.tsx`.
|
||||
- Full mobile card: `C:/Users/park/.codex/visualizations/2026/11/11/01a1c930-2c9b-7531-a709-2ebb87701e9a/player-information-applied/mobile.jpg`.
|
||||
- Desktop context: same directory, `desktop.jpg`.
|
||||
- Desktop identity, tabs and metrics: same directory, `auction-player-card.jpg`.
|
||||
|
||||
## Data and validation
|
||||
|
||||
Both API and web TypeScript checks passed. Targeted ESLint passed. Eleven web
|
||||
tests (including the five existing prototype tests) and seventeen backend tests
|
||||
passed. Tests cover filtering before limiting, older position records, legacy
|
||||
pagination, stalled cursors, independently capped counts, participant-scoped
|
||||
Mongo predicates, averages, missing metrics and remake exclusion.
|
||||
|
||||
The connected staging API predates lane filtering and returns no positionCounts.
|
||||
The UI therefore uses a cached compatibility collector over its paginated public
|
||||
history API. It retains only the independent recent-20 windows. Once the new
|
||||
backend response is deployed, the UI requests the selected position directly.
|
||||
The new backend code was type/unit tested, not deployed or verified against a
|
||||
live database in this task (local bootstrap credentials were unavailable).
|
||||
Current history APIs use their configured season scope, shown below the card.
|
||||
|
||||
The staging DDragon manifest endpoint returned HTTP 500. A separate card-only
|
||||
query obtains champion metadata from Riot's official CDN when that endpoint
|
||||
fails. Its partial manifest does not replace the application's full manifest
|
||||
cache used by item/rune views.
|
||||
|
||||
## Size and stable-height follow-up
|
||||
|
||||
- Desktop inspector width now matches the approved two-column reference:
|
||||
`(1104 - 24) / 2 = 540px`. The page maximum width increases by the same 100px,
|
||||
retaining the existing 484px team grid at the maximum desktop layout width.
|
||||
The four-column layout starts at 1440px with minimum widths for adjacent areas.
|
||||
- The passed-status footer uses the reference's 12px type and 10px vertical
|
||||
padding. Before the fixed-height request, the complete internal card matched
|
||||
the reference's approximately 826px height.
|
||||
- The history body now reserves 656px on desktop, including the maximum solo
|
||||
view, ten champion portraits, the mastery row and the 228px match list. It
|
||||
reserves 720px at container widths up to 480px. Short/empty results retain the
|
||||
space, and flex layout keeps the data note at the bottom. Overflow remains
|
||||
available as an accessibility fallback; it is not needed in the tested states.
|
||||
- Browser measurements: the full desktop card is 877.60px for internal seven
|
||||
games, empty support, solo loading and solo support twenty games. On mobile,
|
||||
both twenty games and empty jungle measure 957.55px. History clientHeight and
|
||||
scrollHeight are equal (656 / 720 respectively); no extra body scroll appears.
|
||||
- Web TypeScript and AuctionPage/profile ESLint checks passed. This CSS change
|
||||
adds no new unit tests; verification exercises the real tab interactions.
|
||||
- During follow-up, another local Vite process replaced port 5173's staging
|
||||
configuration with development. Live-data verification continued on the
|
||||
isolated port 5174 staging proxy (`tmp/auction-profile-qa.mjs`, ignored), with a
|
||||
separate Vite dependency cache. No auction actions were performed.
|
||||
@@ -0,0 +1,84 @@
|
||||
import type {
|
||||
ApiRecentMatchesResponse,
|
||||
ApiRecentMatchView,
|
||||
} from "../../api/types";
|
||||
import {
|
||||
POSITION_LANES,
|
||||
RECENT_GAME_LIMIT,
|
||||
selectProfileGames,
|
||||
type PositionFilter,
|
||||
} from "./stats.ts";
|
||||
|
||||
/** Compatibility for older APIs: collect independent windows, never filter just the overall twenty. */
|
||||
export async function collectProfileWindows(
|
||||
fetchPage: (cursor?: number) => Promise<ApiRecentMatchesResponse>,
|
||||
) {
|
||||
const positions: PositionFilter[] = [
|
||||
"ALL",
|
||||
"TOP",
|
||||
"JGL",
|
||||
"MID",
|
||||
"ADC",
|
||||
"SUP",
|
||||
];
|
||||
const windows = new Map<PositionFilter, ApiRecentMatchView[]>(
|
||||
positions.map((position) => [position, []]),
|
||||
);
|
||||
const seen = new Set<string>();
|
||||
let cursor: number | undefined;
|
||||
let first: ApiRecentMatchesResponse | undefined;
|
||||
while (true) {
|
||||
const page = await fetchPage(cursor);
|
||||
first ??= page;
|
||||
for (const game of [...page.matches].sort(
|
||||
(a, b) => b.gameCreation - a.gameCreation,
|
||||
)) {
|
||||
const key = `${game.matchId}:${game.gameNumber ?? ""}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
for (const position of positions) {
|
||||
const window = windows.get(position)!;
|
||||
if (
|
||||
window.length < RECENT_GAME_LIMIT &&
|
||||
(position === "ALL" || game.teamPosition === POSITION_LANES[position])
|
||||
)
|
||||
window.push(game);
|
||||
}
|
||||
}
|
||||
if (
|
||||
page.nextCursor === null ||
|
||||
positions.every(
|
||||
(position) => windows.get(position)!.length === RECENT_GAME_LIMIT,
|
||||
)
|
||||
)
|
||||
break;
|
||||
if (
|
||||
!Number.isFinite(page.nextCursor) ||
|
||||
(cursor !== undefined && page.nextCursor >= cursor)
|
||||
)
|
||||
throw new Error("전적 페이지를 이어 불러오지 못했습니다.");
|
||||
cursor = page.nextCursor;
|
||||
}
|
||||
const uniqueGames = new Map<string, ApiRecentMatchView>();
|
||||
for (const window of windows.values())
|
||||
for (const game of window)
|
||||
uniqueGames.set(`${game.matchId}:${game.gameNumber ?? ""}`, game);
|
||||
return {
|
||||
...first,
|
||||
matches: [...uniqueGames.values()],
|
||||
positionCounts: Object.fromEntries(
|
||||
positions.map((position) => [
|
||||
position === "ALL" ? "ALL" : POSITION_LANES[position],
|
||||
windows.get(position)!.length,
|
||||
]),
|
||||
),
|
||||
nextCursor: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function profileWindow(
|
||||
history: ApiRecentMatchesResponse,
|
||||
position: PositionFilter,
|
||||
): ApiRecentMatchesResponse {
|
||||
return { ...history, matches: selectProfileGames(history.matches, position) };
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
.auction-player-profile {
|
||||
container: auction-profile / inline-size;
|
||||
color: var(--color-text-primary);
|
||||
font-size: 13px;
|
||||
line-height: 1.45;
|
||||
}
|
||||
.ap-identity {
|
||||
padding: 20px;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 16px;
|
||||
}
|
||||
.ap-player-avatar {
|
||||
width: 64px;
|
||||
height: 64px;
|
||||
flex-shrink: 0;
|
||||
object-fit: cover;
|
||||
border-radius: var(--radius-inner);
|
||||
}
|
||||
.ap-player-info {
|
||||
min-width: 0;
|
||||
}
|
||||
.ap-player-name {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
.ap-player-name h2 {
|
||||
font-size: 20px;
|
||||
font-weight: 750;
|
||||
line-height: 1.2;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
.ap-player-name > span,
|
||||
.ap-secondary {
|
||||
font-size: 12px;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-rank {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.ap-peak {
|
||||
font-size: 12px;
|
||||
color: var(--lts-text-subtle);
|
||||
margin-top: 4px;
|
||||
}
|
||||
.ap-peak strong {
|
||||
font-weight: 500;
|
||||
color: var(--color-text-primary);
|
||||
margin-left: 4px;
|
||||
}
|
||||
.ap-preferences {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
margin-top: 10px;
|
||||
}
|
||||
.ap-preferences > span:first-child {
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
margin-right: 2px;
|
||||
}
|
||||
.ap-role-chip {
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 7px;
|
||||
padding: 2px 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ap-role-chip[data-primary="true"] {
|
||||
color: var(--color-text-accent);
|
||||
border-color: color-mix(in srgb, var(--color-text-accent) 22%, transparent);
|
||||
background: color-mix(in srgb, var(--color-text-accent) 4%, transparent);
|
||||
}
|
||||
.ap-role-chip img {
|
||||
width: 13px;
|
||||
height: 13px;
|
||||
border-radius: 0;
|
||||
}
|
||||
.ap-role-chip small {
|
||||
font-size: 10px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
.ap-tabs {
|
||||
display: flex;
|
||||
border-block: 1px solid var(--color-border);
|
||||
padding-inline: 12px;
|
||||
gap: 5px;
|
||||
}
|
||||
.ap-tabs button {
|
||||
position: relative;
|
||||
padding: 12px 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 13px;
|
||||
font-weight: 650;
|
||||
cursor: pointer;
|
||||
border-radius: 0;
|
||||
}
|
||||
.ap-tabs button[aria-selected="true"] {
|
||||
color: var(--color-text-accent);
|
||||
}
|
||||
.ap-tabs button[aria-selected="true"]::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
height: 2px;
|
||||
background: currentColor;
|
||||
bottom: -1px;
|
||||
left: 11px;
|
||||
right: 11px;
|
||||
}
|
||||
.ap-tabs button:hover {
|
||||
color: var(--color-text-primary);
|
||||
}
|
||||
.ap-tabs button:focus-visible,
|
||||
.ap-recent-game:focus-visible,
|
||||
.ap-summary-heading a:focus-visible {
|
||||
outline: 2px solid var(--color-text-accent);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
.ap-card-body {
|
||||
padding: 16px 18px 12px;
|
||||
}
|
||||
.ap-summary-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.ap-summary-heading h3 {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.ap-summary-heading a {
|
||||
color: var(--color-text-accent);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
font-size: 12px;
|
||||
}
|
||||
.ap-champion-portrait {
|
||||
display: inline-block;
|
||||
height: 32px;
|
||||
width: 32px;
|
||||
flex: 0 0 32px;
|
||||
overflow: hidden;
|
||||
border-radius: var(--radius-inner);
|
||||
background: var(--color-background-muted);
|
||||
}
|
||||
.ap-champion-portrait img {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
object-fit: cover;
|
||||
transform: scale(1.18);
|
||||
}
|
||||
|
||||
.ap-card-body {
|
||||
padding: 14px 18px 10px;
|
||||
/* Reserve the full solo-rank view: 20 games, ten portraits and mastery row. */
|
||||
height: 656px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
.ap-card-body > * {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ap-card-body > [role="tabpanel"] {
|
||||
flex-grow: 1;
|
||||
}
|
||||
.ap-identity {
|
||||
padding: 18px;
|
||||
}
|
||||
.ap-position-tabs {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(6, minmax(0, 1fr));
|
||||
gap: 3px;
|
||||
margin-top: 13px;
|
||||
border-bottom: 1px solid var(--color-border);
|
||||
}
|
||||
.ap-position-tabs button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 5px;
|
||||
min-height: 41px;
|
||||
position: relative;
|
||||
border-radius: 5px 5px 0 0;
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
color: var(--lts-text-subtle);
|
||||
padding: 6px 2px;
|
||||
}
|
||||
.ap-position-tabs button > span {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
}
|
||||
.ap-position-tabs img {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: 0;
|
||||
}
|
||||
.ap-position-tabs small {
|
||||
font-size: 11px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.ap-position-tabs button[data-empty="true"] {
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-position-tabs button[aria-selected="true"] {
|
||||
background: color-mix(in srgb, var(--color-text-accent) 5%, transparent);
|
||||
color: var(--color-text-accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
.ap-position-tabs button[aria-selected="true"]::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 7px;
|
||||
right: 7px;
|
||||
bottom: -1px;
|
||||
height: 2px;
|
||||
background: var(--color-text-accent);
|
||||
}
|
||||
.ap-position-tabs button:hover {
|
||||
background: var(--color-background-muted);
|
||||
}
|
||||
.ap-position-tabs button:focus-visible,
|
||||
.ap-avatar:focus-visible,
|
||||
.ap-mastery-icons > span:focus-visible {
|
||||
outline: 2px solid var(--color-text-accent);
|
||||
outline-offset: 2px;
|
||||
z-index: 5;
|
||||
}
|
||||
.ap-sample-context {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 6px;
|
||||
margin-top: 9px;
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-metrics {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
margin: 13px 0 9px;
|
||||
}
|
||||
.ap-metrics > div {
|
||||
min-width: 0;
|
||||
padding-inline: 13px;
|
||||
display: grid;
|
||||
grid-template-columns: 1fr auto;
|
||||
align-items: center;
|
||||
gap: 3px 5px;
|
||||
}
|
||||
.ap-metrics > div:first-child {
|
||||
padding-left: 0;
|
||||
}
|
||||
.ap-metrics > div:last-child {
|
||||
padding-right: 0;
|
||||
}
|
||||
.ap-metrics > div + div {
|
||||
border-left: 1px solid var(--color-border);
|
||||
}
|
||||
.ap-metrics > div > span {
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-metrics strong {
|
||||
display: block;
|
||||
font-size: 24px;
|
||||
font-weight: 750;
|
||||
line-height: 1.25;
|
||||
font-variant-numeric: tabular-nums;
|
||||
letter-spacing: -0.03em;
|
||||
}
|
||||
.ap-metrics strong[data-perfect="true"] {
|
||||
font-size: 16px;
|
||||
line-height: 1.875;
|
||||
}
|
||||
.ap-metrics small {
|
||||
font-size: 14px;
|
||||
margin-left: 1px;
|
||||
font-weight: 500;
|
||||
}
|
||||
.ap-metrics p {
|
||||
grid-column: 1 / -1;
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ap-champions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px 12px;
|
||||
min-height: 49px;
|
||||
padding-block: 6px;
|
||||
}
|
||||
.ap-champions h3 {
|
||||
font-size: 12px;
|
||||
color: var(--lts-text-subtle);
|
||||
font-weight: 500;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ap-avatar-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding-left: 10px;
|
||||
}
|
||||
.ap-avatar {
|
||||
display: inline-flex;
|
||||
position: relative;
|
||||
border-radius: 50%;
|
||||
border: 2px solid var(--color-background-card);
|
||||
margin-left: -10px;
|
||||
background: var(--color-background-card);
|
||||
cursor: help;
|
||||
}
|
||||
.ap-avatar:hover,
|
||||
.ap-avatar:focus {
|
||||
z-index: 4;
|
||||
}
|
||||
.ap-avatar .ap-champion-portrait {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
flex-basis: 30px;
|
||||
border-radius: 50%;
|
||||
}
|
||||
.ap-play-metrics {
|
||||
padding-block: 9px;
|
||||
border-block: 1px solid var(--color-border);
|
||||
margin: 2px 0 14px;
|
||||
}
|
||||
.ap-section-heading {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 9px;
|
||||
}
|
||||
.ap-section-heading h3 {
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.ap-section-heading > span {
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-play-metrics dl {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
.ap-play-metrics dt {
|
||||
font-size: 11px;
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-play-metrics dd {
|
||||
font-size: 18px;
|
||||
font-weight: 650;
|
||||
margin-top: 2px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.ap-recent table {
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
.ap-game-scroll {
|
||||
max-height: 228px;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior-y: contain;
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: var(--color-border) transparent;
|
||||
}
|
||||
.ap-game-scroll:focus-visible {
|
||||
outline: 2px solid var(--color-text-accent);
|
||||
outline-offset: 3px;
|
||||
}
|
||||
.ap-recent thead {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
background: var(--color-background-card);
|
||||
}
|
||||
.ap-recent th {
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 10px;
|
||||
font-weight: 500;
|
||||
text-align: right;
|
||||
padding: 0 0 6px;
|
||||
}
|
||||
.ap-recent th:first-child {
|
||||
width: auto;
|
||||
text-align: left;
|
||||
}
|
||||
.ap-recent th:nth-child(2) {
|
||||
width: 78px;
|
||||
}
|
||||
.ap-recent th:nth-child(3) {
|
||||
width: 58px;
|
||||
}
|
||||
.ap-recent th:nth-child(4) {
|
||||
width: 62px;
|
||||
}
|
||||
.ap-recent td {
|
||||
text-align: right;
|
||||
padding: 5px 0;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
.ap-recent td:first-child {
|
||||
text-align: left;
|
||||
}
|
||||
.ap-game-identity {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 7px;
|
||||
}
|
||||
.ap-game-identity > div {
|
||||
min-width: 0;
|
||||
}
|
||||
.ap-game-identity .ap-champion-portrait {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
flex-basis: 28px;
|
||||
}
|
||||
.ap-game-identity strong {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
line-height: 1.25;
|
||||
font-weight: 550;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ap-game-identity b {
|
||||
font-weight: 700;
|
||||
}
|
||||
.ap-game-identity b[data-result="win"] {
|
||||
color: var(--color-palette-win-text-light);
|
||||
}
|
||||
.ap-game-identity b[data-result="loss"] {
|
||||
color: var(--color-palette-loss-text-light);
|
||||
}
|
||||
[data-theme="dark"] .ap-game-identity b[data-result="win"] {
|
||||
color: var(--color-palette-win-text-dark);
|
||||
}
|
||||
[data-theme="dark"] .ap-game-identity b[data-result="loss"] {
|
||||
color: var(--color-palette-loss-text-dark);
|
||||
}
|
||||
.ap-game-identity p {
|
||||
font-size: 10px;
|
||||
line-height: 1.2;
|
||||
color: var(--lts-text-subtle);
|
||||
white-space: nowrap;
|
||||
margin-top: 1px;
|
||||
}
|
||||
.ap-masteries {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding-top: 12px;
|
||||
margin-top: 8px;
|
||||
border-top: 1px solid var(--color-border);
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 11px;
|
||||
}
|
||||
.ap-mastery-icons {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
}
|
||||
.ap-mastery-icons > span {
|
||||
display: inline-flex;
|
||||
border-radius: var(--radius-inner);
|
||||
cursor: help;
|
||||
}
|
||||
.ap-masteries .ap-champion-portrait {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
flex-basis: 22px;
|
||||
}
|
||||
.ap-masteries small {
|
||||
margin-left: auto;
|
||||
font-size: 10px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.ap-data-note {
|
||||
font-size: 10px;
|
||||
color: var(--lts-text-subtle);
|
||||
margin-top: 11px;
|
||||
}
|
||||
.ap-empty {
|
||||
padding: 32px 8px 40px;
|
||||
text-align: center;
|
||||
}
|
||||
.ap-empty strong {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.ap-empty p {
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 12px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
.ap-empty button {
|
||||
color: var(--color-text-accent);
|
||||
font-size: 12px;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-element);
|
||||
padding: 8px 12px;
|
||||
margin-top: 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
@container auction-profile (max-width: 480px) {
|
||||
.ap-card-body {
|
||||
height: 720px;
|
||||
}
|
||||
.ap-card-body {
|
||||
padding-inline: 12px;
|
||||
}
|
||||
.ap-position-tabs {
|
||||
gap: 1px;
|
||||
}
|
||||
.ap-position-tabs button {
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
font-size: 11px;
|
||||
min-height: 48px;
|
||||
}
|
||||
.ap-position-tabs img {
|
||||
width: 11px;
|
||||
height: 11px;
|
||||
}
|
||||
.ap-metrics > div {
|
||||
padding-inline: 9px;
|
||||
}
|
||||
.ap-metrics {
|
||||
gap: 0;
|
||||
}
|
||||
.ap-metrics > div {
|
||||
display: block;
|
||||
}
|
||||
.ap-metrics > div > span {
|
||||
font-size: 11px;
|
||||
}
|
||||
.ap-metrics strong {
|
||||
font-size: 23px;
|
||||
}
|
||||
.ap-metrics p {
|
||||
font-size: 10px;
|
||||
margin-top: 2px;
|
||||
}
|
||||
.ap-metrics strong[data-perfect="true"] {
|
||||
font-size: 17px;
|
||||
}
|
||||
.ap-champions {
|
||||
gap: 8px;
|
||||
}
|
||||
.ap-champions h3 {
|
||||
font-size: 11px;
|
||||
}
|
||||
.ap-avatar .ap-champion-portrait {
|
||||
width: 27px;
|
||||
height: 27px;
|
||||
flex-basis: 27px;
|
||||
}
|
||||
.ap-recent th:nth-child(2) {
|
||||
width: 58px;
|
||||
}
|
||||
.ap-recent th:nth-child(3) {
|
||||
width: 43px;
|
||||
}
|
||||
.ap-recent th:nth-child(4) {
|
||||
width: 46px;
|
||||
}
|
||||
.ap-recent table {
|
||||
font-size: 11px;
|
||||
}
|
||||
.ap-game-identity {
|
||||
gap: 5px;
|
||||
}
|
||||
.ap-game-identity strong {
|
||||
font-size: 11px;
|
||||
}
|
||||
.ap-game-identity p {
|
||||
font-size: 9px;
|
||||
}
|
||||
.ap-masteries {
|
||||
gap: 7px;
|
||||
}
|
||||
}
|
||||
|
||||
.ap-identity > a {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.ap-player-name h2 {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.ap-player-name a:hover,
|
||||
.ap-game-identity:hover {
|
||||
color: var(--color-text-accent);
|
||||
}
|
||||
.ap-game-identity:focus-visible,
|
||||
.ap-identity a:focus-visible {
|
||||
outline: 2px solid var(--color-text-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
.ap-game-identity strong {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.ap-game-identity b[data-result="remake"] {
|
||||
color: var(--lts-text-subtle);
|
||||
}
|
||||
.ap-loading {
|
||||
min-height: 360px;
|
||||
padding-top: 24px;
|
||||
color: var(--lts-text-subtle);
|
||||
font-size: 12px;
|
||||
}
|
||||
.ap-loading > span {
|
||||
display: block;
|
||||
height: 64px;
|
||||
border-radius: var(--radius-element);
|
||||
background: var(--color-background-muted);
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
@container auction-profile (max-width: 480px) {
|
||||
.ap-identity {
|
||||
padding: 16px;
|
||||
gap: 11px;
|
||||
}
|
||||
.ap-player-avatar {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
}
|
||||
.ap-player-name h2 {
|
||||
font-size: 18px;
|
||||
}
|
||||
.ap-preferences > span:first-child {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { ApiRecentMatchView, Position, RiotLane } from "../../api/types";
|
||||
|
||||
export type ProfileQueue = "internal" | "solo";
|
||||
export type PositionFilter = "ALL" | Position;
|
||||
export const RECENT_GAME_LIMIT = 20;
|
||||
export const POSITION_LANES: Record<Position, RiotLane> = {
|
||||
TOP: "TOP",
|
||||
JGL: "JUNGLE",
|
||||
MID: "MIDDLE",
|
||||
ADC: "BOTTOM",
|
||||
SUP: "UTILITY",
|
||||
};
|
||||
|
||||
/** The server filters before limiting. Keep the display window bounded and sorted. */
|
||||
export function selectProfileGames(
|
||||
history: ApiRecentMatchView[],
|
||||
position: PositionFilter,
|
||||
) {
|
||||
return history
|
||||
.filter(
|
||||
(game) =>
|
||||
position === "ALL" || game.teamPosition === POSITION_LANES[position],
|
||||
)
|
||||
.sort((a, b) => b.gameCreation - a.gameCreation)
|
||||
.slice(0, RECENT_GAME_LIMIT);
|
||||
}
|
||||
|
||||
const mean = (values: (number | undefined)[]) => {
|
||||
const known = values.filter(
|
||||
(value): value is number =>
|
||||
typeof value === "number" && Number.isFinite(value),
|
||||
);
|
||||
return known.length
|
||||
? known.reduce((sum, value) => sum + value, 0) / known.length
|
||||
: null;
|
||||
};
|
||||
|
||||
function damageShare(game: ApiRecentMatchView) {
|
||||
if (game.damageShare !== undefined) return game.damageShare;
|
||||
// Older responses expose team totals rather than the computed percentage.
|
||||
const team = game.teams?.find((team) => team.win === game.win);
|
||||
if (!team?.participants.length) return undefined;
|
||||
const total = team.participants.reduce(
|
||||
(sum, participant) => sum + participant.damageDealtToChampions,
|
||||
0,
|
||||
);
|
||||
return total > 0
|
||||
? (game.damageDealtToChampions / total) * 100
|
||||
: total === 0
|
||||
? 0
|
||||
: undefined;
|
||||
}
|
||||
|
||||
export function summarizeProfileGames(games: ApiRecentMatchView[]) {
|
||||
// Remakes remain visible in the list but do not distort win rate or performance.
|
||||
const completed = games.filter((game) => !game.remake);
|
||||
if (!completed.length) return null;
|
||||
const kills = completed.reduce((sum, game) => sum + game.kills, 0);
|
||||
const deaths = completed.reduce((sum, game) => sum + game.deaths, 0);
|
||||
const assists = completed.reduce((sum, game) => sum + game.assists, 0);
|
||||
const wins = completed.filter((game) => game.win).length;
|
||||
const champions = new Map<
|
||||
number,
|
||||
{ championId: number; games: number; wins: number }
|
||||
>();
|
||||
for (const game of completed) {
|
||||
const champion = champions.get(game.championId) ?? {
|
||||
championId: game.championId,
|
||||
games: 0,
|
||||
wins: 0,
|
||||
};
|
||||
champion.games++;
|
||||
champion.wins += Number(game.win);
|
||||
champions.set(game.championId, champion);
|
||||
}
|
||||
return {
|
||||
games: completed.length,
|
||||
wins,
|
||||
losses: completed.length - wins,
|
||||
winRate: Math.round((wins / completed.length) * 100),
|
||||
kda: deaths
|
||||
? ((kills + assists) / deaths).toFixed(2)
|
||||
: kills + assists > 0
|
||||
? "Perfect"
|
||||
: "0.00",
|
||||
averageKda: [kills, deaths, assists]
|
||||
.map((value) => (value / completed.length).toFixed(1))
|
||||
.join("/"),
|
||||
killParticipation: mean(completed.map((game) => game.killParticipation)),
|
||||
csPerMinute: mean(completed.map((game) => game.csPerMin)),
|
||||
damageShare: mean(completed.map(damageShare)),
|
||||
visionPerMinute: mean(
|
||||
completed.map((game) =>
|
||||
game.gameDuration > 0 && Number.isFinite(game.visionScore)
|
||||
? game.visionScore / (game.gameDuration / 60)
|
||||
: undefined,
|
||||
),
|
||||
),
|
||||
champions: [...champions.values()].sort(
|
||||
(a, b) => b.games - a.games || b.wins - a.wins,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function metricLabel(
|
||||
value: number | null | undefined,
|
||||
digits = 0,
|
||||
suffix = "",
|
||||
) {
|
||||
return typeof value === "number" && Number.isFinite(value)
|
||||
? `${value.toFixed(digits)}${suffix}`
|
||||
: "—";
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import type { ApiRecentMatchesResponse } from "../../api/types";
|
||||
import { DEFAULT_COMMUNITY_ID } from "../../config";
|
||||
import { apiFetch } from "../../lib/api";
|
||||
import {
|
||||
POSITION_LANES,
|
||||
RECENT_GAME_LIMIT,
|
||||
type PositionFilter,
|
||||
type ProfileQueue,
|
||||
} from "./stats";
|
||||
import { collectProfileWindows, profileWindow } from "./history";
|
||||
|
||||
export function useProfileHistory(
|
||||
userId: string,
|
||||
queue: ProfileQueue,
|
||||
position: PositionFilter,
|
||||
) {
|
||||
const queryClient = useQueryClient();
|
||||
const legacyKey = [
|
||||
"auction-player-history-windows",
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
userId,
|
||||
queue,
|
||||
];
|
||||
return useQuery({
|
||||
queryKey: [
|
||||
"auction-player-history",
|
||||
DEFAULT_COMMUNITY_ID,
|
||||
userId,
|
||||
queue,
|
||||
position,
|
||||
],
|
||||
queryFn: async ({ signal }) => {
|
||||
const params = new URLSearchParams({
|
||||
limit: String(RECENT_GAME_LIMIT),
|
||||
includePositionCounts: "true",
|
||||
});
|
||||
if (position !== "ALL") params.set("lane", POSITION_LANES[position]);
|
||||
if (queue === "solo") {
|
||||
params.set("queueGroup", "summoners-rift");
|
||||
params.set("rank", "solo");
|
||||
}
|
||||
const resource =
|
||||
queue === "internal" ? "internal-history" : "recent-matches";
|
||||
const path = `/communities/${DEFAULT_COMMUNITY_ID}/users/${userId}/${resource}`;
|
||||
const loadWindows = () =>
|
||||
queryClient.fetchQuery({
|
||||
queryKey: legacyKey,
|
||||
staleTime: 60_000,
|
||||
retry: false,
|
||||
queryFn: ({ signal: windowSignal }) =>
|
||||
collectProfileWindows((cursor) => {
|
||||
const pageParams = new URLSearchParams(params);
|
||||
pageParams.delete("lane");
|
||||
pageParams.delete("includePositionCounts");
|
||||
pageParams.set("limit", "30");
|
||||
if (cursor !== undefined)
|
||||
pageParams.set("cursor", String(cursor));
|
||||
return apiFetch<ApiRecentMatchesResponse>(
|
||||
`${path}?${pageParams}`,
|
||||
{ auth: "none", signal: windowSignal },
|
||||
);
|
||||
}),
|
||||
});
|
||||
if (queryClient.getQueryData(legacyKey))
|
||||
return profileWindow(await loadWindows(), position);
|
||||
const response = await apiFetch<ApiRecentMatchesResponse>(
|
||||
`${path}?${params}`,
|
||||
{ auth: "none", signal },
|
||||
);
|
||||
return response.positionCounts
|
||||
? response
|
||||
: profileWindow(await loadWindows(), position);
|
||||
},
|
||||
enabled: Boolean(DEFAULT_COMMUNITY_ID && userId),
|
||||
staleTime: 60_000,
|
||||
retry: 1,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { useDdragonManifest } from "../../api/hooks";
|
||||
import type { DdragonManifest } from "../../api/types";
|
||||
|
||||
/** Keep player portraits available if the application's manifest endpoint is down. */
|
||||
export function useProfileManifest() {
|
||||
const manifest = useDdragonManifest();
|
||||
const champions = useQuery({
|
||||
queryKey: ["auction-profile-champion-manifest", "ko_KR"],
|
||||
enabled: !manifest.data && manifest.failureCount > 0,
|
||||
staleTime: 24 * 60 * 60 * 1000,
|
||||
retry: 1,
|
||||
queryFn: async ({ signal }): Promise<DdragonManifest> => {
|
||||
const cdn = "https://ddragon.leagueoflegends.com/cdn";
|
||||
const versionResponse = await fetch(
|
||||
"https://ddragon.leagueoflegends.com/api/versions.json",
|
||||
{ signal },
|
||||
);
|
||||
if (!versionResponse.ok)
|
||||
throw new Error("챔피언 버전을 불러오지 못했습니다.");
|
||||
const versions: string[] = await versionResponse.json();
|
||||
const version = versions[0];
|
||||
if (!version || !/^\d+\.\d+\.\d+$/.test(version))
|
||||
throw new Error("챔피언 버전 정보가 올바르지 않습니다.");
|
||||
const response = await fetch(
|
||||
`${cdn}/${version}/data/ko_KR/champion.json`,
|
||||
{ signal },
|
||||
);
|
||||
if (!response.ok) throw new Error("챔피언 정보를 불러오지 못했습니다.");
|
||||
const payload: {
|
||||
data: Record<string, { key: string; id: string; name: string }>;
|
||||
} = await response.json();
|
||||
// This separate cache supplies only this card's champion and profile portraits.
|
||||
return {
|
||||
version,
|
||||
cdn,
|
||||
locale: "ko_KR",
|
||||
fetchedAt: new Date().toISOString(),
|
||||
champions: Object.fromEntries(
|
||||
Object.values(payload.data).map((champion) => [
|
||||
champion.key,
|
||||
{ key: champion.id, name: champion.name },
|
||||
]),
|
||||
),
|
||||
items: {},
|
||||
summonerSpells: {},
|
||||
runesReforged: [],
|
||||
};
|
||||
},
|
||||
});
|
||||
return manifest.data ?? champions.data;
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
.auction-reaction-picker-title {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
.auction-reaction-picker-description {
|
||||
margin: 3px 0 12px;
|
||||
color: var(--color-text-secondary);
|
||||
font-size: 12px;
|
||||
}
|
||||
.auction-reaction-options {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(44px, 1fr));
|
||||
gap: 6px;
|
||||
}
|
||||
.auction-reaction-options .auction-reaction-option {
|
||||
width: 100%;
|
||||
height: 46px;
|
||||
border-radius: 10px;
|
||||
}
|
||||
.auction-reaction-option span[aria-hidden] {
|
||||
font-size: 27px;
|
||||
line-height: 1;
|
||||
font-family:
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||
}
|
||||
.auction-reaction-options .auction-reaction-option:disabled {
|
||||
opacity: 0.55;
|
||||
}
|
||||
.auction-reaction-error {
|
||||
margin: 10px 0 0;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
.auction-chat-panel .auction-chat-reaction-trigger {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
min-width: 36px;
|
||||
border-radius: 8px;
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
|
||||
.auction-reaction-layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 60;
|
||||
overflow: hidden;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
contain: strict;
|
||||
}
|
||||
.auction-floating-reaction {
|
||||
position: absolute;
|
||||
bottom: max(20px, env(safe-area-inset-bottom));
|
||||
left: clamp(54px, var(--reaction-left), calc(100% - 54px));
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
gap: 5px;
|
||||
width: 100px;
|
||||
margin-left: -50px;
|
||||
animation: auction-reaction-rise 2.8s cubic-bezier(0.18, 0.6, 0.25, 1) both;
|
||||
will-change: transform, opacity;
|
||||
}
|
||||
.auction-floating-emoji {
|
||||
font-family:
|
||||
"Apple Color Emoji", "Segoe UI Emoji", "Noto Color Emoji", sans-serif;
|
||||
font-size: 48px;
|
||||
line-height: 1.15;
|
||||
filter: drop-shadow(0 3px 5px #0002);
|
||||
}
|
||||
.auction-floating-name {
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
border-radius: 999px;
|
||||
padding: 3px 8px;
|
||||
background: #22252ee6;
|
||||
color: #fff;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
@keyframes auction-reaction-rise {
|
||||
0% {
|
||||
opacity: 0;
|
||||
transform: translate3d(0, 32px, 0) scale(0.65) rotate(0);
|
||||
}
|
||||
12% {
|
||||
opacity: 1;
|
||||
}
|
||||
40% {
|
||||
transform: translate3d(var(--reaction-drift), -18vh, 0) scale(1.08)
|
||||
rotate(var(--reaction-tilt));
|
||||
}
|
||||
70% {
|
||||
opacity: 1;
|
||||
}
|
||||
100% {
|
||||
opacity: 0;
|
||||
transform: translate3d(0, -48vh, 0) scale(0.9) rotate(0);
|
||||
}
|
||||
}
|
||||
@keyframes auction-reaction-fade {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 0;
|
||||
}
|
||||
15%,
|
||||
75% {
|
||||
opacity: 1;
|
||||
}
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.auction-floating-reaction {
|
||||
animation: auction-reaction-fade 2.8s linear both;
|
||||
transform: none;
|
||||
will-change: opacity;
|
||||
}
|
||||
}
|
||||
@media (pointer: coarse), (max-width: 639px) {
|
||||
.auction-chat-panel .auction-chat-reaction-trigger {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
min-width: 44px;
|
||||
}
|
||||
.auction-floating-emoji {
|
||||
font-size: 40px;
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
import { useMemo, useRef, useState, type SubmitEvent } from "react";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import type {
|
||||
CompetitionCommandResponse,
|
||||
@@ -170,7 +170,7 @@ export function CompetitionAdminControls({
|
||||
resetCommandFeedback();
|
||||
}
|
||||
|
||||
function handleAdjudicationSubmit(event: React.FormEvent) {
|
||||
function handleAdjudicationSubmit(event: SubmitEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!selectedSeries || !canAdjudicate || !adjudicationReason.trim()) {
|
||||
return;
|
||||
@@ -216,7 +216,7 @@ export function CompetitionAdminControls({
|
||||
);
|
||||
}
|
||||
|
||||
function handlePreviewSubmit(event: React.FormEvent) {
|
||||
function handlePreviewSubmit(event: SubmitEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (!selectedSeries || !canReverse || !reversalReason.trim()) return;
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@ import type {
|
||||
MatchId,
|
||||
TeamId,
|
||||
} from "@lolympus/contracts";
|
||||
import { ChevronDown } from "lucide-react";
|
||||
import { useState } from "react";
|
||||
import { useLocation } from "react-router";
|
||||
import {
|
||||
formatCompetitionHistoryDate,
|
||||
@@ -73,10 +71,7 @@ export function CompetitionSeriesHistory({
|
||||
className="inline-flex min-h-11 shrink-0 items-center gap-1 px-2 text-xs font-bold text-content-muted transition-colors hover:bg-base-content/[0.03] hover:text-base-content focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
|
||||
>
|
||||
{jumpLabel}
|
||||
<ChevronDown
|
||||
className="h-4 w-4 text-primary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<span aria-hidden="true">↓</span>
|
||||
</a>
|
||||
)}
|
||||
</header>
|
||||
@@ -121,7 +116,6 @@ export function CompetitionSeriesHistory({
|
||||
communityId={communityId}
|
||||
matchId={matchId}
|
||||
historyPath={historyPath}
|
||||
currentHash={location.hash}
|
||||
/>
|
||||
</li>
|
||||
))}
|
||||
@@ -140,18 +134,15 @@ function SeriesHistoryRow({
|
||||
communityId,
|
||||
matchId,
|
||||
historyPath,
|
||||
currentHash,
|
||||
}: {
|
||||
row: CompetitionSeriesHistoryRow;
|
||||
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||
communityId: CommunityId;
|
||||
matchId: MatchId;
|
||||
historyPath: string;
|
||||
currentHash: string;
|
||||
}) {
|
||||
const detailsId = seriesHistoryDetailsId(row.series.seriesId);
|
||||
const seriesHash = `#${detailsId}`;
|
||||
const [expanded, setExpanded] = useState(currentHash === seriesHash);
|
||||
|
||||
if (row.games.length === 0) {
|
||||
return (
|
||||
@@ -164,19 +155,14 @@ function SeriesHistoryRow({
|
||||
}
|
||||
|
||||
return (
|
||||
<details
|
||||
id={detailsId}
|
||||
className="group scroll-mt-24"
|
||||
open={expanded}
|
||||
onToggle={(event) => setExpanded(event.currentTarget.open)}
|
||||
>
|
||||
<summary className="list-none cursor-pointer transition-colors hover:bg-base-content/[0.04] active:bg-base-content/[0.06] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary group-open:bg-base-content/[0.025] [&::-webkit-details-marker]:hidden">
|
||||
<section id={detailsId} className="group scroll-mt-24">
|
||||
<header>
|
||||
<SeriesSummary
|
||||
row={row}
|
||||
teamById={teamById}
|
||||
hasGameDetails
|
||||
/>
|
||||
</summary>
|
||||
</header>
|
||||
<CompetitionGameHistory
|
||||
games={row.games}
|
||||
teamById={teamById}
|
||||
@@ -184,7 +170,7 @@ function SeriesHistoryRow({
|
||||
matchId={matchId}
|
||||
historyBackTo={`${historyPath}${seriesHash}`}
|
||||
/>
|
||||
</details>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -203,10 +189,9 @@ function SeriesSummary({
|
||||
series.stage.type,
|
||||
series.stage.roundNumber,
|
||||
);
|
||||
const closedRecordLabel = getSeriesHistoryRecordLabel(
|
||||
const recordLabel = getSeriesHistoryRecordLabel(
|
||||
series,
|
||||
row.games.length,
|
||||
false,
|
||||
);
|
||||
const showRecordLabel = hasGameDetails || !isFutureSeries(series);
|
||||
|
||||
@@ -228,20 +213,7 @@ function SeriesSummary({
|
||||
|
||||
{showRecordLabel && (
|
||||
<span className="mt-2 flex min-h-6 items-center justify-end text-xs font-bold text-content-muted lg:col-start-3 lg:row-start-1 lg:mt-0">
|
||||
{hasGameDetails ? (
|
||||
<>
|
||||
<span className="group-open:hidden">{closedRecordLabel}</span>
|
||||
<span className="hidden group-open:inline">
|
||||
{getSeriesHistoryRecordLabel(series, row.games.length, true)}
|
||||
</span>
|
||||
<ChevronDown
|
||||
className="ml-1 h-4 w-4 text-primary transition-transform group-open:rotate-180 motion-reduce:transition-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<span>{closedRecordLabel}</span>
|
||||
)}
|
||||
<span>{recordLabel}</span>
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
|
||||
@@ -23,10 +23,6 @@ export function DoubleEliminationMobileBracket({
|
||||
projection.series.map((series) => [series.seriesId, series]),
|
||||
);
|
||||
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||
const isCurrentRound = (seriesIds: readonly SeriesId[]) => seriesIds.some((seriesId) => {
|
||||
const status = seriesById.get(seriesId)?.status;
|
||||
return status === "ready" || status === "in-progress";
|
||||
});
|
||||
const sections = [
|
||||
{
|
||||
key: "upper",
|
||||
@@ -77,17 +73,11 @@ export function DoubleEliminationMobileBracket({
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
{groups.map((group) => (
|
||||
<details
|
||||
key={`${group.stage}:${group.roundNumber}`}
|
||||
open={groups.length === 1 || isCurrentRound(group.seriesIds)}
|
||||
className="group lts-panel"
|
||||
>
|
||||
<summary
|
||||
className="cursor-pointer px-3 py-3 text-sm font-semibold hover:bg-sunken"
|
||||
>
|
||||
<section key={`${group.stage}:${group.roundNumber}`} className="group lts-panel">
|
||||
<h4 className="px-3 py-3 text-sm font-semibold ">
|
||||
{group.accessibleLabel}
|
||||
<span className="ml-2 text-xs font-medium text-content-muted">{group.seriesIds.length}경기</span>
|
||||
</summary>
|
||||
</h4>
|
||||
<div className="space-y-3 border-t border-line p-3">
|
||||
{group.seriesIds.map((seriesId) => {
|
||||
const series = seriesById.get(seriesId);
|
||||
@@ -117,7 +107,7 @@ export function DoubleEliminationMobileBracket({
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import type { CompetitionTeamView } from "@lolympus/contracts";
|
||||
import { sortTeamMembersForRoster } from "../../pages/match-team-progress-view";
|
||||
import { SummonerAvatar } from "../SummonerAvatar";
|
||||
|
||||
export function TeamMemberSummary({ team }: { team: CompetitionTeamView }) {
|
||||
const members = sortTeamMembersForRoster(team.members);
|
||||
if (members.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1.5">
|
||||
<span className="flex shrink-0 -space-x-1.5 py-1.5 pr-1" aria-hidden="true">
|
||||
{members.map((member) => (
|
||||
<SummonerAvatar
|
||||
key={member.userId}
|
||||
profileIconId={member.profileIconId}
|
||||
isCaptain={member.userId === team.captainUserId}
|
||||
size="sm"
|
||||
shape="circle"
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
<p className="min-w-0 basis-48 grow text-[13px] leading-5 text-content-muted">
|
||||
{members.map((member, index) => (
|
||||
<span key={member.userId}>
|
||||
{index > 0 && <span aria-hidden="true"> · </span>}
|
||||
{index > 0 && <span className="sr-only">, </span>}
|
||||
<span className="inline-block max-w-full align-top [overflow-wrap:anywhere]">{member.displayName}</span>
|
||||
{member.userId === team.captainUserId && <span className="sr-only"> (팀장)</span>}
|
||||
</span>
|
||||
))}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { CompetitionTeamView } from "@lolympus/contracts";
|
||||
import { Link } from "react-router";
|
||||
import { positionLabel } from "../../lib/league";
|
||||
import { sortTeamMembersForRoster } from "../../pages/match-team-progress-view";
|
||||
import { SummonerAvatar } from "../SummonerAvatar";
|
||||
|
||||
export function TeamRoster({ team }: { team: CompetitionTeamView }) {
|
||||
return (
|
||||
<ul className="lts-panel divide-y divide-line">
|
||||
{sortTeamMembersForRoster(team.members).map((member) => (
|
||||
<li key={member.userId}>
|
||||
<Link
|
||||
to={`/users/${member.userId}/history?queueGroup=internal`}
|
||||
className="group grid min-h-16 grid-cols-[2.5rem_2.5rem_minmax(0,1fr)] items-center gap-3 px-4 py-3 transition-colors hover:bg-sunken focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:px-5"
|
||||
>
|
||||
<span className="text-xs font-semibold text-content-muted">
|
||||
{member.assignedPosition ? positionLabel[member.assignedPosition] : "미정"}
|
||||
</span>
|
||||
<SummonerAvatar
|
||||
profileIconId={member.profileIconId}
|
||||
isCaptain={member.userId === team.captainUserId}
|
||||
/>
|
||||
<span className="min-w-0 text-sm font-bold text-base-content [overflow-wrap:anywhere] group-hover:underline">
|
||||
{member.displayName}
|
||||
<span className="sr-only"> 전적 보기</span>
|
||||
</span>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
type TeamSeriesTone,
|
||||
} from "../../pages/match-team-progress-view";
|
||||
import { isSeriesEntryWinner } from "./series-score-card-model";
|
||||
import { TeamMemberSummary } from "./TeamMemberSummary";
|
||||
|
||||
const STATUS_TONE_CLASS: Record<TeamSeriesTone, string> = {
|
||||
muted: "border-base-content/15 bg-base-200 text-base-content",
|
||||
@@ -38,7 +39,7 @@ export function TeamSeriesCard({
|
||||
|
||||
return (
|
||||
<article
|
||||
className={`overflow-hidden border bg-base-100 ${
|
||||
className={`overflow-hidden rounded-box border bg-base-100 ${
|
||||
emphasized ? "border-primary/30" : "border-base-content/10"
|
||||
}`}
|
||||
aria-labelledby={headingId}
|
||||
@@ -50,19 +51,19 @@ export function TeamSeriesCard({
|
||||
: "border-base-content/10 bg-base-200/40"
|
||||
}`}
|
||||
>
|
||||
<div className="min-w-0">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-x-3 gap-y-1 self-center">
|
||||
<h3
|
||||
id={headingId}
|
||||
className="break-words text-base font-black text-base-content"
|
||||
className="break-words text-xs font-bold text-content-muted"
|
||||
>
|
||||
{displayLabel}
|
||||
</h3>
|
||||
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-content-muted">
|
||||
<div className="text-xs text-content-muted">
|
||||
<span>{seriesRuleLabel(series)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span
|
||||
className={`shrink-0 border-l-2 px-2 py-1 text-xs font-bold ${STATUS_TONE_CLASS[presentation.tone]}`}
|
||||
className={`inline-flex shrink-0 items-center rounded-full border px-2 py-1 text-xs font-bold ${STATUS_TONE_CLASS[presentation.tone]}`}
|
||||
>
|
||||
{presentation.label}
|
||||
</span>
|
||||
@@ -81,31 +82,32 @@ export function TeamSeriesCard({
|
||||
return (
|
||||
<li
|
||||
key={entry.slot}
|
||||
className={`grid min-h-12 grid-cols-[minmax(0,1fr)_3rem] items-center gap-3 px-4 py-2.5 sm:px-5 ${
|
||||
isHighlightedTeam ? "bg-base-200/35" : ""
|
||||
}`}
|
||||
className="grid grid-cols-[minmax(0,1fr)_2.5rem] items-center gap-3 px-4 py-3 sm:px-5"
|
||||
>
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<span
|
||||
className={`min-w-0 break-words text-sm ${
|
||||
isWinner || isHighlightedTeam
|
||||
? "font-bold text-base-content"
|
||||
: "text-content-subtle"
|
||||
}`}
|
||||
>
|
||||
<span className="sr-only">{entry.slot} 슬롯: </span>
|
||||
{teamName}
|
||||
</span>
|
||||
{isHighlightedTeam && (
|
||||
<span className="border border-base-content/15 bg-base-100 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||
이 팀
|
||||
<div className="min-w-0 space-y-1.5">
|
||||
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||
<span
|
||||
className={`min-w-0 break-words text-base text-base-content ${
|
||||
isWinner || isHighlightedTeam
|
||||
? "font-bold"
|
||||
: "font-semibold"
|
||||
}`}
|
||||
>
|
||||
<span className="sr-only">{entry.slot} 슬롯: </span>
|
||||
{teamName}
|
||||
</span>
|
||||
)}
|
||||
{isWinner && (
|
||||
<span className="border-l-2 border-success bg-success/10 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||
승리
|
||||
</span>
|
||||
)}
|
||||
{isHighlightedTeam && (
|
||||
<span className="inline-flex items-center rounded-full border border-base-content/15 bg-base-100 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||
우리 팀
|
||||
</span>
|
||||
)}
|
||||
{isWinner && (
|
||||
<span className="inline-flex items-center rounded-full border border-success bg-success/10 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||
승리
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{team && <TeamMemberSummary team={team} />}
|
||||
</div>
|
||||
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content">
|
||||
<span className="sr-only">
|
||||
@@ -129,7 +131,7 @@ export function TeamSeriesCard({
|
||||
|
||||
function seriesRuleLabel(series: SeriesProjection): string {
|
||||
if (series.rule.type === "fixed-games") {
|
||||
return `${series.rule.gameCount}게임`;
|
||||
return `총 ${series.rule.gameCount}경기`;
|
||||
}
|
||||
return `${series.rule.maxGames}전 ${series.rule.winsRequired}선승`;
|
||||
}
|
||||
@@ -99,97 +99,96 @@ export function TeamTournamentCodes({
|
||||
}
|
||||
}
|
||||
|
||||
const nextAssignment = assignments.find((assignment) => assignment.state !== "used") ?? assignments[0];
|
||||
const otherAssignments = assignments.filter((assignment) => assignment !== nextAssignment);
|
||||
|
||||
function renderAssignment(assignment: TeamTournamentCodeView) {
|
||||
const slotId = String(assignment.gameSlotId);
|
||||
const presentation = getTournamentCodePresentation(assignment, now);
|
||||
const isCopying = copyingSlotId === slotId;
|
||||
const copied =
|
||||
feedback?.kind === "success" && feedback.gameSlotId === slotId;
|
||||
return (
|
||||
<li
|
||||
key={slotId}
|
||||
className="grid gap-3 px-4 py-3 sm:px-5 md:grid-cols-[5.5rem_minmax(0,1fr)_auto] md:items-center"
|
||||
>
|
||||
<div>
|
||||
<p className="text-sm font-bold text-base-content">
|
||||
{assignment.ordinal}세트
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-content-muted">
|
||||
전체 {assignment.displayNumber}경기
|
||||
</p>
|
||||
</div>
|
||||
const slotId = String(assignment.gameSlotId);
|
||||
const presentation = getTournamentCodePresentation(assignment, now);
|
||||
const isCopying = copyingSlotId === slotId;
|
||||
const copied =
|
||||
feedback?.kind === "success" && feedback.gameSlotId === slotId;
|
||||
return (
|
||||
<li
|
||||
key={slotId}
|
||||
className="grid grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-2 px-4 py-3 sm:grid-cols-[5.5rem_minmax(0,1fr)_auto] sm:px-5"
|
||||
>
|
||||
<div className="col-span-2 flex flex-wrap items-center gap-x-3 gap-y-1 sm:col-span-1 sm:block">
|
||||
<div>
|
||||
<p className="text-sm font-bold text-base-content">
|
||||
{assignment.ordinal}세트
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-content-muted">
|
||||
대회 경기 #{assignment.displayNumber}
|
||||
</p>
|
||||
</div>
|
||||
<span
|
||||
className={`inline-flex items-center rounded-full border px-1.5 py-0.5 text-[11px] font-semibold sm:mt-1.5 ${CODE_TONE_CLASS[presentation.tone]}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{presentation.label}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="min-w-0">
|
||||
{assignment.code ? (
|
||||
<AutoSizingCodeField
|
||||
label={`${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드`}
|
||||
value={assignment.code}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm font-bold text-content-muted">
|
||||
발급되면 이곳에서 복사할 수 있습니다.
|
||||
</p>
|
||||
)}
|
||||
{assignment.code &&
|
||||
assignment.state === "reserved" &&
|
||||
assignment.expiresAt && (
|
||||
<p className="mt-1 text-xs text-content-muted">
|
||||
<time dateTime={assignment.expiresAt}>
|
||||
{getTournamentCodeExpiryLabel(
|
||||
assignment.expiresAt,
|
||||
now,
|
||||
)}
|
||||
</time>
|
||||
</p>
|
||||
<div className="min-w-0">
|
||||
{assignment.code ? (
|
||||
<AutoSizingCodeField
|
||||
label={`${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드`}
|
||||
value={assignment.code}
|
||||
/>
|
||||
) : (
|
||||
<p className="text-sm font-bold text-content-muted">
|
||||
발급되면 이곳에서 복사할 수 있습니다.
|
||||
</p>
|
||||
)}
|
||||
{assignment.code &&
|
||||
assignment.state === "reserved" &&
|
||||
assignment.expiresAt && (
|
||||
<p className="mt-1 text-xs text-content-muted">
|
||||
<time dateTime={assignment.expiresAt}>
|
||||
{getTournamentCodeExpiryLabel(
|
||||
assignment.expiresAt,
|
||||
now,
|
||||
)}
|
||||
</div>
|
||||
</time>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 md:justify-end">
|
||||
<span
|
||||
className={`border-l-2 px-2 py-1 text-xs font-bold ${CODE_TONE_CLASS[presentation.tone]}`}
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
aria-atomic="true"
|
||||
>
|
||||
{presentation.label}
|
||||
</span>
|
||||
{assignment.code && assignment.state === "reserved" && (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-11 items-center justify-center gap-1.5 border border-base-content/20 bg-base-100 px-3 text-sm font-bold text-base-content hover:border-primary/50 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-70"
|
||||
aria-label={
|
||||
presentation.canCopy
|
||||
? getTournamentCodeCopyLabel(assignment, seriesLabel)
|
||||
: `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 만료됨`
|
||||
}
|
||||
disabled={!presentation.canCopy || copyingSlotId !== null}
|
||||
onClick={() => void handleCopy(assignment)}
|
||||
>
|
||||
{!presentation.canCopy ? null : isCopying ? (
|
||||
<LoaderCircle
|
||||
className="h-4 w-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : copied ? (
|
||||
<Check className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
{!presentation.canCopy
|
||||
? "복사 불가"
|
||||
: isCopying
|
||||
? "복사 중"
|
||||
: copied
|
||||
? "복사됨"
|
||||
: "복사"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
<div className="flex min-w-20 justify-end">
|
||||
{assignment.code && assignment.state === "reserved" && (
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex min-h-11 min-w-20 items-center justify-center gap-1.5 rounded-field border border-base-content/20 bg-base-100 px-3 text-sm font-bold text-base-content hover:border-primary/50 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-not-allowed disabled:opacity-70"
|
||||
aria-label={
|
||||
presentation.canCopy
|
||||
? getTournamentCodeCopyLabel(assignment, seriesLabel)
|
||||
: `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 만료됨`
|
||||
}
|
||||
disabled={!presentation.canCopy || copyingSlotId !== null}
|
||||
onClick={() => void handleCopy(assignment)}
|
||||
>
|
||||
{!presentation.canCopy ? null : isCopying ? (
|
||||
<LoaderCircle
|
||||
className="h-4 w-4 animate-spin motion-reduce:animate-none"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
) : copied ? (
|
||||
<Check className="h-4 w-4" aria-hidden="true" />
|
||||
) : (
|
||||
<Copy className="h-4 w-4" aria-hidden="true" />
|
||||
)}
|
||||
{!presentation.canCopy
|
||||
? "복사 불가"
|
||||
: isCopying
|
||||
? "복사 중"
|
||||
: copied
|
||||
? "복사됨"
|
||||
: "복사"}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -197,22 +196,13 @@ export function TeamTournamentCodes({
|
||||
className="border-t border-base-content/10 bg-sunken/50"
|
||||
aria-label={`${seriesLabel} 토너먼트 코드`}
|
||||
>
|
||||
<div className="px-4 pt-3 sm:px-5">
|
||||
<div className="flex items-center justify-between gap-3 border-b border-line px-4 py-3 sm:px-5">
|
||||
<h4 className="text-sm font-bold">토너먼트 코드</h4>
|
||||
<span className="text-xs text-content-muted">{assignments.length}세트</span>
|
||||
</div>
|
||||
<ol>
|
||||
{renderAssignment(nextAssignment)}
|
||||
<ol className="divide-y divide-line">
|
||||
{assignments.map(renderAssignment)}
|
||||
</ol>
|
||||
{otherAssignments.length > 0 && (
|
||||
<details className="border-t border-line">
|
||||
<summary className="cursor-pointer px-4 py-3 text-sm font-semibold hover:bg-sunken sm:px-5">
|
||||
다른 세트 코드 · {otherAssignments.length}개
|
||||
</summary>
|
||||
<ol className="divide-y divide-line border-t border-line">
|
||||
{otherAssignments.map(renderAssignment)}
|
||||
</ol>
|
||||
</details>
|
||||
)}
|
||||
|
||||
{feedback && (
|
||||
<p
|
||||
|
||||
@@ -193,10 +193,9 @@ export function getSeriesHistoryResultLabel(
|
||||
export function getSeriesHistoryRecordLabel(
|
||||
series: CompetitionSeriesHistorySeries,
|
||||
gameCount: number,
|
||||
expanded: boolean,
|
||||
): string {
|
||||
if (gameCount > 0) {
|
||||
return expanded ? "게임 상세 접기" : `게임 상세 (${gameCount})`;
|
||||
return `게임 기록 ${gameCount}개`;
|
||||
}
|
||||
if (
|
||||
series.status === "inactive" ||
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
import {
|
||||
ArrowRight,
|
||||
CalendarDays,
|
||||
ChevronRight,
|
||||
Clock3,
|
||||
Info,
|
||||
Users,
|
||||
} from "lucide-react";
|
||||
import type { SeriesProjection } from "@lolympus/contracts";
|
||||
import type { ApiInternalMatchCard } from "../../api/types";
|
||||
import pixelMedal from "../../assets/pixel-medal-first.svg";
|
||||
import { formatOfficialMatchResult } from "../../lib/internal-stats-presentation";
|
||||
import {
|
||||
getSeriesHistoryResultLabel,
|
||||
shouldDisplaySeriesHistoryScore,
|
||||
} from "../competition/competition-series-history";
|
||||
import { StatsLink } from "./StatsShared";
|
||||
import { statsDate, statsDuration } from "./stats-navigation";
|
||||
import { statsGroups } from "./stats-model";
|
||||
|
||||
function statsFormat(match: ApiInternalMatchCard) {
|
||||
const result = match.resultPresentation;
|
||||
if (result?.type !== "official")
|
||||
return match.teams.length === 2 ? "두 팀 내전" : "내전 기록";
|
||||
return {
|
||||
"paired-series": "두 팀 내전",
|
||||
"double-elimination": "더블 엘리미네이션",
|
||||
"round-robin": "리그전",
|
||||
}[result.formatType];
|
||||
}
|
||||
function seriesLabel(series: SeriesProjection | undefined) {
|
||||
if (!series) return "공식 시리즈 정보 없음";
|
||||
if (series.stage.type === "pair")
|
||||
return series.rule.type === "first-to"
|
||||
? `${series.rule.winsRequired}선승 시리즈`
|
||||
: `${series.rule.gameCount}세트 시리즈`;
|
||||
return `${{ upper: "승자조", lower: "패자조", "grand-final": "최종 결승", "reset-final": "결승 재경기", "round-robin": "리그" }[series.stage.type]}${series.stage.roundNumber ? ` ${series.stage.roundNumber}라운드` : ""}`;
|
||||
}
|
||||
export function StatsEventOverview({ match }: { match: ApiInternalMatchCard }) {
|
||||
const analyzed = match.games.every(
|
||||
(g) => g.analysisAvailability !== undefined,
|
||||
)
|
||||
? match.games.filter((g) => g.analysisAvailability === "available").length
|
||||
: "—";
|
||||
return (
|
||||
<div className="is-event-overview">
|
||||
<div className="is-event-meta">
|
||||
<span>
|
||||
<CalendarDays size={14} />
|
||||
<time dateTime={match.scheduledAt}>
|
||||
{statsDate(match.scheduledAt)}{" "}
|
||||
{new Intl.DateTimeFormat("ko-KR", {
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
hour12: false,
|
||||
timeZone: "Asia/Seoul",
|
||||
}).format(new Date(match.scheduledAt))}
|
||||
</time>
|
||||
</span>
|
||||
<span>
|
||||
<Users size={14} />
|
||||
{match.teams.length}팀 ·{" "}
|
||||
{match.teams.reduce((n, t) => n + t.members.length, 0)}명
|
||||
</span>
|
||||
<span>{match.games.length}세트 결과</span>
|
||||
<span className="is-analysis-count">{analyzed}세트 분석 가능</span>
|
||||
</div>
|
||||
<span className="is-champion-label">
|
||||
<img src={pixelMedal} alt="" className="size-4 shrink-0 [image-rendering:pixelated]" />
|
||||
<strong>{formatOfficialMatchResult(match.resultPresentation)}</strong>
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function StatsSeries({
|
||||
match,
|
||||
gameHref,
|
||||
}: {
|
||||
match: ApiInternalMatchCard;
|
||||
gameHref: (number: number) => string;
|
||||
}) {
|
||||
const team = (index: number) =>
|
||||
match.teams.find((t) => t.teamIndex === index)?.name ?? `${index}팀`;
|
||||
const officialTeam = (id: string | null) =>
|
||||
match.teams.find((t) => t.teamId === id)?.name ??
|
||||
(id ? "팀 미확인" : "상대 미정");
|
||||
return (
|
||||
<div className="is-series-grid">
|
||||
{statsGroups(match).map(({ id, series, games }) => {
|
||||
const first = games[0],
|
||||
label = seriesLabel(series);
|
||||
const [a, b] = series?.entries ?? [];
|
||||
const score = series && shouldDisplaySeriesHistoryScore(series);
|
||||
const winner =
|
||||
series?.status === "completed" && series.outcome.type !== "draw"
|
||||
? series.outcome.winnerTeamId
|
||||
: null;
|
||||
return (
|
||||
<section className="is-series-group" key={id} aria-label={label}>
|
||||
<header>
|
||||
<span>{label}</span>
|
||||
<span>
|
||||
{games.length}세트
|
||||
{series &&
|
||||
score &&
|
||||
games.length !== (a?.gameWins ?? 0) + (b?.gameWins ?? 0)
|
||||
? " · 기간 내 기록"
|
||||
: ""}
|
||||
</span>
|
||||
</header>
|
||||
<div className="is-matchup">
|
||||
<strong
|
||||
className={winner && winner === a?.teamId ? "is-winner" : ""}
|
||||
>
|
||||
{a
|
||||
? officialTeam(a.teamId)
|
||||
: first
|
||||
? team(first.blueTeamIndex)
|
||||
: "팀 미확인"}
|
||||
</strong>
|
||||
<span className="is-score">
|
||||
{score ? (
|
||||
<>
|
||||
<b>{a?.gameWins}</b>
|
||||
<i>:</i>
|
||||
<b>{b?.gameWins}</b>
|
||||
</>
|
||||
) : series ? (
|
||||
(getSeriesHistoryResultLabel(series) ?? "VS")
|
||||
) : (
|
||||
"VS"
|
||||
)}
|
||||
</span>
|
||||
<strong
|
||||
className={winner && winner === b?.teamId ? "is-winner" : ""}
|
||||
>
|
||||
{b
|
||||
? officialTeam(b.teamId)
|
||||
: first
|
||||
? team(first.redTeamIndex)
|
||||
: "팀 미확인"}
|
||||
</strong>
|
||||
</div>
|
||||
<ul>
|
||||
{games.map((game) => (
|
||||
<li key={game.gameNumber}>
|
||||
<span className="is-set-number">
|
||||
{game.ordinal ?? game.gameNumber}세트
|
||||
<small>전체 #{game.gameNumber}</small>
|
||||
</span>
|
||||
<span className="is-set-winner">
|
||||
{game.winnerTeamIndex !== null ? (
|
||||
<>
|
||||
<span className="is-win-badge">승</span>
|
||||
{team(game.winnerTeamIndex)}
|
||||
</>
|
||||
) : (
|
||||
"결과 미확정"
|
||||
)}
|
||||
</span>
|
||||
<span className="is-duration">
|
||||
<Clock3 size={12} />
|
||||
{statsDuration(game.gameDuration)}
|
||||
</span>
|
||||
<StatsLink
|
||||
className={`is-analysis-link ${game.analysisAvailability !== "available" ? "is-unavailable" : ""}`}
|
||||
to={gameHref(game.gameNumber)}
|
||||
data-return-id={`set-${match.matchId}-${game.gameNumber}`}
|
||||
aria-label={`${match.title} 전체 ${game.gameNumber}세트 ${game.analysisAvailability === "missing" ? "원본 상태 확인" : "상세 분석"}`}
|
||||
>
|
||||
{game.analysisAvailability === "missing"
|
||||
? "원본 없음"
|
||||
: game.analysisAvailability === "pending"
|
||||
? "준비 중"
|
||||
: "분석"}
|
||||
{game.analysisAvailability === "missing" ? (
|
||||
<Info size={12} />
|
||||
) : (
|
||||
<ChevronRight size={13} />
|
||||
)}
|
||||
</StatsLink>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
{games.length === 0 && (
|
||||
<p className="is-muted">
|
||||
{series && getSeriesHistoryResultLabel(series)} · 기록된 세트
|
||||
없음
|
||||
</p>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function StatsEvent({
|
||||
match,
|
||||
eventHref,
|
||||
gameHref,
|
||||
}: {
|
||||
match: ApiInternalMatchCard;
|
||||
eventHref: string;
|
||||
gameHref: (number: number) => string;
|
||||
}) {
|
||||
return (
|
||||
<article className="is-event-section" id={`event-${match.matchId}`}>
|
||||
<header>
|
||||
<div>
|
||||
<div className="is-event-kicker">
|
||||
<span>{statsFormat(match)}</span>
|
||||
{Boolean(match.series?.length) && (
|
||||
<span>{match.series!.length}개 시리즈</span>
|
||||
)}
|
||||
</div>
|
||||
<h3>
|
||||
<StatsLink to={eventHref} data-return-id={`event-${match.matchId}`}>
|
||||
{match.title}
|
||||
<ChevronRight size={18} />
|
||||
</StatsLink>
|
||||
</h3>
|
||||
</div>
|
||||
<StatsLink
|
||||
className="is-text-link is-event-detail-link"
|
||||
to={eventHref}
|
||||
data-return-id={`event-detail-${match.matchId}`}
|
||||
>
|
||||
전체 기록
|
||||
<ArrowRight size={15} />
|
||||
</StatsLink>
|
||||
</header>
|
||||
<StatsEventOverview match={match} />
|
||||
<StatsSeries match={match} gameHref={gameHref} />
|
||||
{match.games.length === 0 && (
|
||||
<p className="is-event-empty is-muted">
|
||||
기록된 세트가 없습니다. 전체 기록에서 공식 결과를 확인할 수 있습니다.
|
||||
</p>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
export function StatsEventJump({
|
||||
matches,
|
||||
}: {
|
||||
matches: ApiInternalMatchCard[];
|
||||
}) {
|
||||
return (
|
||||
<nav className="is-event-jump" aria-label="내전 바로가기">
|
||||
<div className="is-jump-desktop">
|
||||
<p>
|
||||
<CalendarDays size={15} /> 내전 바로가기
|
||||
</p>
|
||||
{matches.map((m) => (
|
||||
<a href={`#event-${m.matchId}`} key={m.matchId}>
|
||||
<span>{statsDate(m.scheduledAt)}</span>
|
||||
<strong>{m.title}</strong>
|
||||
<small>{statsFormat(m)}</small>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
<label className="is-jump-mobile">
|
||||
<CalendarDays size={16} />
|
||||
<span>내전 이동</span>
|
||||
<select
|
||||
aria-label="내전 바로가기"
|
||||
defaultValue=""
|
||||
onChange={(e) =>
|
||||
document.getElementById(`event-${e.target.value}`)?.scrollIntoView({
|
||||
behavior: matchMedia("(prefers-reduced-motion: reduce)").matches
|
||||
? "instant"
|
||||
: "smooth",
|
||||
block: "start",
|
||||
})
|
||||
}
|
||||
>
|
||||
<option value="" disabled>
|
||||
날짜로 바로가기
|
||||
</option>
|
||||
{matches.map((m) => (
|
||||
<option key={m.matchId} value={m.matchId}>
|
||||
{statsDate(m.scheduledAt)} · {m.title}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,200 @@
|
||||
import { ArrowDown, ArrowDownUp, ArrowRight, Info } from "lucide-react";
|
||||
import type {
|
||||
ApiLeaderboardRow,
|
||||
DdragonManifest,
|
||||
RiotLane,
|
||||
} from "../../api/types";
|
||||
import { getMainLane } from "../../lib/internal-stats-presentation";
|
||||
import { profileIconUrl } from "../../lib/ddragon";
|
||||
import { LANE_LABELS } from "../../lib/riot-history";
|
||||
import { StatsChampion, StatsLink } from "./StatsShared";
|
||||
|
||||
import { STATS_SORTS, type StatsSort } from "./stats-model";
|
||||
export function StatsLeaderboard({
|
||||
rows,
|
||||
minimum,
|
||||
lane,
|
||||
sort,
|
||||
direction,
|
||||
onSort,
|
||||
playerHref,
|
||||
participationHref,
|
||||
manifest,
|
||||
}: {
|
||||
rows: Array<ApiLeaderboardRow & { rank: number }>;
|
||||
minimum: number;
|
||||
lane?: RiotLane;
|
||||
sort: StatsSort;
|
||||
direction: "asc" | "desc";
|
||||
onSort: (key: StatsSort) => void;
|
||||
playerHref: (id: string) => string;
|
||||
participationHref: (id: string) => string;
|
||||
manifest?: DdragonManifest;
|
||||
}) {
|
||||
const metric = (key: StatsSort, label: string) => (
|
||||
<th
|
||||
scope="col"
|
||||
aria-sort={
|
||||
sort === key
|
||||
? direction === "desc"
|
||||
? "descending"
|
||||
: "ascending"
|
||||
: "none"
|
||||
}
|
||||
>
|
||||
<button
|
||||
className={sort === key ? "is-sorted" : ""}
|
||||
onClick={() => onSort(key)}
|
||||
>
|
||||
{label}
|
||||
{sort === key ? (
|
||||
<ArrowDown
|
||||
size={13}
|
||||
className={direction === "asc" ? "is-arrow-up" : ""}
|
||||
/>
|
||||
) : (
|
||||
<ArrowDownUp size={12} />
|
||||
)}
|
||||
</button>
|
||||
</th>
|
||||
);
|
||||
return (
|
||||
<>
|
||||
<p className="is-table-hint">
|
||||
<ArrowRight size={14} />
|
||||
옆으로 이동하면 모든 지표를 볼 수 있어요. 선수 이름은 고정됩니다.
|
||||
</p>
|
||||
<div
|
||||
className="is-table-scroll"
|
||||
role="region"
|
||||
tabIndex={0}
|
||||
aria-label="선수 순위표, 좌우 방향키로 지표 이동"
|
||||
>
|
||||
<table className="is-leaderboard">
|
||||
<caption className="sr-only">
|
||||
{lane ? LANE_LABELS[lane] : "전체 포지션"} · {STATS_SORTS[sort]}{" "}
|
||||
{direction === "desc" ? "높은" : "낮은"} 순 · 최소 {minimum}판
|
||||
</caption>
|
||||
<colgroup>
|
||||
<col className="is-col-rank" />
|
||||
<col className="is-col-player" />
|
||||
<col className="is-col-win" />
|
||||
<col className="is-col-games" />
|
||||
<col className="is-col-kda" />
|
||||
<col className="is-col-champions" />
|
||||
<col />
|
||||
<col />
|
||||
<col />
|
||||
</colgroup>
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" className="is-sticky-rank">
|
||||
순위
|
||||
</th>
|
||||
<th scope="col" className="is-sticky-player">
|
||||
선수
|
||||
</th>
|
||||
{metric("winRate", "승률")}
|
||||
{metric("games", "판수")}
|
||||
{metric("kda", "KDA")}
|
||||
<th scope="col">주 챔피언</th>
|
||||
{metric("avgGoldPerMin", "GPM")}
|
||||
{metric("avgKillParticipation", "킬 관여")}
|
||||
{metric("avgCsPerMin", "CS/분")}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((row) => (
|
||||
<tr
|
||||
key={row.userId}
|
||||
className={row.games < minimum ? "is-under-qualified" : ""}
|
||||
>
|
||||
<td className="is-sticky-rank">
|
||||
<span className="is-rank-number">{row.rank}</span>
|
||||
</td>
|
||||
<th scope="row" className="is-sticky-player">
|
||||
<div className="is-player-identity">
|
||||
<img
|
||||
className="is-champion"
|
||||
src={profileIconUrl(manifest, row.profileIconId)}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
/>
|
||||
<div>
|
||||
<StatsLink
|
||||
to={playerHref(row.userId)}
|
||||
data-return-id={`player-${row.userId}`}
|
||||
>
|
||||
{row.summonerName}
|
||||
</StatsLink>
|
||||
<small>
|
||||
{LANE_LABELS[lane ?? getMainLane(row.byLane) ?? ""] ??
|
||||
"포지션 미확인"}
|
||||
<span>·</span>
|
||||
<StatsLink
|
||||
to={participationHref(row.userId)}
|
||||
data-return-id={`participation-${row.userId}`}
|
||||
>
|
||||
참가 내전
|
||||
</StatsLink>
|
||||
</small>
|
||||
{row.games < minimum && (
|
||||
<span className="is-sample-badge">기준 미달</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</th>
|
||||
<td>
|
||||
<strong className={row.winRate >= 50 ? "is-blue" : ""}>
|
||||
{row.winRate}
|
||||
<small>%</small>
|
||||
</strong>
|
||||
<div className="is-win-track" aria-hidden="true">
|
||||
<span style={{ width: `${row.winRate}%` }} />
|
||||
</div>
|
||||
</td>
|
||||
<td>
|
||||
<strong>{row.games}</strong>
|
||||
<small className="is-win-loss">
|
||||
{row.wins}승 {row.losses}패
|
||||
</small>
|
||||
</td>
|
||||
<td>
|
||||
<strong className={row.kda >= 3 ? "is-green" : ""}>
|
||||
{row.kda.toFixed(2)}
|
||||
</strong>
|
||||
</td>
|
||||
<td>
|
||||
<div className="is-champion-list">
|
||||
{row.topChampions.map((c) => (
|
||||
<span key={c.championId}>
|
||||
<StatsChampion
|
||||
id={c.championId}
|
||||
manifest={manifest}
|
||||
size="small"
|
||||
/>
|
||||
<small>{c.games}</small>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
</td>
|
||||
<td>{row.avgGoldPerMin}</td>
|
||||
<td>{row.avgKillParticipation}%</td>
|
||||
<td>{row.avgCsPerMin}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div className="is-table-footnote">
|
||||
<Info size={14} />
|
||||
<p>
|
||||
KDA는 (킬 + 어시스트) ÷ 데스, GPM은 분당 골드입니다.{" "}
|
||||
{lane &&
|
||||
`${LANE_LABELS[lane]}로 플레이한 경기의 모든 지표를 다시 집계합니다. `}
|
||||
검색해도 전체 순위는 유지됩니다.
|
||||
</p>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
import {
|
||||
useEffect,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
import { Link } from "react-router";
|
||||
import {
|
||||
ArrowLeft,
|
||||
Check,
|
||||
Copy,
|
||||
LoaderCircle,
|
||||
Search,
|
||||
ShieldAlert,
|
||||
} from "lucide-react";
|
||||
import type {
|
||||
ApiHistorySeason,
|
||||
DdragonManifest,
|
||||
RiotLane,
|
||||
} from "../../api/types";
|
||||
import { championDisplayName, championIconUrl } from "../../lib/ddragon";
|
||||
import { LANE_LABELS } from "../../lib/riot-history";
|
||||
import "./internal-stats.css";
|
||||
import { STATS_LANES, rememberStatsVisit } from "./stats-navigation";
|
||||
|
||||
export function StatsLink(props: ComponentProps<typeof Link>) {
|
||||
return (
|
||||
<Link
|
||||
{...props}
|
||||
onClick={(event) => {
|
||||
rememberStatsVisit();
|
||||
props.onClick?.(event);
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
export function StatsBack({
|
||||
to,
|
||||
children = "내전 전적으로 돌아가기",
|
||||
}: {
|
||||
to: string;
|
||||
children?: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<StatsLink className="is-back-link" to={to}>
|
||||
<ArrowLeft size={16} />
|
||||
{children}
|
||||
</StatsLink>
|
||||
);
|
||||
}
|
||||
export function StatsFeedback({
|
||||
type,
|
||||
title,
|
||||
children,
|
||||
action,
|
||||
}: {
|
||||
type: "empty" | "error" | "loading";
|
||||
title: string;
|
||||
children?: ReactNode;
|
||||
action?: ReactNode;
|
||||
}) {
|
||||
const Icon =
|
||||
type === "loading" ? LoaderCircle : type === "error" ? ShieldAlert : Search;
|
||||
return (
|
||||
<section
|
||||
className={`is-feedback is-feedback-${type}`}
|
||||
role={type === "error" ? "alert" : "status"}
|
||||
>
|
||||
<Icon size={26} aria-hidden="true" />
|
||||
<h2>{title}</h2>
|
||||
{children && <p>{children}</p>}
|
||||
{action && <div className="is-feedback-actions">{action}</div>}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
export function StatsChampion({
|
||||
id,
|
||||
manifest,
|
||||
size = "normal",
|
||||
}: {
|
||||
id: number;
|
||||
manifest?: DdragonManifest;
|
||||
size?: "small" | "normal" | "large";
|
||||
}) {
|
||||
const src = championIconUrl(manifest, id),
|
||||
name = championDisplayName(manifest, id) ?? "챔피언";
|
||||
return src ? (
|
||||
<img
|
||||
className={`is-champion is-champion-${size}`}
|
||||
src={src}
|
||||
alt={name}
|
||||
title={name}
|
||||
loading="lazy"
|
||||
/>
|
||||
) : (
|
||||
<span
|
||||
className={`is-champion is-champion-${size}`}
|
||||
aria-label="챔피언 이미지 없음"
|
||||
/>
|
||||
);
|
||||
}
|
||||
export function StatsSeasonControls({
|
||||
value,
|
||||
seasons,
|
||||
onChange,
|
||||
label,
|
||||
}: {
|
||||
value: string;
|
||||
seasons?: ApiHistorySeason[];
|
||||
onChange: (value: string) => void;
|
||||
label?: string;
|
||||
}) {
|
||||
const [notice, setNotice] = useState("");
|
||||
useEffect(() => {
|
||||
if (!notice) return;
|
||||
const timer = setTimeout(() => setNotice(""), 3000);
|
||||
return () => clearTimeout(timer);
|
||||
}, [notice]);
|
||||
return (
|
||||
<div className="is-page-actions">
|
||||
<button
|
||||
className="is-icon-button"
|
||||
aria-label="현재 전적 링크 복사"
|
||||
onClick={() =>
|
||||
void navigator.clipboard.writeText(location.href).then(
|
||||
() => setNotice("현재 조건이 포함된 링크를 복사했습니다."),
|
||||
() => setNotice("주소 표시줄의 링크를 복사해 주세요."),
|
||||
)
|
||||
}
|
||||
>
|
||||
{notice ? <Check size={17} /> : <Copy size={17} />}
|
||||
</button>
|
||||
<label className="is-season-select">
|
||||
<span>집계 시즌</span>
|
||||
<select value={value} onChange={(e) => onChange(e.target.value)}>
|
||||
<option value="current">현재 시즌</option>
|
||||
{seasons
|
||||
?.filter((s) => !["current", "all"].includes(s.id))
|
||||
.map((s) => (
|
||||
<option key={s.id} value={s.id}>
|
||||
{s.label}
|
||||
</option>
|
||||
))}
|
||||
<option value="all">전체 시즌</option>
|
||||
{!["current", "all"].includes(value) &&
|
||||
!seasons?.some((s) => s.id === value) && (
|
||||
<option value={value}>{label ?? value}</option>
|
||||
)}
|
||||
</select>
|
||||
</label>
|
||||
<div className="is-announcement" role="status">
|
||||
{notice}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
export function StatsLaneSelect({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value?: RiotLane;
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
return (
|
||||
<label className="is-select">
|
||||
<span className="sr-only">플레이 포지션</span>
|
||||
<select
|
||||
aria-label="플레이 포지션"
|
||||
value={value ?? ""}
|
||||
onChange={(e) => onChange(e.target.value)}
|
||||
>
|
||||
<option value="">전체 포지션</option>
|
||||
{STATS_LANES.map((lane) => (
|
||||
<option key={lane} value={lane}>
|
||||
{LANE_LABELS[lane]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
import { ChevronRight, Trophy } from "lucide-react";
|
||||
import type {
|
||||
ApiLeaderHighlight,
|
||||
ApiTeamInsightsResponse,
|
||||
} from "../../api/types";
|
||||
import { StatsLink } from "./StatsShared";
|
||||
import { statsPeriod } from "./stats-navigation";
|
||||
export function StatsSummary({
|
||||
data,
|
||||
href,
|
||||
}: {
|
||||
data: ApiTeamInsightsResponse;
|
||||
href: (highlight: ApiLeaderHighlight) => string;
|
||||
}) {
|
||||
const total = data.totals,
|
||||
rate = data.sideWinRate.confirmed;
|
||||
const records = [
|
||||
{
|
||||
label: "평균 KDA",
|
||||
value: data.topKda,
|
||||
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
|
||||
suffix: "",
|
||||
},
|
||||
{
|
||||
label: "누적 킬",
|
||||
value: data.mostKills,
|
||||
scope: "시즌 누적",
|
||||
suffix: "킬",
|
||||
},
|
||||
{
|
||||
label: "분당 골드",
|
||||
value: data.topTeamGpm,
|
||||
scope: "단일 경기 최고",
|
||||
suffix: "",
|
||||
},
|
||||
{
|
||||
label: "평균 킬 관여",
|
||||
value: data.topKillParticipation,
|
||||
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
|
||||
suffix: "%",
|
||||
},
|
||||
{
|
||||
label: "평균 분당 CS",
|
||||
value: data.bestFarm,
|
||||
scope: `시즌 최고 · 최소 ${data.minGamesThreshold}판`,
|
||||
suffix: "",
|
||||
},
|
||||
];
|
||||
return (
|
||||
<section className="is-season-summary" aria-label="커뮤니티 전체 시즌 요약">
|
||||
<div className="is-summary-topline">
|
||||
<span>
|
||||
<span className="is-current-dot" />
|
||||
{data.season.label} 요약
|
||||
</span>
|
||||
<span className="is-muted">
|
||||
커뮤니티 전체 · {statsPeriod(data.season)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="is-summary-metrics">
|
||||
<div>
|
||||
<span>진행한 내전</span>
|
||||
<strong>
|
||||
{total?.matches ?? "—"}
|
||||
<small>회</small>
|
||||
</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>기록된 세트</span>
|
||||
<strong>
|
||||
{total?.games ?? "—"}
|
||||
<small>판</small>
|
||||
</strong>
|
||||
</div>
|
||||
<div>
|
||||
<span>참가 선수</span>
|
||||
<strong>
|
||||
{total?.players ?? "—"}
|
||||
<small>명</small>
|
||||
</strong>
|
||||
</div>
|
||||
<div className="is-side-rate">
|
||||
<span>
|
||||
진영 승률<small>{rate?.sampleSize ?? 0}세트 기준</small>
|
||||
</span>
|
||||
<div>
|
||||
<strong className="is-blue">
|
||||
{rate?.sampleSize ? rate.blue : "—"}
|
||||
<small>%</small>
|
||||
</strong>
|
||||
<span>BLUE / RED</span>
|
||||
<strong className="is-red">
|
||||
{rate?.sampleSize ? rate.red : "—"}
|
||||
<small>%</small>
|
||||
</strong>
|
||||
</div>
|
||||
<div className="is-side-track" aria-hidden="true">
|
||||
<span style={{ width: `${rate?.blue ?? 50}%` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="is-records-heading">
|
||||
<Trophy size={14} />
|
||||
<h2>시즌 기록</h2>
|
||||
<span>
|
||||
분석 가능한 {total?.analyzedGames ?? "—"}세트 기준 · 검색 조건과 별도
|
||||
집계
|
||||
</span>
|
||||
</div>
|
||||
<div className="is-records">
|
||||
{records.map((record) => (
|
||||
<div className="is-record" key={record.label}>
|
||||
<p>
|
||||
{record.label}
|
||||
<span>{record.scope}</span>
|
||||
</p>
|
||||
<div>
|
||||
<strong>
|
||||
{record.value?.metric ?? "—"}
|
||||
<small>{record.suffix}</small>
|
||||
</strong>
|
||||
{record.value ? (
|
||||
<StatsLink
|
||||
to={href(record.value)}
|
||||
data-return-id={`record-${record.label}`}
|
||||
aria-label={`${record.label} ${record.value.summonerName} ${record.value.isSingleGame ? "근거 경기" : "시즌 전적"}`}
|
||||
>
|
||||
{record.value.summonerName}
|
||||
<ChevronRight size={13} />
|
||||
</StatsLink>
|
||||
) : (
|
||||
<span className="is-muted">기록 없음</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
# 내전 전적 제품 반영 · 2026-11-11
|
||||
|
||||
승인된 `src/design-previews/internal-stats` 시안의 정보 구조와 스타일을 실제 라우트와 API에 반영했다. 시안의 fixture는 제품 코드에서 사용하지 않는다. 모든 세트는 표시하며 접기/아코디언을 추가하지 않았다.
|
||||
|
||||
## 반영 범위
|
||||
|
||||
- 시즌 전체 요약과 5개 기록, 최근 내전/선수 순위의 별도 검색, 날짜·유형·참가 선수 조건, 조건 초기화, 이전 내전 더 보기.
|
||||
- 공식 `seriesId`와 세트 순번으로 대결을 묶는다. 같은 두 팀의 재대결을 합치거나 누락된 라운드를 추정하지 않는다. 공식 경기 결과와 원본 분석 가능 상태를 구분한다.
|
||||
- 6개 지표 정렬, 최소 0/5/10/20판, 기준 충족 선수만 보기, 검색 후에도 전체 순위 유지, 모바일 선수 이름 고정과 표 내부 가로 스크롤.
|
||||
- 개인 전적 라우트, 시즌/포지션/챔피언별 집계와 세트 목록, 참가 내전 및 상세 분석 연결. URL에 조건과 로드한 페이지 수를 보존한다.
|
||||
- 상세 분석의 기존 타임라인·스코어보드·라인전·룬/빌드는 유지하고 헤더, 선수 링크, 분석 탭 URL, 복귀 경로를 연결했다. 복귀 시 스크롤과 포커스를 복원하며 중첩 경로의 이전 링크는 세션에 보관한다.
|
||||
- 실패/빈 결과/로딩/원본 없음 상태, 재시도와 복귀 동작, 키보드 탭 이동, 감소된 모션 설정을 지원한다.
|
||||
|
||||
## API 계약
|
||||
|
||||
기존 공개 읽기 API를 확장했다. 스키마 마이그레이션이나 새 서비스 의존성은 없다.
|
||||
|
||||
| 경로 (`/communities/:communityId` 기준) | 변경 |
|
||||
| --- | --- |
|
||||
| `/internal-stats/matches` | 내전명·팀명·선수명 검색, 공식 series/팀 ID와 세트 순번·분석 상태 반환. 날짜 범위와 커서 조건을 함께 유지한다. |
|
||||
| `/internal-stats/leaderboard` | `lane=TOP/JUNGLE/MIDDLE/BOTTOM/UTILITY` 검증, 해당 경기만으로 모든 지표 재집계. lane별 캐시 분리. |
|
||||
| `/internal-stats/team-insights` | `totals.matches/games/analyzedGames/players`, 단일 경기 기록의 `internalMatchId/gameNumber` 추가. |
|
||||
| `/users/:userId/internal-history` | 포지션 필터, `playerStats`, `internalMatchTitle`. 챔피언 선택 목록은 선택한 챔피언으로 축소하지 않는다. |
|
||||
| `/internal-stats/match/:matchId` | 목록과 같은 공식 시리즈 식별자 및 분석 상태 제공. 상세 응답 캐시 버전 9. |
|
||||
|
||||
날짜만 받은 경우 한국 시간 00:00:00.000~23:59:59.999로 해석하며 시즌 범위와 교집합을 사용한다. 잘못된 날짜와 역전된 범위는 400이다. 원본이 없는 세트는 공식 결과/세트 수에는 남기고 KDA 등 상세 지표에서는 제외한다. API 응답 캐시의 presentation 버전을 변경해 예전 응답과 분리했다.
|
||||
|
||||
## 검증
|
||||
|
||||
- 전적 API 8개 suite, 60개 테스트 통과. 새 테스트는 실제 Nest HTTP 라우트에 Supertest 요청을 보내 포지션별 응답과 400을 확인한다. DB/캐시 경계에는 fixture를 사용했다.
|
||||
- 웹 전체 테스트 186개 통과. 제품용 추가 테스트는 자격 판수 우선 정렬, 원본 배열 불변, 공식 재대결/순번, 검색·시즌 조건을 담은 복귀 URL을 검증한다.
|
||||
- 웹 TypeScript/변경 범위 ESLint, API TypeScript/변경 범위 ESLint 통과. API build와 웹 staging build 통과. 웹에는 기존 큰 번들 경고가 남는다.
|
||||
- 기존 개발 서버 데이터를 연결한 브라우저에서 검색 `귤`, KDA 정렬, 순위 1/45 유지, 개인 화면 이동 후 검색·정렬·선수 포커스 복귀를 확인했다.
|
||||
- 390px 모바일에서 문서 폭 375px=내용 폭 375px(스크롤바 제외), 표 내부 780px 스크롤과 sticky 선수 열 확인. 데스크톱도 문서 가로 넘침 없음.
|
||||
- 상세 API 실패 시 모바일에 복귀 링크와 재시도 버튼이 표시된다. 변경 중 HMR에서 발생한 hook 순서 경고는 최종 새로고침 뒤 추가 발생하지 않았다.
|
||||
|
||||
## 증거와 검증 한계
|
||||
|
||||
화면 자료: `C:/Users/park/.codex/visualizations/2026/11/11/01a1c9d5-e028-75a0-8b1b-f70126da1d08/internal-stats-production/`
|
||||
|
||||
- `01-desktop-ranking.jpg`: 조건과 포커스 복귀.
|
||||
- `02-mobile-ranking.jpg`: 고정 선수 열과 가로 스크롤.
|
||||
- `03-mobile-error.jpg`: 상세 요청 실패에서 복귀/재시도.
|
||||
- `04-final-desktop.jpg`: 최종 새로고침한 화면.
|
||||
|
||||
현재 개발 서버 API는 이번 변경을 배포하지 않은 상태다. 새 `totals`, `series`, `playerStats`와 포지션 집계의 실제 서버 검증은 미완료이며, 화면 자료의 `—`는 새 집계 항목이 없는 응답이다. 상세 분석 요청도 실패하여 실제 데이터 차트의 최종 시각 검증은 배포 후 필요하다. 이 항목들은 fixture HTTP 계약 테스트 통과와 구분한다.
|
||||
|
||||
사용자의 최종 지시에 따라 커밋, main 푸시, 배포를 수행하지 않았다. 배포 후에는 시즌 요약 수치, 포지션별 모든 지표, 공식 시리즈·원본 없는 세트, 개인 전적→분석→목록 복귀를 실제 데이터로 확인한다.
|
||||
|
||||
final result: local checks passed; staging integration pending deployment
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,54 @@
|
||||
import type { ApiInternalMatchCard, ApiLeaderboardRow } from "../../api/types";
|
||||
export const STATS_SORTS = {
|
||||
games: "참여 경기 수",
|
||||
winRate: "승률",
|
||||
kda: "KDA",
|
||||
avgGoldPerMin: "분당 골드",
|
||||
avgKillParticipation: "킬 관여율",
|
||||
avgCsPerMin: "분당 CS",
|
||||
};
|
||||
export type StatsSort = keyof typeof STATS_SORTS;
|
||||
export function parseStatsSort(value: string | null): StatsSort {
|
||||
return value && Object.hasOwn(STATS_SORTS, value)
|
||||
? (value as StatsSort)
|
||||
: "games";
|
||||
}
|
||||
export function sortStatsRows(
|
||||
rows: readonly ApiLeaderboardRow[],
|
||||
sort: StatsSort,
|
||||
minimum: number,
|
||||
direction: "asc" | "desc",
|
||||
) {
|
||||
return [...rows]
|
||||
.sort(
|
||||
(a, b) =>
|
||||
Number(b.games >= minimum) - Number(a.games >= minimum) ||
|
||||
(a[sort] - b[sort]) * (direction === "desc" ? -1 : 1) ||
|
||||
b.games - a.games ||
|
||||
a.summonerName.localeCompare(b.summonerName, "ko") ||
|
||||
a.userId.localeCompare(b.userId),
|
||||
)
|
||||
.map((row, i) => ({ ...row, rank: i + 1 }));
|
||||
}
|
||||
export function statsGroups(match: ApiInternalMatchCard) {
|
||||
const series = match.series ?? [];
|
||||
const known = new Set<string>(series.map((s) => s.seriesId));
|
||||
return [
|
||||
...series.map((s) => ({
|
||||
id: s.seriesId,
|
||||
series: s,
|
||||
games: match.games
|
||||
.filter((g) => g.seriesId === s.seriesId)
|
||||
.sort(
|
||||
(a, b) => (a.ordinal ?? a.gameNumber) - (b.ordinal ?? b.gameNumber),
|
||||
),
|
||||
})),
|
||||
...match.games
|
||||
.filter((g) => !g.seriesId || !known.has(g.seriesId))
|
||||
.map((g) => ({
|
||||
id: `game-${g.gameNumber}`,
|
||||
series: undefined,
|
||||
games: [g],
|
||||
})),
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useLayoutEffect, useRef } from "react";
|
||||
import { useLocation, useSearchParams } from "react-router";
|
||||
import type { ApiHistorySeason, RiotLane } from "../../api/types";
|
||||
export const STATS_LANES: RiotLane[] = [
|
||||
"TOP",
|
||||
"JUNGLE",
|
||||
"MIDDLE",
|
||||
"BOTTOM",
|
||||
"UTILITY",
|
||||
];
|
||||
export function parseStatsLane(value: string | null): RiotLane | undefined {
|
||||
return STATS_LANES.includes(value as RiotLane)
|
||||
? (value as RiotLane)
|
||||
: undefined;
|
||||
}
|
||||
export function statsRoot(cid: string) {
|
||||
return `/communities/${cid}/internal-stats`;
|
||||
}
|
||||
export function statsDate(value: string) {
|
||||
return new Intl.DateTimeFormat("ko-KR", {
|
||||
month: "numeric",
|
||||
day: "numeric",
|
||||
weekday: "short",
|
||||
timeZone: "Asia/Seoul",
|
||||
}).format(new Date(value));
|
||||
}
|
||||
export function statsDuration(seconds: number) {
|
||||
return seconds > 0
|
||||
? `${Math.floor(seconds / 60)}:${String(Math.floor(seconds % 60)).padStart(2, "0")}`
|
||||
: "시간 미확인";
|
||||
}
|
||||
export function statsPeriod(season?: ApiHistorySeason) {
|
||||
if (!season) return "시즌을 불러오는 중";
|
||||
const date = (value: string) =>
|
||||
new Intl.DateTimeFormat("ko-KR", {
|
||||
year: "numeric",
|
||||
month: "2-digit",
|
||||
day: "2-digit",
|
||||
timeZone: "Asia/Seoul",
|
||||
}).format(new Date(value));
|
||||
return season.startedAt
|
||||
? `${date(season.startedAt)} — ${season.endedAt ? date(season.endedAt) : "현재"}`
|
||||
: "전체 기록";
|
||||
}
|
||||
export function statsTarget(
|
||||
path: string,
|
||||
params: URLSearchParams,
|
||||
returnTo?: string,
|
||||
) {
|
||||
const query = new URLSearchParams();
|
||||
for (const key of ["seasonId", "lane", "championId"]) {
|
||||
const value = params.get(key);
|
||||
if (value) query.set(key, value);
|
||||
}
|
||||
if (returnTo) {
|
||||
// Keep the immediate parent in the URL. Its own return link is restored
|
||||
// from the saved visit, so repeated player/game hops cannot grow the URL.
|
||||
query.set("returnTo", visitKey(returnTo));
|
||||
}
|
||||
return `${path}${query.size ? `?${query}` : ""}`;
|
||||
}
|
||||
function visitKey(value: string) {
|
||||
const url = new URL(value, "https://internal-stats.local");
|
||||
url.searchParams.delete("returnTo");
|
||||
return url.pathname + url.search;
|
||||
}
|
||||
export function rememberStatsVisit() {
|
||||
const key = visitKey(location.pathname + location.search);
|
||||
try {
|
||||
const previous = JSON.parse(
|
||||
sessionStorage.getItem(`internal-stats:${key}`) ?? "null",
|
||||
);
|
||||
sessionStorage.setItem(
|
||||
`internal-stats:${key}`,
|
||||
JSON.stringify({
|
||||
y: scrollY,
|
||||
focus: document.activeElement?.getAttribute("data-return-id"),
|
||||
back:
|
||||
new URLSearchParams(location.search).get("returnTo") ??
|
||||
previous?.back,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
/* Storage can be unavailable. */
|
||||
}
|
||||
}
|
||||
export function useStatsRestoration(ready: boolean) {
|
||||
const location = useLocation();
|
||||
const previousPath = useRef<string | null>(null);
|
||||
useLayoutEffect(() => {
|
||||
if (!ready) return;
|
||||
const changedPage = previousPath.current !== location.pathname;
|
||||
previousPath.current = location.pathname;
|
||||
let saved: { y: number; focus?: string } | null = null;
|
||||
try {
|
||||
saved = JSON.parse(
|
||||
sessionStorage.getItem(
|
||||
`internal-stats:${visitKey(location.pathname + location.search)}`,
|
||||
) ?? "null",
|
||||
);
|
||||
} catch {
|
||||
/* Ignore corrupt storage. */
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (saved && Number.isFinite(saved.y)) {
|
||||
window.scrollTo({ top: saved.y, behavior: "instant" });
|
||||
if (saved.focus)
|
||||
document
|
||||
.querySelector<HTMLElement>(
|
||||
`[data-return-id="${CSS.escape(saved.focus)}"]`,
|
||||
)
|
||||
?.focus({ preventScroll: true });
|
||||
} else if (changedPage) window.scrollTo({ top: 0, behavior: "instant" });
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [location.pathname, location.search, ready]);
|
||||
}
|
||||
export function useStatsBack(fallback: string) {
|
||||
const location = useLocation();
|
||||
const [params] = useSearchParams();
|
||||
let savedBack: unknown;
|
||||
try {
|
||||
savedBack = JSON.parse(
|
||||
sessionStorage.getItem(
|
||||
`internal-stats:${visitKey(location.pathname + location.search)}`,
|
||||
) ?? "null",
|
||||
)?.back;
|
||||
} catch {
|
||||
/* A direct visit can use the fallback without storage. */
|
||||
}
|
||||
const back = params.get("returnTo") ?? location.state?.backTo ?? savedBack;
|
||||
return typeof back === "string" &&
|
||||
/^\/(communities|users|match)\//.test(back) &&
|
||||
!back.includes("\\")
|
||||
? back
|
||||
: fallback;
|
||||
}
|
||||
@@ -3,7 +3,9 @@ import { useSyncExternalStore } from 'react';
|
||||
const AUTH_USER_ID_STORAGE_KEY = 'lolympus.authUserId';
|
||||
const THEME_STORAGE_KEY = 'lolympus.theme';
|
||||
const AUTH_USER_CHANGED_EVENT = 'lolympus:auth-user-changed';
|
||||
const AUCTION_ROLE_CHANGED_EVENT = 'lolympus:auction-role-changed';
|
||||
const THEME_CHANGED_EVENT = 'lolympus:theme-changed';
|
||||
const auctionRoleFallback = new Map<string, number | null>();
|
||||
|
||||
export type AppTheme = 'light' | 'dark';
|
||||
|
||||
@@ -55,6 +57,46 @@ export function setAuthUserId(userId: string | null) {
|
||||
dispatchWindowEvent(AUTH_USER_CHANGED_EVENT);
|
||||
}
|
||||
|
||||
function getAuctionCaptainTeamIndex(matchId: string | undefined): number | null | undefined {
|
||||
if (!matchId || typeof window === 'undefined') return undefined;
|
||||
if (auctionRoleFallback.has(matchId)) return auctionRoleFallback.get(matchId);
|
||||
|
||||
try {
|
||||
const value = window.localStorage.getItem(`lolympus.auctionRole.${matchId}`);
|
||||
if (value === null) return undefined;
|
||||
if (value === 'spectator') return null;
|
||||
const teamIndex = Number(value);
|
||||
return Number.isInteger(teamIndex) && teamIndex > 0 ? teamIndex : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function setAuctionCaptainTeamIndex(matchId: string, teamIndex: number | null) {
|
||||
if (typeof window === 'undefined') return;
|
||||
const selectedTeamIndex = teamIndex !== null && Number.isInteger(teamIndex) && teamIndex > 0
|
||||
? teamIndex
|
||||
: null;
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
`lolympus.auctionRole.${matchId}`,
|
||||
selectedTeamIndex === null ? 'spectator' : String(selectedTeamIndex),
|
||||
);
|
||||
auctionRoleFallback.delete(matchId);
|
||||
} catch {
|
||||
auctionRoleFallback.set(matchId, selectedTeamIndex);
|
||||
}
|
||||
dispatchWindowEvent(AUCTION_ROLE_CHANGED_EVENT);
|
||||
}
|
||||
|
||||
export function useAuctionCaptainTeamIndex(matchId: string | undefined) {
|
||||
return useSyncExternalStore<number | null | undefined>(
|
||||
(callback) => subscribeToWindowChanges(AUCTION_ROLE_CHANGED_EVENT, callback),
|
||||
() => getAuctionCaptainTeamIndex(matchId),
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
function normalizeTheme(value: string | null | undefined): AppTheme {
|
||||
return value === 'dark' ? 'dark' : 'light';
|
||||
}
|
||||
|
||||
@@ -0,0 +1,240 @@
|
||||
import { useEffect, useLayoutEffect, useRef, useState, type ComponentProps, type ReactNode } from 'react';
|
||||
import { Link, useLocation, useSearchParams } from 'react-router';
|
||||
import { ArrowDown, ArrowDownUp, ArrowLeft, ArrowRight, CalendarDays, Check, ChevronRight, Clock3, Copy, Filter, Info, List, LoaderCircle, Moon, Search, ShieldAlert, Sun, Trophy, Users, X } from 'lucide-react';
|
||||
import { CartesianGrid, Legend, Line, LineChart, ResponsiveContainer, Tooltip, XAxis, YAxis } from 'recharts';
|
||||
import { Btn, Chip } from '../../ui';
|
||||
import { setTheme, useTheme } from '../../config';
|
||||
import { champions, championImage, events, games, lanes, laneNames, ORIGINAL_PATH, playerById, PREVIEW_PATH, seasons, type Event, type Game, type Lane, type Participant, type Series } from './data';
|
||||
import { aggregateRows, filterEvents, formatDate, formatDuration, playerGames, seasonMetrics, sortLabels, teamName, type PlayerRow, type SortKey } from './model';
|
||||
|
||||
type Changes = Record<string, string | null>;
|
||||
const visits = new Map<string, { y: number; focus: string | null }>();
|
||||
function visitKey(pathname: string, search: string) {
|
||||
const query = new URLSearchParams(search);
|
||||
query.delete('returnTo');
|
||||
return `${pathname}?${query.toString()}`;
|
||||
}
|
||||
function rememberVisit() {
|
||||
const focus = document.activeElement?.getAttribute('data-return-id') ?? null;
|
||||
const key = visitKey(location.pathname, location.search);
|
||||
const value = { y: window.scrollY, focus };
|
||||
visits.set(key, value);
|
||||
try { sessionStorage.setItem(`stats-preview:${key}`, JSON.stringify(value)); } catch { /* Memory restoration still works. */ }
|
||||
}
|
||||
function PreviewLink(props: ComponentProps<typeof Link>) {
|
||||
return <Link {...props} onClick={event => { rememberVisit(); props.onClick?.(event); }} />;
|
||||
}
|
||||
function Champion({ id, size = 'normal' }: { id: number; size?: 'small' | 'normal' | 'large' }) {
|
||||
const champion = champions[id];
|
||||
return <img className={`is-champion is-champion-${size}`} src={championImage(champion.key)} alt={champion.name} title={champion.name} loading="lazy" />;
|
||||
}
|
||||
function Feedback({ type, title, children, action }: { type: 'empty' | 'error' | 'loading'; title: string; children?: ReactNode; action?: ReactNode }) {
|
||||
const Icon = type === 'loading' ? LoaderCircle : type === 'error' ? ShieldAlert : Search;
|
||||
return <section className={`is-feedback is-feedback-${type}`} role={type === 'error' ? 'alert' : 'status'} aria-live="polite"><Icon size={26} aria-hidden="true" /><h2>{title}</h2>{children && <p>{children}</p>}{action && <div className="is-feedback-actions">{action}</div>}</section>;
|
||||
}
|
||||
|
||||
export default function Preview() {
|
||||
const [params, setParams] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const theme = useTheme();
|
||||
const [copied, setCopied] = useState(false);
|
||||
const [copyError, setCopyError] = useState(false);
|
||||
const [retrying, setRetrying] = useState(false);
|
||||
const timer = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||
const view = params.get('view') === 'players' ? 'players' : 'matches';
|
||||
const season = seasons.some(s => s.id === params.get('season')) || params.get('season') === 'all' ? params.get('season')! : '2026-2';
|
||||
const lane = lanes.includes(params.get('lane') as Lane) ? params.get('lane') as Lane : 'all';
|
||||
const sort = Object.hasOwn(sortLabels, params.get('sort') ?? '') ? params.get('sort') as SortKey : 'games';
|
||||
const direction = params.get('dir') === 'asc' ? 'asc' : 'desc';
|
||||
const minimum = ['0', '5', '10', '20'].includes(params.get('min') ?? '') ? Number(params.get('min')) : 5;
|
||||
const detail = params.get('detail');
|
||||
const state = params.get('state');
|
||||
const matchQuery = params.get('matchQ') ?? '';
|
||||
const playerQuery = params.get('playerQ') ?? '';
|
||||
const format = ['pair', 'tournament'].includes(params.get('format') ?? '') ? params.get('format')! : 'all';
|
||||
const from = params.get('from') ?? '', to = params.get('to') ?? '';
|
||||
const selectedPlayer = params.get('player') ?? '';
|
||||
const selected = playerById.get(selectedPlayer);
|
||||
const shown = Math.max(4, Math.min(100, Number(params.get('shown')) || 4));
|
||||
const rawReturn = params.get('returnTo');
|
||||
const listParams = new URLSearchParams(params);
|
||||
['detail', 'event', 'game', 'profile', 'returnTo', 'state'].forEach(key => listParams.delete(key));
|
||||
const listHref = `${PREVIEW_PATH}?${listParams.toString()}`;
|
||||
const backHref = rawReturn?.startsWith(`${PREVIEW_PATH}?`) ? rawReturn : listHref;
|
||||
const current = visitKey(location.pathname, location.search);
|
||||
const metrics = seasonMetrics(season);
|
||||
const seasonLabel = season === 'all' ? '전체 시즌' : seasons.find(s => s.id === season)!.name;
|
||||
const period = season === 'all' ? '2026.05.01 — 06.30' : season === '2026-2' ? '2026.06.01 — 06.30' : '2026.05.01 — 05.31';
|
||||
const invalidDates = Boolean(from && to && from > to);
|
||||
const filteredEvents = invalidDates ? [] : filterEvents({ season, query: matchQuery, format, from, to, player: selectedPlayer });
|
||||
const visibleEvents = filteredEvents.slice(0, shown);
|
||||
const rankedRows = aggregateRows(season, lane, minimum, sort, direction);
|
||||
const query = playerQuery.trim().toLocaleLowerCase('ko-KR');
|
||||
const visibleRows = rankedRows.filter(row => row.name.toLocaleLowerCase('ko-KR').includes(query) && (params.get('qualified') !== '1' || row.games >= minimum));
|
||||
const event = events.find(e => e.id === params.get('event'));
|
||||
const game = games.find(g => g.id === params.get('game'));
|
||||
const profile = playerById.get(params.get('profile') ?? '');
|
||||
|
||||
function update(changes: Changes, replace = false) {
|
||||
const next = new URLSearchParams(params);
|
||||
for (const [key, value] of Object.entries(changes)) {
|
||||
if (value === null || value === '') next.delete(key); else next.set(key, value);
|
||||
}
|
||||
setParams(next, { replace, preventScrollReset: true });
|
||||
}
|
||||
function target(changes: Changes, asDetail = true) {
|
||||
const next = new URLSearchParams(params);
|
||||
['detail', 'event', 'game', 'profile', 'state'].forEach(k => next.delete(k));
|
||||
Object.entries(changes).forEach(([key, value]) => value === null ? next.delete(key) : next.set(key, value));
|
||||
if (asDetail) next.set('returnTo', current); else next.delete('returnTo');
|
||||
return `${PREVIEW_PATH}?${next.toString()}`;
|
||||
}
|
||||
const eventHref = (id: string) => target({ detail: 'event', event: id });
|
||||
const gameHref = (id: string) => target({ detail: 'game', game: id });
|
||||
const profileHref = (id: string) => target({ detail: 'player', profile: id });
|
||||
const participationHref = (id: string) => target({ view: 'matches', player: id, shown: null }, false);
|
||||
function resetFilters() {
|
||||
update(view === 'matches' ? { matchQ: null, format: null, from: null, to: null, player: null, shown: null } : { playerQ: null, lane: null, min: null, qualified: null, sort: null, dir: null });
|
||||
}
|
||||
function retry() {
|
||||
setRetrying(true);
|
||||
timer.current = setTimeout(() => { setRetrying(false); update({ state: null }, true); }, 700);
|
||||
}
|
||||
async function copyLink() {
|
||||
try { await navigator.clipboard.writeText(window.location.href); setCopied(true); setCopyError(false); }
|
||||
catch { setCopyError(true); }
|
||||
}
|
||||
useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []);
|
||||
useEffect(() => {
|
||||
if (!copied && !copyError) return;
|
||||
const timeout = setTimeout(() => { setCopied(false); setCopyError(false); }, 3500);
|
||||
return () => clearTimeout(timeout);
|
||||
}, [copied, copyError]);
|
||||
useLayoutEffect(() => {
|
||||
const key = visitKey(location.pathname, location.search);
|
||||
let saved = visits.get(key);
|
||||
if (!saved) try { saved = JSON.parse(sessionStorage.getItem(`stats-preview:${key}`) ?? 'null'); } catch { /* Ignore obsolete preview state. */ }
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (saved) {
|
||||
window.scrollTo({ top: saved.y, behavior: 'instant' });
|
||||
if (saved.focus) document.querySelector<HTMLElement>(`[data-return-id="${CSS.escape(saved.focus)}"]`)?.focus({ preventScroll: true });
|
||||
} else if (detail) {
|
||||
window.scrollTo({ top: 0, behavior: 'instant' });
|
||||
document.getElementById('stats-detail-title')?.focus({ preventScroll: true });
|
||||
}
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [location.key, location.pathname, location.search, detail]);
|
||||
|
||||
const activeFilters: Array<{ label: string; clear: Changes }> = view === 'matches' ? [
|
||||
...(matchQuery ? [{ label: `검색: ${matchQuery}`, clear: { matchQ: null } }] : []),
|
||||
...(format !== 'all' ? [{ label: format === 'pair' ? '두 팀 내전' : '대회', clear: { format: null } }] : []),
|
||||
...(from || to ? [{ label: `${from || '처음'} ~ ${to || '마지막'}`, clear: { from: null, to: null } }] : []),
|
||||
...(selectedPlayer ? [{ label: `${selected?.name ?? '선수'} 참가 내전`, clear: { player: null } }] : []),
|
||||
] : [
|
||||
...(playerQuery ? [{ label: `검색: ${playerQuery}`, clear: { playerQ: null } }] : []),
|
||||
...(lane !== 'all' ? [{ label: `${laneNames[lane]}에서 플레이한 기록`, clear: { lane: null } }] : []),
|
||||
...(params.get('qualified') === '1' ? [{ label: `${minimum}판 이상만`, clear: { qualified: null } }] : []),
|
||||
];
|
||||
const secondaryControls = <div className="is-page-actions"><button className="is-icon-button" onClick={copyLink} aria-label="현재 전적 링크 복사">{copied ? <Check size={17} /> : <Copy size={17} />}</button><label className="is-season-select"><span>집계 시즌</span><select value={season} onChange={e => update({ season: e.target.value, shown: null, returnTo: null, ...(detail !== 'player' ? { detail: null, event: null, game: null } : {}) })}>{seasons.map(s => <option value={s.id} key={s.id}>{s.name}</option>)}<option value="all">전체 시즌</option></select></label></div>;
|
||||
|
||||
return <div className="internal-stats-preview">
|
||||
<a className="is-skip-link" href="#stats-main">전적 본문으로 건너뛰기</a>
|
||||
<div className="is-preview-notice"><span><span className="is-preview-dot" /> 인터랙티브 시안 <span className="is-notice-separator">/</span> 예시 데이터</span><a href={ORIGINAL_PATH}>현재 페이지와 비교 <ArrowRight size={13} /></a></div>
|
||||
<header className="is-site-header"><a className="is-brand" href="/">LOLYMPUS<span>TOURNAMENT</span></a><nav aria-label="주 메뉴"><a href="/">홈</a><a href="/inhouse">내전</a><a href="/tournaments">멸망전</a><PreviewLink to={PREVIEW_PATH} aria-current="page">전적</PreviewLink></nav><button className="is-icon-button" aria-label={theme === 'dark' ? '라이트 테마로 전환' : '다크 테마로 전환'} onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}>{theme === 'dark' ? <Sun size={19} /> : <Moon size={19} />}</button></header>
|
||||
<main id="stats-main" className="is-page">
|
||||
{!detail ? <>
|
||||
<header className="is-page-heading"><div><p className="is-eyebrow">LOLYMPUS COMMUNITY</p><h1>내전 전적</h1><p className="is-muted">함께한 경기와 선수들의 기록을 만나보세요.</p></div>{secondaryControls}</header>
|
||||
<SeasonSummary metrics={metrics} label={seasonLabel} period={period} profileHref={id => target({ detail: 'player', profile: id, lane: null })} gameHref={gameHref} />
|
||||
<div className="is-workspace">
|
||||
<div className="is-view-tabs" role="tablist" aria-label="전적 보기">
|
||||
{(['matches', 'players'] as const).map((v, index) => <button key={v} id={`tab-${v}`} role="tab" aria-selected={view === v} aria-controls="stats-view-panel" tabIndex={view === v ? 0 : -1} onClick={() => update({ view: v })} onKeyDown={e => { if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) { e.preventDefault(); const next = e.key === 'Home' ? 'matches' : e.key === 'End' ? 'players' : index === 0 ? 'players' : 'matches'; update({ view: next }); document.getElementById(`tab-${next}`)?.focus(); } }}>{v === 'matches' ? <List size={17} /> : <Users size={17} />}{v === 'matches' ? '최근 내전' : '선수 전적·순위'}<span>{v === 'matches' ? metrics.events : metrics.players}</span></button>)}
|
||||
<span className="is-tabs-caption">{seasonLabel} <span>·</span> {period}</span>
|
||||
</div>
|
||||
<section id="stats-view-panel" role="tabpanel" aria-labelledby={`tab-${view}`}>
|
||||
<div className="is-filter-bar">
|
||||
<label className="is-search"><Search size={18} aria-hidden="true" /><input type="search" maxLength={100} aria-label={view === 'matches' ? '내전·팀·선수 검색' : '선수 검색'} placeholder={view === 'matches' ? '내전명, 팀명, 선수 이름 검색' : '선수 이름 검색'} value={view === 'matches' ? matchQuery : playerQuery} onChange={e => update({ [view === 'matches' ? 'matchQ' : 'playerQ']: e.target.value, shown: null }, true)} />{(view === 'matches' ? matchQuery : playerQuery) && <button aria-label="검색어 지우기" onClick={() => update({ [view === 'matches' ? 'matchQ' : 'playerQ']: null }, true)}><X size={16} /></button>}</label>
|
||||
{view === 'matches' ? <>
|
||||
<div className="is-type-filters" role="group" aria-label="내전 유형">{[['all', '전체'], ['pair', '두 팀 내전'], ['tournament', '대회']].map(([value, label]) => <Chip key={value} selected={format === value} onClick={() => update({ format: value === 'all' ? null : value, shown: null })}>{label}</Chip>)}</div>
|
||||
<div className="is-date-range"><CalendarDays size={16} aria-hidden="true" /><label><span className="sr-only">시작일</span><input type="date" aria-label="시작일" value={from} onInput={e => update({ from: e.currentTarget.value, shown: null })} /></label><span>—</span><label><span className="sr-only">종료일</span><input type="date" aria-label="종료일" value={to} onInput={e => update({ to: e.currentTarget.value, shown: null })} /></label></div>
|
||||
</> : <><label className="is-select"><Filter size={15} /><span className="sr-only">플레이 포지션</span><select aria-label="플레이 포지션" value={lane} onChange={e => update({ lane: e.target.value })}><option value="all">전체 포지션</option>{lanes.map(l => <option value={l} key={l}>{laneNames[l]}</option>)}</select></label><label className="is-select"><span>순위 기준</span><select aria-label="최소 판수" value={minimum} onChange={e => update({ min: e.target.value })}>{[0, 5, 10, 20].map(n => <option key={n} value={n}>{n === 0 ? '모든 선수' : `최소 ${n}판`}</option>)}</select></label><label className="is-sort-select"><ArrowDownUp size={16} /><select aria-label="순위 정렬" value={sort} onChange={e => update({ sort: e.target.value, dir: null })}>{Object.entries(sortLabels).map(([key, value]) => <option value={key} key={key}>{value} 순</option>)}</select></label></>}
|
||||
</div>
|
||||
{activeFilters.length > 0 && <div className="is-active-filters"><span>적용 조건</span>{activeFilters.map(filter => <button key={filter.label} onClick={() => update({ ...filter.clear, shown: null })} aria-label={`${filter.label} 해제`}>{filter.label}<X size={13} /></button>)}<button className="is-reset" onClick={resetFilters}>전체 초기화</button></div>}
|
||||
{view === 'matches' && invalidDates && <p className="is-inline-error" role="alert">종료일을 시작일과 같거나 이후 날짜로 선택해 주세요.</p>}
|
||||
{(state === 'error' || state === 'loading' || retrying) ? <Feedback type={retrying || state === 'loading' ? 'loading' : 'error'} title={retrying || state === 'loading' ? '전적을 불러오는 중입니다' : '전적을 불러오지 못했습니다'} action={<><Btn onClick={retry} disabled={retrying}>다시 시도</Btn><Btn variant="ghost" onClick={() => update({ state: null })}>목록으로 돌아가기</Btn></>}>선택한 시즌과 검색 조건은 유지됩니다.</Feedback> : view === 'matches' ? <>
|
||||
<div className="is-result-heading"><h2>경기 기록 <span>{filteredEvents.length}회</span></h2><p role="status">{visibleEvents.length}개 표시{filteredEvents.length > shown && ` / 검색 결과 ${filteredEvents.length}개`}</p></div>
|
||||
{visibleEvents.length ? <div className="is-events-layout"><EventJumpNav events={visibleEvents} /><div className="is-events-list">{visibleEvents.map(e => <EventSection key={e.id} event={e} eventHref={eventHref} gameHref={gameHref} />)}{filteredEvents.length > shown && <button className="is-load-more" onClick={() => update({ shown: String(shown + 2) })}>이전 내전 2개 더 보기 <ArrowDown size={16} /><span>{filteredEvents.length - shown}개 남음</span></button>}</div></div> : <Feedback type="empty" title={invalidDates ? '조회 기간을 확인해 주세요' : '조건에 맞는 내전이 없습니다'} action={<Btn onClick={resetFilters}>검색 조건 초기화</Btn>}>날짜나 검색어를 바꾸면 다른 내전을 찾을 수 있습니다.</Feedback>}
|
||||
</> : <>
|
||||
<div className="is-result-heading"><div><h2>{sortLabels[sort]} 순 <span>{visibleRows.length}명</span></h2><p>{lane === 'all' ? '전체 포지션' : `${laneNames[lane]} 플레이만 집계`} · {minimum > 0 ? `${minimum}판 미만은 기준 미달로 뒤에 표시` : '판수 제한 없음'}</p></div><label className="is-checkbox"><input type="checkbox" checked={params.get('qualified') === '1'} onChange={e => update({ qualified: e.target.checked ? '1' : null })} />기준 충족 선수만</label></div>
|
||||
{visibleRows.length ? <LeaderboardTable rows={visibleRows} minimum={minimum} lane={lane} sort={sort} direction={direction} onSort={key => update({ sort: key, dir: sort === key && direction === 'desc' ? 'asc' : 'desc' })} profileHref={profileHref} participationHref={participationHref} /> : <Feedback type="empty" title="조건에 맞는 선수가 없습니다" action={<Btn onClick={resetFilters}>검색 조건 초기화</Btn>}>검색어, 포지션 또는 최소 판수를 바꿔 보세요.</Feedback>}
|
||||
</>}
|
||||
</section>
|
||||
</div>
|
||||
</> : <>
|
||||
<PreviewLink className="is-back-link" to={backHref}><ArrowLeft size={16} />{rawReturn?.includes('detail=') ? '이전 기록으로' : '내전 전적으로 돌아가기'}</PreviewLink>
|
||||
<header className="is-page-heading is-detail-heading"><div><p className="is-eyebrow">{seasonLabel} · {period}</p><h1 id="stats-detail-title" tabIndex={-1}>{detail === 'event' ? event?.name ?? '내전 기록' : detail === 'game' ? '세트 상세 분석' : profile?.name ?? '선수 전적'}</h1><p className="is-muted">{detail === 'player' ? '선택한 시즌의 개인 기록과 참가 경기를 확인합니다.' : '공식 경기 결과와 수집된 분석 기록을 함께 확인합니다.'}</p></div>{secondaryControls}</header>
|
||||
{(state === 'error' || state === 'loading' || retrying) ? <Feedback type={retrying || state === 'loading' ? 'loading' : 'error'} title={retrying || state === 'loading' ? '기록을 불러오는 중입니다' : '기록을 불러오지 못했습니다'} action={<><Btn onClick={retry} disabled={retrying}>다시 시도</Btn><Btn to={backHref} variant="ghost">이전 기록으로</Btn></>}>경기 제목과 선택한 조건을 유지했습니다. 다시 시도하거나 이전 화면으로 돌아갈 수 있습니다.</Feedback> : detail === 'event' && event ? <><EventOverview event={event} /><div className="is-detail-series">{event.series.map(series => <SeriesResultGroup key={series.id} series={series} event={event} gameHref={gameHref} />)}</div></> : detail === 'game' && game ? <GameAnalysis game={game} profileHref={profileHref} eventHref={eventHref} /> : detail === 'player' && profile ? <PlayerDetail playerId={profile.id} season={season} lane={lane} onLane={value => update({ lane: value })} gameHref={gameHref} participationHref={participationHref} /> : <Feedback type="empty" title="요청한 기록을 찾을 수 없습니다" action={<Btn to={listHref}>내전 전적으로 돌아가기</Btn>}>기록의 링크를 확인하거나 목록에서 다시 선택해 주세요.</Feedback>}
|
||||
</>}
|
||||
<div className="is-announcement" role="status">{copyError ? '링크를 복사하지 못했습니다. 주소 표시줄의 주소를 복사해 주세요.' : copied ? '현재 검색 조건이 포함된 링크를 복사했습니다.' : ''}</div>
|
||||
<footer className="is-page-footer"><span>LOLYMPUS <span>·</span> 함께하는 모든 게임의 기록</span><span>예시 데이터로 구성한 디자인 시안</span></footer>
|
||||
<aside className="is-preview-tools" aria-label="시안 상태 확인"><span>시안 상태 확인</span><button onClick={() => update({ state: null })} aria-pressed={!state}>정상</button><button onClick={() => update({ state: 'loading' })} aria-pressed={state === 'loading'}>로딩</button><button onClick={() => update({ state: 'error' })} aria-pressed={state === 'error'}>조회 오류</button></aside>
|
||||
</main>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function SeasonSummary({ metrics: m, label, period, profileHref, gameHref }: { metrics: ReturnType<typeof seasonMetrics>; label: string; period: string; profileHref: (id: string) => string; gameHref: (id: string) => string }) {
|
||||
const records = [
|
||||
{ title: '평균 KDA', value: m.topKda?.kda.toFixed(2), suffix: '', name: m.topKda?.name, href: m.topKda ? profileHref(m.topKda.id) : '', scope: '시즌 최고 · 최소 5판' },
|
||||
{ title: '누적 킬', value: m.kills?.kills.toLocaleString(), suffix: '킬', name: m.kills?.player.name, href: m.kills ? profileHref(m.kills.player.id) : '', scope: '시즌 누적' },
|
||||
{ title: '분당 골드', value: m.bestGpm?.gpm.toFixed(1), suffix: '', name: m.bestGpm ? playerById.get(m.bestGpm.p.playerId)?.name : '', href: m.bestGpm ? gameHref(m.bestGpm.game.id) : '', scope: '단일 경기 최고' },
|
||||
{ title: '평균 킬 관여', value: m.topKp?.kp.toFixed(1), suffix: '%', name: m.topKp?.name, href: m.topKp ? profileHref(m.topKp.id) : '', scope: '시즌 최고 · 최소 5판' },
|
||||
{ title: '평균 분당 CS', value: m.topCs?.cspm.toFixed(1), suffix: '', name: m.topCs?.name, href: m.topCs ? profileHref(m.topCs.id) : '', scope: '시즌 최고 · 최소 5판' },
|
||||
];
|
||||
return <section className="is-season-summary" aria-label="커뮤니티 전체 시즌 요약"><div className="is-summary-topline"><span><span className="is-current-dot" />{label} <span className="is-muted">시즌 요약</span></span><span className="is-muted">커뮤니티 전체 · {period}</span></div><div className="is-summary-metrics"><div><span>진행한 내전</span><strong>{m.events}<small>회</small></strong></div><div><span>확정 세트</span><strong>{m.sets}<small>판</small></strong></div><div><span>참가 선수</span><strong>{m.players}<small>명</small></strong></div><div className="is-side-rate"><span>진영 승률 <small>{m.sets}세트 기준</small></span><div><strong className="is-blue">{Math.round(m.blue)}<small>%</small></strong><span>BLUE / RED</span><strong className="is-red">{100 - Math.round(m.blue)}<small>%</small></strong></div><div className="is-side-track" aria-hidden="true"><span style={{ width: `${m.blue}%` }} /></div></div></div><div className="is-records-heading"><Trophy size={14} /><h2>시즌 기록</h2><span>분석 가능한 {m.ready}세트 기준 · 검색 조건과 별도 집계</span></div><div className="is-records">{records.map(record => <div className="is-record" key={record.title}><p>{record.title}<span>{record.scope}</span></p><div><strong>{record.value ?? '—'}<small>{record.suffix}</small></strong>{record.href ? <PreviewLink to={record.href} aria-label={`${record.title} ${record.name}의 ${record.scope === '단일 경기 최고' ? '근거 경기' : '시즌 전적'} 보기`}>{record.name}<ChevronRight size={13} /></PreviewLink> : <span>기록 없음</span>}</div></div>)}</div></section>;
|
||||
}
|
||||
|
||||
function EventJumpNav({ events: items }: { events: Event[] }) {
|
||||
return <nav className="is-event-jump" aria-label="내전 바로가기"><div className="is-jump-desktop"><p><CalendarDays size={15} /> 내전 바로가기</p>{items.map(event => <a href={`#event-${event.id}`} key={event.id}><span>{formatDate(event.date)}</span><strong>{event.name}</strong><small>{event.formatLabel}</small></a>)}</div><label className="is-jump-mobile"><CalendarDays size={16} /><span>내전 이동</span><select aria-label="내전 바로가기" defaultValue="" onChange={e => { if (e.target.value) { document.getElementById(`event-${e.target.value}`)?.scrollIntoView({ behavior: 'smooth', block: 'start' }); } }}><option value="" disabled>날짜로 바로가기</option>{items.map(e => <option key={e.id} value={e.id}>{formatDate(e.date)} · {e.name}</option>)}</select></label></nav>;
|
||||
}
|
||||
function EventOverview({ event }: { event: Event }) {
|
||||
const sets = event.series.flatMap(s => s.games), ready = sets.filter(g => g.evidence === 'ready').length;
|
||||
const single = event.series.length === 1 ? event.series[0] : null;
|
||||
return <div className="is-event-overview"><div className="is-event-meta"><span><CalendarDays size={14} />{formatDate(event.date)} {event.time}</span><span><Users size={14} />{event.teamIds.length}팀 · {event.teamIds.length * 5}명</span><span>{sets.length}세트 결과</span><span className="is-analysis-count">{ready}세트 분석 가능</span></div>{event.champion ? <span className="is-champion-label"><Trophy size={15} />우승 <strong>{teamName(event.champion)}</strong></span> : single && <span className="is-series-score">{teamName(single.a)} <strong>{single.scoreA} : {single.scoreB}</strong> {teamName(single.b)}</span>}</div>;
|
||||
}
|
||||
function EventSection({ event, eventHref, gameHref }: { event: Event; eventHref: (id: string) => string; gameHref: (id: string) => string }) {
|
||||
return <article className="is-event-section" id={`event-${event.id}`}><header><div><div className="is-event-kicker"><span>{event.formatLabel}</span><span>{event.series.length}개 시리즈</span></div><h3><PreviewLink to={eventHref(event.id)} data-return-id={`event-link-${event.id}`}>{event.name}<ChevronRight size={18} /></PreviewLink></h3></div><PreviewLink className="is-text-link is-event-detail-link" to={eventHref(event.id)} data-return-id={`event-detail-${event.id}`}>전체 기록<ArrowRight size={15} /></PreviewLink></header><EventOverview event={event} /><div className="is-series-grid">{event.series.map(series => <SeriesResultGroup key={series.id} series={series} event={event} gameHref={gameHref} />)}</div></article>;
|
||||
}
|
||||
function SeriesResultGroup({ series, event, gameHref }: { series: Series; event: Event; gameHref: (id: string) => string }) {
|
||||
return <section className="is-series-group" aria-label={`${series.label} ${teamName(series.a)} 대 ${teamName(series.b)}`}><header><span>{series.label}</span><span>{series.games.length}세트</span></header><div className="is-matchup"><strong className={series.winner === series.a ? 'is-winner' : ''}>{teamName(series.a)}</strong><span className="is-score"><b className={series.scoreA > series.scoreB ? 'is-winner' : ''}>{series.scoreA}</b><i>:</i><b className={series.scoreB > series.scoreA ? 'is-winner' : ''}>{series.scoreB}</b></span><strong className={series.winner === series.b ? 'is-winner' : ''}>{teamName(series.b)}</strong></div><ul>{series.games.map(game => <li key={game.id}><span className="is-set-number">{game.ordinal}세트<small>전체 #{game.number}</small></span><span className="is-set-winner"><span className="is-win-badge">승</span>{teamName(game.winner)}</span><span className="is-duration"><Clock3 size={12} />{formatDuration(game.duration)}</span><PreviewLink className={`is-analysis-link ${game.evidence !== 'ready' ? 'is-unavailable' : ''}`} to={gameHref(game.id)} data-return-id={`game-link-${game.id}`} aria-label={`${formatDate(event.date)} ${series.label} ${game.ordinal}세트 ${game.evidence === 'ready' ? '상세 분석' : '기록 상태 확인'}`}>{game.evidence === 'ready' ? '분석' : game.evidence === 'missing' ? '원본 없음' : '수집 중'}{game.evidence === 'ready' ? <ChevronRight size={13} /> : <Info size={12} />}</PreviewLink></li>)}</ul></section>;
|
||||
}
|
||||
|
||||
function LeaderboardTable({ rows, minimum, lane, sort, direction, onSort, profileHref, participationHref }: { rows: PlayerRow[]; minimum: number; lane: Lane | 'all'; sort: SortKey; direction: 'asc' | 'desc'; onSort: (key: SortKey) => void; profileHref: (id: string) => string; participationHref: (id: string) => string }) {
|
||||
const firstUnder = rows.findIndex(row => row.games < minimum);
|
||||
const metric = (key: SortKey, label: string) => <th scope="col" aria-sort={sort === key ? direction === 'desc' ? 'descending' : 'ascending' : 'none'}><button className={sort === key ? 'is-sorted' : ''} onClick={() => onSort(key)}>{label}{sort === key ? <ArrowDown size={13} className={direction === 'asc' ? 'is-arrow-up' : ''} /> : <ArrowDownUp size={12} />}</button></th>;
|
||||
return <><div className="is-table-hint"><ArrowRight size={14} />옆으로 이동하면 모든 지표를 볼 수 있어요. 선수 이름은 고정됩니다.</div><div className="is-table-scroll" role="region" aria-label="선수 순위표, 좌우 방향키로 지표 이동" tabIndex={0}><table className="is-leaderboard"><caption className="sr-only">{lane === 'all' ? '전체 포지션' : laneNames[lane]} 선수 순위. {sortLabels[sort]} {direction === 'desc' ? '높은' : '낮은'} 순. 최소 {minimum}판 기준.</caption><colgroup><col className="is-col-rank" /><col className="is-col-player" /><col className="is-col-win" /><col className="is-col-games" /><col className="is-col-kda" /><col className="is-col-champions" /><col /><col /><col /></colgroup><thead><tr><th scope="col" className="is-sticky-rank">순위</th><th scope="col" className="is-sticky-player">선수</th>{metric('winRate', '승률')}{metric('games', '판수')}{metric('kda', 'KDA')}<th scope="col">주 챔피언</th>{metric('gpm', 'GPM')}{metric('kp', '킬 관여')}{metric('cspm', 'CS/분')}</tr></thead><tbody>{rows.map((row, index) => <tr key={row.id} className={`${row.games < minimum ? 'is-under-qualified' : ''} ${index === firstUnder ? 'is-threshold-first' : ''}`}><td className="is-sticky-rank"><span className="is-rank-number">{row.rank}</span></td><th scope="row" className="is-sticky-player"><div className="is-player-identity"><Champion id={row.champions[0].id} /><div><PreviewLink to={profileHref(row.id)} data-return-id={`player-link-${row.id}`}>{row.name}</PreviewLink><small>{lane === 'all' ? laneNames[row.lane] : laneNames[lane]}<span>·</span><PreviewLink to={participationHref(row.id)}>참가 내전</PreviewLink></small>{row.games < minimum && <span className="is-sample-badge">기준 미달</span>}</div></div></th><td><strong className={row.winRate >= 50 ? 'is-blue' : ''}>{Math.round(row.winRate)}<small>%</small></strong><div className="is-win-track" aria-hidden="true"><span style={{ width: `${row.winRate}%` }} /></div></td><td><strong>{row.games}</strong><small className="is-win-loss">{row.wins}승 {row.losses}패</small></td><td><strong className={row.kda >= 3 ? 'is-green' : ''}>{row.kda.toFixed(2)}</strong></td><td><div className="is-champion-list">{row.champions.map(c => <span key={c.id}><Champion id={c.id} size="small" /><small>{c.games}</small></span>)}</div></td><td>{row.gpm.toFixed(1)}</td><td>{row.kp.toFixed(1)}%</td><td>{row.cspm.toFixed(1)}</td></tr>)}</tbody></table></div><div className="is-table-footnote"><Info size={14} /><p>KDA는 (킬 + 어시스트) ÷ 데스, GPM은 분당 골드입니다. {lane !== 'all' && `${laneNames[lane]}로 플레이한 경기의 모든 지표를 다시 집계했습니다. `}검색 결과의 순위는 전체 순위를 유지합니다.</p></div></>;
|
||||
}
|
||||
|
||||
function GameAnalysis({ game, profileHref, eventHref }: { game: Game; profileHref: (id: string) => string; eventHref: (id: string) => string }) {
|
||||
const event = events.find(e => e.id === game.eventId)!;
|
||||
const series = event.series.find(s => s.id === game.seriesId)!;
|
||||
const [retryMessage, setRetryMessage] = useState('');
|
||||
const totals = [game.blue, game.red].map(id => game.participants.filter(p => p.teamId === id).reduce((sum, p) => ({ gold: sum.gold + p.gold, kills: sum.kills + p.kills, damage: sum.damage + p.damage }), { gold: 0, kills: 0, damage: 0 }));
|
||||
const timeline = [0, 5, 10, 15, 20, Math.round(game.duration / 60)].filter((n, i, a) => a.indexOf(n) === i).map((minute, i) => ({ minute, 블루: Math.round(totals[0].gold * minute / Math.round(game.duration / 60) * (i < 3 ? .85 : 1)), 레드: Math.round(totals[1].gold * minute / Math.round(game.duration / 60) * (i < 3 ? .9 : 1)) }));
|
||||
return <>
|
||||
<div className="is-game-context"><PreviewLink to={eventHref(event.id)}>{event.name}<ChevronRight size={14} /></PreviewLink><span>{series.label}</span><strong>{game.ordinal}세트 <span className="is-muted">· 전체 #{game.number}</span></strong><span><Clock3 size={14} />{formatDuration(game.duration)}</span></div>
|
||||
<div className="is-game-result"><div className={game.winner === game.blue ? 'is-result-win' : ''}><span className="is-blue">BLUE SIDE</span><h2>{teamName(game.blue)}</h2><b>{game.winner === game.blue ? '승리' : '패배'}</b></div><strong>{game.evidence === 'ready' ? `${totals[0].kills} : ${totals[1].kills}` : 'VS'}<small>{game.evidence === 'ready' ? '팀 킬 스코어' : '공식 세트 결과'}</small></strong><div className={game.winner === game.red ? 'is-result-win' : ''}><span className="is-red">RED SIDE</span><h2>{teamName(game.red)}</h2><b>{game.winner === game.red ? '승리' : '패배'}</b></div></div>
|
||||
{game.evidence !== 'ready' ? <Feedback type="empty" title={game.evidence === 'missing' ? '공식 결과만 남아 있는 경기입니다' : '상세 기록을 수집하고 있습니다'} action={<><Btn to={eventHref(event.id)}>내전의 전체 기록 보기</Btn>{game.evidence === 'pending' && <Btn variant="ghost" onClick={() => setRetryMessage('아직 새로운 분석 기록이 없습니다. 공식 결과는 위에서 확인할 수 있습니다.')}>수집 상태 다시 확인</Btn>}</>}>{retryMessage || (game.evidence === 'missing' ? 'Riot 원본 기록이 없어 선수별 지표와 그래프를 제공하지 않습니다. 승패 결과는 계속 확인할 수 있습니다.' : '선수별 지표는 수집이 완료되면 표시됩니다. 공식 승패와 경기 시간은 먼저 확인할 수 있습니다.')}</Feedback> : <>
|
||||
<div className="is-analysis-top"><section className="is-analysis-panel"><header><h2>골드 흐름</h2><span>예시 타임라인 · 팀 누적 골드</span></header><div className="is-chart"><ResponsiveContainer width="100%" height="100%" minWidth={0} initialDimension={{ width: 520, height: 215 }}><LineChart data={timeline} margin={{ left: 0, right: 12, top: 10, bottom: 0 }} accessibilityLayer><CartesianGrid strokeDasharray="3 3" vertical={false} stroke="var(--color-border)" /><XAxis dataKey="minute" tickFormatter={n => `${n}분`} tickLine={false} axisLine={false} fontSize={11} /><YAxis tickFormatter={n => `${Number(n) / 1000}k`} width={40} tickLine={false} axisLine={false} fontSize={11} /><Tooltip formatter={value => Number(value).toLocaleString()} labelFormatter={label => `${label}분`} contentStyle={{ background: 'var(--color-background-card)', color: 'var(--color-text-primary)', border: '1px solid var(--color-border)', borderRadius: 8 }} /><Legend /><Line type="monotone" dataKey="블루" stroke="var(--color-win)" strokeWidth={2} dot={false} isAnimationActive={false} /><Line type="monotone" dataKey="레드" stroke="var(--color-loss)" strokeWidth={2} dot={false} isAnimationActive={false} /></LineChart></ResponsiveContainer></div><p className="is-muted is-chart-description">최종 골드: 블루 {totals[0].gold.toLocaleString()} · 레드 {totals[1].gold.toLocaleString()}</p></section><section className="is-analysis-panel"><header><h2>팀 비교</h2><span>블루 / 레드</span></header><div className="is-team-comparison">{(['kills', 'gold', 'damage'] as const).map((key, i) => <div key={key}><div><strong className="is-blue">{totals[0][key].toLocaleString()}</strong><span>{['킬', '골드', '챔피언 피해량'][i]}</span><strong className="is-red">{totals[1][key].toLocaleString()}</strong></div><div className="is-comparison-track" aria-hidden="true"><span style={{ width: `${totals[0][key] / (totals[0][key] + totals[1][key]) * 100}%` }} /></div></div>)}</div></section></div>
|
||||
{[game.blue, game.red].map((id, index) => <section key={id} className="is-scoreboard"><header><h2><span className={index === 0 ? 'is-blue' : 'is-red'}>{game.winner === id ? '승리' : '패배'}</span>{teamName(id)}</h2><span>{index === 0 ? '블루' : '레드'} · {totals[index].kills}킬 · {totals[index].gold.toLocaleString()}골드</span></header><div className="is-table-scroll" tabIndex={0} role="region" aria-label={`${teamName(id)} 선수별 스코어보드`}><table><thead><tr><th scope="col">선수 / 챔피언</th><th scope="col">K / D / A</th><th scope="col">킬 관여</th><th scope="col">피해량</th><th scope="col">골드</th><th scope="col">CS / 분당</th><th scope="col">시야 점수</th></tr></thead><tbody>{game.participants.filter(p => p.teamId === id).map(p => <ScoreboardRow key={p.playerId} participant={p} duration={game.duration} profileHref={profileHref} />)}</tbody></table></div></section>)}
|
||||
</>}
|
||||
</>;
|
||||
}
|
||||
function ScoreboardRow({ participant: p, duration, profileHref }: { participant: Participant; duration: number; profileHref: (id: string) => string }) {
|
||||
return <tr><th scope="row"><div className="is-player-identity"><Champion id={p.champion} /><div><PreviewLink to={profileHref(p.playerId)}>{playerById.get(p.playerId)!.name}</PreviewLink><small>{laneNames[p.lane]} · {champions[p.champion].name}</small></div></div></th><td><strong>{p.kills} / {p.deaths} / {p.assists}</strong><small>{((p.kills + p.assists) / Math.max(1, p.deaths)).toFixed(2)} KDA</small></td><td>{p.kp.toFixed(1)}%</td><td>{p.damage.toLocaleString()}</td><td>{p.gold.toLocaleString()}</td><td>{p.cs}<small>{(p.cs / (duration / 60)).toFixed(1)} / 분</small></td><td>{p.vision}</td></tr>;
|
||||
}
|
||||
function PlayerDetail({ playerId, season, lane, onLane, gameHref, participationHref }: { playerId: string; season: string; lane: Lane | 'all'; onLane: (lane: string) => void; gameHref: (id: string) => string; participationHref: (id: string) => string }) {
|
||||
const player = playerById.get(playerId)!;
|
||||
const row = aggregateRows(season, lane, 5, 'games').find(r => r.id === playerId);
|
||||
const appearances = playerGames(playerId, season, lane);
|
||||
return <><div className="is-profile-heading"><Champion id={player.champion} size="large" /><div><h2>{player.name}</h2><span>{teamName(player.teamId)} · 주 포지션 {laneNames[player.lane]}</span></div><PreviewLink className="is-action-link" to={participationHref(playerId)}>참가 내전 보기<ArrowRight size={16} /></PreviewLink></div><div className="is-profile-filters"><label className="is-select"><span>집계 포지션</span><select aria-label="선수 집계 포지션" value={lane} onChange={e => onLane(e.target.value)}><option value="all">전체 포지션</option>{lanes.map(l => <option value={l} key={l}>{laneNames[l]}</option>)}</select></label><p className="is-muted">선택한 시즌과 포지션으로 모든 지표를 집계합니다.</p></div>{row ? <><div className="is-profile-stats">{[['판수', `${row.games}`, `${row.wins}승 ${row.losses}패`], ['승률', `${Math.round(row.winRate)}%`, '수집된 경기 기준'], ['KDA', row.kda.toFixed(2), '(킬 + 어시스트) / 데스'], ['GPM', row.gpm.toFixed(1), '평균 분당 골드'], ['킬 관여', `${row.kp.toFixed(1)}%`, '평균 킬 관여율'], ['분당 CS', row.cspm.toFixed(1), '평균 CS']].map(([label, value, desc]) => <div key={label}><span>{label}</span><strong>{value}</strong><small>{desc}</small></div>)}</div><div className="is-result-heading"><h2>참가 세트 기록 <span>{appearances.length}판</span></h2><p>최근 내전부터 표시</p></div><div className="is-personal-games">{appearances.map(({ game, participant: p }) => { const event = events.find(e => e.id === game.eventId)!; return <article key={game.id} className={p.won ? 'is-personal-win' : 'is-personal-loss'}><span className={`is-personal-result ${p.won ? 'is-blue' : 'is-red'}`}>{p.won ? '승리' : '패배'}</span><Champion id={p.champion} /><div className="is-personal-event"><strong>{event.name}</strong><small>{formatDate(event.date)} · 전체 {game.number}세트 · {laneNames[p.lane]}</small></div><span className="is-personal-kda"><strong>{p.kills} / {p.deaths} / {p.assists}</strong><small>{((p.kills + p.assists) / Math.max(p.deaths, 1)).toFixed(2)} KDA</small></span><span className="is-duration">{formatDuration(game.duration)}</span><PreviewLink className="is-analysis-link" to={gameHref(game.id)} data-return-id={`personal-${game.id}`} aria-label={`${event.name} 전체 ${game.number}세트 분석`}>분석<ChevronRight size={14} /></PreviewLink></article>; })}</div></> : <Feedback type="empty" title="이 포지션의 기록이 없습니다" action={<Btn onClick={() => onLane('all')}>전체 포지션 보기</Btn>}>다른 포지션이나 시즌을 선택해 주세요.</Feedback>}</>;
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Deterministic, preview-only fixtures. Every displayed aggregate is calculated
|
||||
// from these games. These are illustrative records, not imported live results.
|
||||
export const PREVIEW_PATH = '/design-previews/internal-stats.html';
|
||||
export const ORIGINAL_PATH = '/communities/69ebe0adf627c11be2f020a1/internal-stats';
|
||||
export const lanes = ['TOP', 'JUNGLE', 'MIDDLE', 'BOTTOM', 'UTILITY'] as const;
|
||||
export type Lane = typeof lanes[number];
|
||||
export const laneNames: Record<Lane, string> = { TOP: '탑', JUNGLE: '정글', MIDDLE: '미드', BOTTOM: '원딜', UTILITY: '서포터' };
|
||||
export const seasons = [
|
||||
{ id: '2026-2', name: '2026 시즌 2', from: '2026-06-01', to: '2026-06-30' },
|
||||
{ id: '2026-1', name: '2026 시즌 1', from: '2026-05-01', to: '2026-05-31' },
|
||||
];
|
||||
export const champions = [
|
||||
{ key: 'Ornn', name: '오른' }, { key: 'LeeSin', name: '리 신' },
|
||||
{ key: 'Ahri', name: '아리' }, { key: 'Ezreal', name: '이즈리얼' }, { key: 'Thresh', name: '쓰레쉬' },
|
||||
{ key: 'Gnar', name: '나르' }, { key: 'Viego', name: '비에고' },
|
||||
{ key: 'Orianna', name: '오리아나' }, { key: 'Jinx', name: '징크스' }, { key: 'Leona', name: '레오나' },
|
||||
{ key: 'Renekton', name: '레넥톤' }, { key: 'Sejuani', name: '세주아니' },
|
||||
{ key: 'Syndra', name: '신드라' }, { key: 'Kaisa', name: '카이사' }, { key: 'Nautilus', name: '노틸러스' },
|
||||
];
|
||||
export function championImage(key: string) {
|
||||
return `https://ddragon.leagueoflegends.com/cdn/15.24.1/img/champion/${key}.png`;
|
||||
}
|
||||
export type Player = { id: string; name: string; lane: Lane; teamId: string; champion: number };
|
||||
export type Team = { id: string; name: string; players: Player[] };
|
||||
const names = [
|
||||
'덕 덕', '정 웅', '장금순', '귤팽이', 'Choco Queen',
|
||||
'으악도망처', '정공글주', '프리리', '멘헤라 원딜', '달래줘',
|
||||
'그 냥', '하냥이', '귤딱콩', '김꾸루꾸루', '서폿의 품격',
|
||||
'캐리요정', 'Horra', '던 던', '포악한 너구리', '여름밤',
|
||||
'오른손', '달빛정글', '민트초코', '봄날의 원딜', '구름산책',
|
||||
'단단한 바위', '바람길', '새벽별', '라임소다', '느린우체통',
|
||||
'탑의기억', '초록숲', '고양이발', '은빛화살', '작은파도',
|
||||
'도토리', '숲속여우', '별사탕', '노을빛', '밤하늘',
|
||||
];
|
||||
export const teams: Team[] = ['포구리야~', '나물장수', '해온해줘', '똥칼라파워', '참봉발사', '월요일의 기적', '바텀 듀오', '다섯 번째 계절'].map((name, t) => ({
|
||||
id: `t${t}`, name,
|
||||
players: lanes.map((lane, i) => ({ id: `p${t * 5 + i}`, name: names[t * 5 + i], lane, teamId: `t${t}`, champion: (t % 3) * 5 + i })),
|
||||
}));
|
||||
export const players = teams.flatMap(t => t.players);
|
||||
export const teamById = new Map(teams.map(t => [t.id, t]));
|
||||
export const playerById = new Map(players.map(p => [p.id, p]));
|
||||
export type Participant = {
|
||||
playerId: string; teamId: string; lane: Lane; champion: number;
|
||||
kills: number; deaths: number; assists: number; cs: number; gold: number;
|
||||
damage: number; vision: number; kp: number; won: boolean;
|
||||
};
|
||||
export type Game = {
|
||||
id: string; eventId: string; seriesId: string; number: number; ordinal: number;
|
||||
blue: string; red: string; winner: string; duration: number;
|
||||
evidence: 'ready' | 'missing' | 'pending'; participants: Participant[];
|
||||
};
|
||||
export type Series = { id: string; label: string; a: string; b: string; games: Game[]; winner: string; scoreA: number; scoreB: number };
|
||||
export type Event = {
|
||||
id: string; name: string; date: string; time: string; season: string;
|
||||
format: 'pair' | 'tournament'; formatLabel: string; teamIds: string[];
|
||||
champion: string | null; series: Series[];
|
||||
};
|
||||
function makeEvent(id: string, name: string, date: string, kind: 'double' | 'league' | 'pair', seed: number): Event {
|
||||
const event: Event = { id, name, date, time: '21:00', season: date.startsWith('2026-06') ? '2026-2' : '2026-1', format: kind === 'pair' ? 'pair' : 'tournament', formatLabel: kind === 'double' ? '더블 엘리미네이션' : kind === 'league' ? '리그전' : '두 팀 내전', teamIds: [], champion: null, series: [] };
|
||||
let serial = 0;
|
||||
const series = (label: string, a: string, b: string, winner: string, count = 3) => {
|
||||
const sid = `${id}-s${event.series.length + 1}`;
|
||||
const games: Game[] = Array.from({ length: count }, (_, i) => {
|
||||
serial += 1;
|
||||
const n = serial;
|
||||
const losingTeam = winner === a ? b : a;
|
||||
const won = count === 3 && i === 1 ? losingTeam : winner;
|
||||
const blue = i % 2 ? b : a;
|
||||
const red = blue === a ? b : a;
|
||||
const duration = 1560 + ((n * 127 + seed * 79) % 900);
|
||||
const kills = [0, 1].map(side => lanes.map((_, slot) => 2 + (n * 7 + seed * 3 + side * 5 + slot * 3) % 10));
|
||||
const participants = [blue, red].flatMap((tid, side) => teamById.get(tid)!.players.map((player, slot): Participant => {
|
||||
const lane = lanes[(slot + (n % 7 === 0 ? 1 : 0)) % 5];
|
||||
const teamKills = kills[side].reduce((sum, k) => sum + k, 0);
|
||||
const assists = Math.min(teamKills - kills[side][slot], 5 + (n + slot * 4 + seed) % 17);
|
||||
const gpm = (lane === 'UTILITY' ? 260 : lane === 'BOTTOM' ? 460 : 370) + (n * 13 + slot * 21 + seed * 7 + side * 37) % 100 + (won === tid ? 28 : 0);
|
||||
return { playerId: player.id, teamId: tid, lane, champion: (player.champion + (n % 3) * 5) % champions.length, kills: kills[side][slot], deaths: kills[1 - side][slot], assists, cs: Math.round((lane === 'UTILITY' ? 1.2 : 5.5 + (n + slot) % 4) * duration / 60), gold: Math.round(gpm * duration / 60), damage: 8000 + ((n * 1331 + slot * 3443 + seed * 701 + side * 3911) % 24000), vision: lane === 'UTILITY' ? 45 + n % 42 : 12 + n % 30, kp: (kills[side][slot] + assists) / teamKills * 100, won: won === tid };
|
||||
}));
|
||||
const evidence = id === 'summer-finals' && [3, 6, 9, 12, 15, 18, 21].includes(n) ? 'missing' : id === 'friday-league' && n === 12 ? 'pending' : 'ready';
|
||||
return { id: `${id}-g${n}`, eventId: id, seriesId: sid, number: n, ordinal: i + 1, blue, red, winner: won, duration, evidence, participants };
|
||||
});
|
||||
const result = { id: sid, label, a, b, games, winner, scoreA: games.filter(g => g.winner === a).length, scoreB: games.filter(g => g.winner === b).length };
|
||||
event.series.push(result);
|
||||
return { win: winner, loss: winner === a ? b : a };
|
||||
};
|
||||
if (kind === 'double') {
|
||||
const q1 = series('승자조 1라운드 · 1경기', 't0', 't7', 't0', 2);
|
||||
const q2 = series('승자조 1라운드 · 2경기', 't1', 't6', 't1', 2);
|
||||
const q3 = series('승자조 1라운드 · 3경기', 't2', 't5', 't2', 2);
|
||||
const q4 = series('승자조 1라운드 · 4경기', 't3', 't4', 't3', 2);
|
||||
const s1 = series('승자조 준결승 · 1경기', q1.win, q2.win, q1.win, 2);
|
||||
const s2 = series('승자조 준결승 · 2경기', q3.win, q4.win, q3.win, 2);
|
||||
const l1 = series('패자조 1라운드 · 1경기', q1.loss, q2.loss, q2.loss, 2);
|
||||
const l2 = series('패자조 1라운드 · 2경기', q3.loss, q4.loss, q4.loss, 2);
|
||||
const l3 = series('패자조 2라운드 · 1경기', l1.win, s2.loss, s2.loss, 2);
|
||||
const l4 = series('패자조 2라운드 · 2경기', l2.win, s1.loss, s1.loss, 2);
|
||||
const wf = series('승자조 결승', s1.win, s2.win, s1.win, 2);
|
||||
const ls = series('패자조 준결승', l3.win, l4.win, l4.win, 2);
|
||||
const lf = series('패자조 결승', ls.win, wf.loss, ls.win, 2);
|
||||
const final = series('최종 결승', wf.win, lf.win, wf.win, 3);
|
||||
event.champion = final.win;
|
||||
} else if (kind === 'league') {
|
||||
const ids = seed % 2 ? ['t0', 't1', 't2', 't3'] : ['t4', 't5', 't6', 't7'];
|
||||
for (let i = 0; i < 4; i++) for (let j = i + 1; j < 4; j++) series(`리그 ${event.series.length + 1}경기`, ids[i], ids[j], ids[i], 2);
|
||||
event.champion = ids[0];
|
||||
} else {
|
||||
const a = `t${seed % 8}`, b = `t${(seed + 3) % 8}`;
|
||||
series('3판 2선승', a, b, seed % 2 ? a : b);
|
||||
}
|
||||
event.teamIds = [...new Set(event.series.flatMap(s => [s.a, s.b]))];
|
||||
return event;
|
||||
}
|
||||
export const events: Event[] = [
|
||||
makeEvent('summer-finals', '6월 정기 멸망전', '2026-06-27', 'double', 1),
|
||||
makeEvent('friday-league', '목요일, 한 판 더', '2026-06-25', 'league', 3),
|
||||
makeEvent('tuesday-pair', '화요일 저녁 내전', '2026-06-23', 'pair', 2),
|
||||
makeEvent('monday-league', '월요 내전 리그', '2026-06-22', 'league', 4),
|
||||
makeEvent('weekend-pair', '주말 자유 내전', '2026-06-21', 'pair', 5),
|
||||
makeEvent('saturday-pair', '토요일 리매치', '2026-06-20', 'pair', 6),
|
||||
makeEvent('may-finals', '5월 마무리 리그', '2026-05-30', 'league', 7),
|
||||
makeEvent('may-pair', '수요일 저녁 내전', '2026-05-27', 'pair', 0),
|
||||
];
|
||||
export const games = events.flatMap(e => e.series.flatMap(s => s.games));
|
||||
@@ -0,0 +1,57 @@
|
||||
# 내전 전적 코드 시안 — 2026-11-11
|
||||
|
||||
## 범위와 실행
|
||||
|
||||
- URL: http://localhost:5173/design-previews/internal-stats.html
|
||||
- React / TypeScript / 기존 Vite 서버, 제품 테마 토큰과 Btn·Chip·AppTheme 재사용.
|
||||
- 기존 전적 페이지를 대체하지 않는 독립 HTML 진입점. 제품 라우터와 API를 수정하지 않았다.
|
||||
- 2시즌, 8내전, 40선수의 결정적인 예시 데이터. 실제 전적을 가져오거나 수정하지 않는다. 골드 흐름도 예시 타임라인이라고 화면에 표시한다.
|
||||
- 원본의 색상과 서체를 유지하면서 이전 UX 검토 제안을 구현한 재설계다. 원본의 픽셀 복제가 목표가 아니다.
|
||||
|
||||
## 제안 반영
|
||||
|
||||
| 검토 항목 | 구현 |
|
||||
| --- | --- |
|
||||
| 요약 때문에 좁아지는 본문 | 상단 SeasonSummary, 전체 너비 순위표. 시즌 최고/누적/단일 경기 기록의 범위를 각각 표기 |
|
||||
| 세트의 맥락 부족 | EventSection → SeriesResultGroup. 양 팀, 라운드, 시리즈 점수, 승리 팀, 개별/전체 세트 번호, 시간, 원본 상태 |
|
||||
| 긴 경기 목록 탐색 | 데스크톱 날짜 인덱스, 모바일 바로가기, 내전 단위 추가 로드. 표시한 내전의 세트는 모두 공개 |
|
||||
| 순위의 의미 | 기본값은 참여 경기 수. 중립적인 숫자 순위, 명시적 정렬, 최소 판수와 기준 미달 표기, 기준 충족 필터 |
|
||||
| 모바일 표 | 순위·이름 고정, 승률·판수 우선, 나머지 지표를 가로 스크롤. 챔피언/상세 지표 삭제 없음 |
|
||||
| 필터와 시즌 | 시즌·기간·유형·선수/팀/내전 검색, 개별 조건 해제와 초기화. 검색 순위는 원래 순위 유지 |
|
||||
| 포지션 정확성 | 해당 포지션으로 플레이한 세트만 판수·승률·KDA·GPM·킬 관여·CS/분 재집계 |
|
||||
| 탐색 복귀 | URL에 탭과 조건 저장. 개인 전적/내전/세트 분석 왕복 시 스크롤·포커스 복원. returnTo 중첩 제거 |
|
||||
| 개인 및 경기 상세 | 같은 시즌의 개인 지표와 참가 세트, 근거 경기 링크, 10인 스코어보드, 골드 그래프/팀 비교 |
|
||||
| 실패/부족한 데이터 | 빈 결과 초기화, 기간 오류, 로딩/조회 오류와 재시도, 원본 없음/수집 중과 공식 결과 분리 |
|
||||
| 접근성 | 탭 방향키/Home/End, 표 헤더/aria-sort, 고정 열, 포커스 표시, skip link, 상태 알림, 이미지 alt, reduced-motion |
|
||||
|
||||
이전 조사에서 OpenDota·Lichess의 경기 맥락, Umami·Plausible·Metabase의 범위와 필터, TanStack Table의 정렬·고정 열, Radix·shadcn의 상태와 접근성, Recharts의 데이터 표현, brackets-viewer·react-tournament-brackets의 시리즈 계층을 검토했다. 이 시안은 해당 패턴을 현재 제품의 정보 상시 노출 원칙에 맞춰 구현한다. 라이브러리를 새로 추가하지 않았다. LeagueStats는 비상업 라이선스의 추가 참고 자료이며 코드를 복제하지 않았다.
|
||||
|
||||
## 시각 검수
|
||||
|
||||
증거 폴더: `C:/Users/park/.codex/visualizations/2026/11/11/01a1c9d5-e028-75a0-8b1b-f70126da1d08/internal-stats-preview/`
|
||||
|
||||
- 원본: 같은 상위 폴더의 `internal-stats-audit/01-recent.jpg`, `02-ranking.jpg`, `07-mobile-recent.jpg`, `08-mobile-ranking.jpg` 및 사용자 첨부 이미지.
|
||||
- 구현: `01-desktop-matches.jpg`, `02-desktop-ranking.jpg`, `03-player-detail.jpg`, `04-set-analysis.jpg`, `05-mobile-overview.jpg`, `06-mobile-ranking.jpg`, `07-mobile-matches.jpg`, `08-mobile-analysis.jpg`, `09-mobile-error.jpg`, `10-missing-record.jpg`, `11-dark-missing-record.jpg`, `12-dark-ranking.jpg`.
|
||||
- 1440×1050, 390×844 CSS viewport에서 실제 렌더를 확인. 원본의 밀집된 세트 행을 상대·점수가 있는 묶음으로 바꾸고 기존의 흰색/잉크/코랄 위계를 유지했다.
|
||||
- 모바일 문서 가로 넘침 없음. 341px 표 컨테이너에서 이름·승률·판수 확인. 가로 스크롤 374px 후에도 이름 열의 x좌표 유지.
|
||||
- 경기·선수·세트 화면의 글꼴, 카드 여백, 상태색, 선/표 정렬, 이미지 로딩, 라이트/다크를 확인. 확인한 화면의 깨진 이미지 없음.
|
||||
- 발견 후 수정: 날짜 입력 이벤트가 UI와 URL에 반영되도록 onInput 사용, 차트 초기 크기 경고 제거, 한국어 설명 줄바꿈 개선, 시즌 요약 링크의 포지션 필터 제거, 경기 상세에서 시즌 변경 시 해당 시즌 목록으로 이동, 복귀 URL 중첩 제거.
|
||||
- 승인된 재설계 범위에서 남은 P0/P1/P2 시각 문제 없음. 모바일 표의 나머지 열은 의도적으로 가로 스크롤한다. 정량 색 대비 감사·모든 브라우저 전수 검증은 수행하지 않았다.
|
||||
|
||||
## 동작 검증
|
||||
|
||||
- 시즌 2: 6내전, 62공식 세트, 54분석 가능 세트, 40선수. 시즌 1: 2내전, 15세트, 20선수로 전환됨.
|
||||
- 14시리즈/29세트 내전의 공식 결과가 모두 보이며, 7개의 원본 누락은 분석 지표에서 제외됨.
|
||||
- 선수 검색 + 정글 필터 → 개인 전적 → 세트 분석 → 복귀. 필터, 스크롤, 포커스 복원 확인.
|
||||
- KDA/승률 정렬, 빈 선수 검색/초기화, 모바일 고정 열, 날짜 바로가기, 키보드 탭 전환 확인.
|
||||
- 6월25일 이후 필터 2내전. 역전 날짜의 오류와 초기화, 목록 4→6개 추가 로드 확인.
|
||||
- 조회 오류 → 다시 시도 → 같은 목록 복귀. 원본 없음에서 공식 결과만 표시하며 분석표 미생성. 수집 중 상태 재확인 문구 확인.
|
||||
- 최종 차트 재진입 후 새 browser error/warn 로그 없음.
|
||||
- TypeScript 검사, 대상 ESLint, 데이터 집계/시즌/상대·점수/필터/포지션/판수·정렬/최고 기록 근거를 검증하는 6개 테스트 통과.
|
||||
- 독립 HTML을 대상으로 Vite production build 통과. 기존 전체 테마 CSS와 Recharts를 포함하므로 500KB chunk 안내가 있다. 시안 단계에서 분할 로딩 최적화는 적용하지 않았다.
|
||||
|
||||
## 적용 시 필요한 경계
|
||||
|
||||
이 결과는 검토 가능한 코드 시안이다. 실제 API의 오류 복구, 원본 가용성/시리즈/포지션별 집계 계약 연결은 제품 적용 단계의 작업이며 이 시안으로 실서버 오류가 해결된 것은 아니다. DDragon 챔피언 이미지에는 네트워크 연결이 필요하다. 배포하지 않았다.
|
||||
|
||||
final result: passed
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import { BrowserRouter } from 'react-router';
|
||||
import { AppTheme } from '../../ui/AppTheme';
|
||||
import { initializeTheme } from '../../config';
|
||||
import Preview from './Preview';
|
||||
import '../../index.css';
|
||||
import './preview.css';
|
||||
|
||||
initializeTheme();
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode><BrowserRouter><AppTheme><Preview /></AppTheme></BrowserRouter></StrictMode>,
|
||||
);
|
||||
Loaded 100 of 154 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user