Compare commits
25
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2004ea03fe | ||
|
|
8ec9edc35f | ||
|
|
61f1db0e6a | ||
|
|
c9140b8622 | ||
|
|
4e10998794 | ||
|
|
b115072005 | ||
|
|
03e88a03bc | ||
|
|
43c25c05cd | ||
|
|
dc77b37494 | ||
|
|
bb32c26694 | ||
|
|
81b951889f | ||
|
|
96bae0ce28 | ||
|
|
a88562b208 | ||
|
|
3bd3120eb1 | ||
|
|
3c60081ece | ||
|
|
aa675199af | ||
|
|
9f698a8fec | ||
|
|
075fb52848 | ||
|
|
738d274095 | ||
|
|
ef47de7e4f | ||
|
|
489d040d8f | ||
|
|
6b1c450752 | ||
|
|
bbcb2f43dc | ||
|
|
a307780752 | ||
|
|
c2f89f9cb2 |
No files matched your search
@@ -0,0 +1,4 @@
|
|||||||
|
[mcp_servers.playwright_macos]
|
||||||
|
url = "http://100.96.0.26:8931/mcp"
|
||||||
|
tool_timeout_sec = 120
|
||||||
|
startup_timeout_sec = 30
|
||||||
@@ -26,6 +26,10 @@ website/LICENSE
|
|||||||
*.md
|
*.md
|
||||||
!README.md
|
!README.md
|
||||||
!AGENTS.md
|
!AGENTS.md
|
||||||
|
!docs/specs/internal-match-game-analysis.md
|
||||||
|
!docs/plans/internal-match-game-analysis-p0-p1.md
|
||||||
|
!docs/specs/double-elimination-connector-routing.md
|
||||||
|
!docs/plans/double-elimination-connector-routing.md
|
||||||
!agents/**/*.md
|
!agents/**/*.md
|
||||||
!skills/**/*.md
|
!skills/**/*.md
|
||||||
/tmp/
|
/tmp/
|
||||||
|
|||||||
+6
-1
@@ -14,20 +14,23 @@ FROM pnpm-base AS deps
|
|||||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
COPY apps/api/package.json apps/api/package.json
|
COPY apps/api/package.json apps/api/package.json
|
||||||
COPY apps/web/package.json apps/web/package.json
|
COPY apps/web/package.json apps/web/package.json
|
||||||
|
COPY packages/contracts/package.json packages/contracts/package.json
|
||||||
|
|
||||||
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
RUN pnpm install --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
||||||
|
|
||||||
FROM deps AS build
|
FROM deps AS build
|
||||||
|
|
||||||
|
COPY packages/contracts packages/contracts
|
||||||
COPY apps/api apps/api
|
COPY apps/api apps/api
|
||||||
|
|
||||||
RUN pnpm --filter api build
|
RUN pnpm --filter api... build
|
||||||
|
|
||||||
FROM pnpm-base AS prod-deps
|
FROM pnpm-base AS prod-deps
|
||||||
|
|
||||||
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./
|
||||||
COPY apps/api/package.json apps/api/package.json
|
COPY apps/api/package.json apps/api/package.json
|
||||||
COPY apps/web/package.json apps/web/package.json
|
COPY apps/web/package.json apps/web/package.json
|
||||||
|
COPY packages/contracts/package.json packages/contracts/package.json
|
||||||
|
|
||||||
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
RUN pnpm install --prod --frozen-lockfile --filter api... --filter lolympus-tournament-support
|
||||||
|
|
||||||
@@ -41,6 +44,8 @@ COPY --from=prod-deps --chown=nonroot:nonroot /app/package.json ./package.json
|
|||||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/node_modules ./node_modules
|
||||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/package.json ./apps/api/package.json
|
||||||
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
COPY --from=prod-deps --chown=nonroot:nonroot /app/apps/api/node_modules ./apps/api/node_modules
|
||||||
|
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/package.json ./packages/contracts/package.json
|
||||||
|
COPY --from=build --chown=nonroot:nonroot /app/packages/contracts/dist ./packages/contracts/dist
|
||||||
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
|
COPY --chown=nonroot:nonroot apps/api/newrelic.cjs ./apps/api/newrelic.cjs
|
||||||
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
COPY --from=build --chown=nonroot:nonroot /app/apps/api/dist ./apps/api/dist
|
||||||
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
COPY --chown=nonroot:nonroot apps/project.env ./project.env
|
||||||
|
|||||||
@@ -83,7 +83,7 @@ function record(matchId: mongoose.Types.ObjectId): InternalRecord {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('CommunityStatsService', () => {
|
describe('CommunityStatsService', () => {
|
||||||
it('ignores stale detail cache entries missing timeline build fields', async () => {
|
it('ignores detail caches missing unified events or containing invalid checkpoints', async () => {
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const match: InternalMatchCardView = {
|
const match: InternalMatchCardView = {
|
||||||
@@ -97,6 +97,20 @@ describe('CommunityStatsService', () => {
|
|||||||
seriesResults: [],
|
seriesResults: [],
|
||||||
};
|
};
|
||||||
const participant = record(matchId);
|
const participant = record(matchId);
|
||||||
|
Object.assign(participant, {
|
||||||
|
participantId: 1,
|
||||||
|
checkpoints: {
|
||||||
|
at10: {
|
||||||
|
timestamp: 590,
|
||||||
|
gold: 5_200,
|
||||||
|
cs: 90,
|
||||||
|
xp: 4_200,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
const gameDetail: InternalGameDetail = {
|
const gameDetail: InternalGameDetail = {
|
||||||
gameNumber: 1,
|
gameNumber: 1,
|
||||||
riotMatchId: 'KR_1',
|
riotMatchId: 'KR_1',
|
||||||
@@ -125,38 +139,81 @@ describe('CommunityStatsService', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
const staleCache = {
|
Object.assign(gameDetail, {
|
||||||
match,
|
timelineEvents: [
|
||||||
games: [
|
|
||||||
{
|
{
|
||||||
gameNumber: 1,
|
timestamp: 300,
|
||||||
riotMatchId: 'KR_1',
|
side: 'blue',
|
||||||
gameCreation: 1_000,
|
type: 'championKill',
|
||||||
gameDuration: 1_800,
|
killerParticipantId: 1,
|
||||||
teams: [
|
victimParticipantId: 2,
|
||||||
|
assistingParticipantIds: [],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
const otherwiseCompleteCachedGame = {
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
gameCreation: 1_000,
|
||||||
|
gameDuration: 1_800,
|
||||||
|
timeline: [],
|
||||||
|
objectiveEvents: [],
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
side: 'blue' as const,
|
||||||
|
win: true,
|
||||||
|
objectives: objectives(),
|
||||||
|
bans: [],
|
||||||
|
participants: [
|
||||||
{
|
{
|
||||||
teamIndex: 1,
|
summonerName: 'Cached Player',
|
||||||
side: 'blue',
|
tagLine: 'KR1',
|
||||||
win: true,
|
itemBuild: [],
|
||||||
objectives: { tower: 1, dragon: 0, baron: 0 },
|
skillBuild: [],
|
||||||
participants: [
|
|
||||||
{
|
|
||||||
summonerName: 'Player',
|
|
||||||
perks: {
|
|
||||||
primaryStyle: 8000,
|
|
||||||
subStyle: 8400,
|
|
||||||
keystone: 8010,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
],
|
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
|
};
|
||||||
|
const missingTimelineEventsCache = {
|
||||||
|
match,
|
||||||
|
games: [otherwiseCompleteCachedGame],
|
||||||
} as unknown as InternalMatchDetailResponse;
|
} as unknown as InternalMatchDetailResponse;
|
||||||
|
const invalidCheckpointCache = {
|
||||||
|
match,
|
||||||
|
games: [
|
||||||
|
{
|
||||||
|
...otherwiseCompleteCachedGame,
|
||||||
|
timelineEvents: [],
|
||||||
|
teams: otherwiseCompleteCachedGame.teams.map((team) => ({
|
||||||
|
...team,
|
||||||
|
participants: team.participants.map((cachedParticipant) => ({
|
||||||
|
...cachedParticipant,
|
||||||
|
participantId: 1,
|
||||||
|
checkpoints: {
|
||||||
|
at10: {
|
||||||
|
timestamp: '590',
|
||||||
|
gold: 5_200,
|
||||||
|
cs: 90,
|
||||||
|
xp: 4_200,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
} as unknown as InternalMatchDetailResponse;
|
||||||
|
const setDetail = jest.fn().mockResolvedValue(undefined);
|
||||||
const cacheService = {
|
const cacheService = {
|
||||||
get: jest.fn().mockResolvedValue(staleCache),
|
get: jest
|
||||||
setDetail: jest.fn().mockResolvedValue(undefined),
|
.fn()
|
||||||
|
.mockResolvedValueOnce(missingTimelineEventsCache)
|
||||||
|
.mockResolvedValueOnce(invalidCheckpointCache),
|
||||||
|
setDetail,
|
||||||
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
const matchStatsService = {
|
const matchStatsService = {
|
||||||
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
buildAndUpsert: jest.fn().mockResolvedValue(undefined),
|
||||||
@@ -180,22 +237,245 @@ describe('CommunityStatsService', () => {
|
|||||||
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
|
detailsByMatchId: new Map([[matchId.toString(), [gameDetail]]]),
|
||||||
});
|
});
|
||||||
|
|
||||||
const response = await service.getMatchDetail({ communityId, matchId });
|
const missingEventsResponse = await service.getMatchDetail({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
const invalidCheckpointResponse = await service.getMatchDetail({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
});
|
||||||
|
|
||||||
expect(response.games[0].timeline).toHaveLength(1);
|
expect(missingEventsResponse.games[0].timeline).toHaveLength(1);
|
||||||
expect(response.games[0].teams[0].participants[0].itemBuild).toHaveLength(
|
expect(invalidCheckpointResponse.games[0].timeline).toHaveLength(1);
|
||||||
1,
|
expect(invalidCheckpointResponse.games[0]).toMatchObject({
|
||||||
);
|
timelineEvents: [
|
||||||
expect(response.games[0].teams[0].participants[0].perks).toMatchObject({
|
{
|
||||||
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
|
timestamp: 300,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'championKill',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
invalidCheckpointResponse.games[0].teams[0].participants[0],
|
||||||
|
).toMatchObject({
|
||||||
|
participantId: 1,
|
||||||
|
checkpoints: {
|
||||||
|
at10: {
|
||||||
|
timestamp: 590,
|
||||||
|
gold: 5_200,
|
||||||
|
cs: 90,
|
||||||
|
xp: 4_200,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
itemBuild: [{ timestamp: 10, itemId: 1054, type: 'purchased' }],
|
||||||
|
perks: {
|
||||||
|
selectedPerkIds: [8010, 9111, 9105, 8299, 8444, 8451],
|
||||||
|
},
|
||||||
});
|
});
|
||||||
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
|
expect(matchStatsService.buildAndUpsert).not.toHaveBeenCalled();
|
||||||
expect(cacheService.setDetail).toHaveBeenCalledWith(
|
expect(setDetail).toHaveBeenCalledTimes(2);
|
||||||
expect.stringContaining(':r3:'),
|
expect(setDetail).toHaveBeenNthCalledWith(
|
||||||
response,
|
2,
|
||||||
|
expect.stringContaining(':r4:'),
|
||||||
|
invalidCheckpointResponse,
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('backs off failed timeline hydration and retries after the short cache expires', async () => {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const match: InternalMatchCardView = {
|
||||||
|
matchId: matchId.toString(),
|
||||||
|
title: '내전',
|
||||||
|
scheduledAt: '2026-06-18T12:00:00.000Z',
|
||||||
|
status: 'finished',
|
||||||
|
gameCount: 1,
|
||||||
|
games: [],
|
||||||
|
teams: [],
|
||||||
|
seriesResults: [],
|
||||||
|
};
|
||||||
|
const participant = record(matchId);
|
||||||
|
const gameDetail: InternalGameDetail = {
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
gameCreation: 1_000,
|
||||||
|
gameDuration: 1_800,
|
||||||
|
winnerSide: 'blue',
|
||||||
|
timelineLoaded: false,
|
||||||
|
timeline: [],
|
||||||
|
objectiveEvents: [],
|
||||||
|
timelineEvents: [],
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
side: 'blue',
|
||||||
|
win: true,
|
||||||
|
objectives: objectives(),
|
||||||
|
bans: [],
|
||||||
|
participants: [participant],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const dataset = (timelineLoaded: boolean) => ({
|
||||||
|
season: {
|
||||||
|
id: 'all',
|
||||||
|
label: '전체',
|
||||||
|
startTime: null,
|
||||||
|
endTime: null,
|
||||||
|
},
|
||||||
|
matches: [match],
|
||||||
|
records: [participant],
|
||||||
|
detailsByMatchId: new Map([
|
||||||
|
[matchId.toString(), [{ ...gameDetail, timelineLoaded }]],
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
let cachedResponse: InternalMatchDetailResponse | null = null;
|
||||||
|
const set = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(
|
||||||
|
(_key: string, value: InternalMatchDetailResponse) => {
|
||||||
|
cachedResponse = value;
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const setDetail = jest
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(
|
||||||
|
(_key: string, value: InternalMatchDetailResponse) => {
|
||||||
|
cachedResponse = value;
|
||||||
|
return Promise.resolve();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const cacheService = {
|
||||||
|
get: jest.fn().mockImplementation(() => Promise.resolve(cachedResponse)),
|
||||||
|
set,
|
||||||
|
setDetail,
|
||||||
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
|
const buildAndUpsert = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{} as ConnectionService,
|
||||||
|
cacheService,
|
||||||
|
{} as MatchStatsRepository,
|
||||||
|
{ buildAndUpsert } as unknown as MatchStatsService,
|
||||||
|
);
|
||||||
|
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
|
||||||
|
jest
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(dataset(false))
|
||||||
|
.mockResolvedValueOnce(dataset(false))
|
||||||
|
.mockResolvedValueOnce(dataset(false))
|
||||||
|
.mockResolvedValueOnce(dataset(true));
|
||||||
|
|
||||||
|
const fallback = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
const backedOff = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
|
||||||
|
expect(backedOff).toBe(fallback);
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(1);
|
||||||
|
expect(set).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining(':r4:'),
|
||||||
|
fallback,
|
||||||
|
60,
|
||||||
|
);
|
||||||
|
expect(setDetail).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
cachedResponse = null;
|
||||||
|
const recovered = await service.getMatchDetail({ communityId, matchId });
|
||||||
|
|
||||||
|
expect(buildAndUpsert).toHaveBeenCalledTimes(2);
|
||||||
|
expect(setDetail).toHaveBeenCalledTimes(1);
|
||||||
|
expect(setDetail).toHaveBeenCalledWith(
|
||||||
|
expect.stringContaining(':r4:'),
|
||||||
|
recovered,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('coalesces concurrent internal match detail cache misses', async () => {
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const match: InternalMatchCardView = {
|
||||||
|
matchId: matchId.toString(),
|
||||||
|
title: '내전',
|
||||||
|
scheduledAt: '2026-06-18T12:00:00.000Z',
|
||||||
|
status: 'finished',
|
||||||
|
gameCount: 1,
|
||||||
|
games: [],
|
||||||
|
teams: [],
|
||||||
|
seriesResults: [],
|
||||||
|
};
|
||||||
|
const participant = record(matchId);
|
||||||
|
const dataset = {
|
||||||
|
season: {
|
||||||
|
id: 'all',
|
||||||
|
label: '전체',
|
||||||
|
startTime: null,
|
||||||
|
endTime: null,
|
||||||
|
},
|
||||||
|
matches: [match],
|
||||||
|
records: [participant],
|
||||||
|
detailsByMatchId: new Map([
|
||||||
|
[
|
||||||
|
matchId.toString(),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
gameNumber: 1,
|
||||||
|
riotMatchId: 'KR_1',
|
||||||
|
gameCreation: 1_000,
|
||||||
|
gameDuration: 1_800,
|
||||||
|
winnerSide: 'blue' as const,
|
||||||
|
timelineLoaded: true,
|
||||||
|
timeline: [],
|
||||||
|
objectiveEvents: [],
|
||||||
|
timelineEvents: [],
|
||||||
|
teams: [
|
||||||
|
{
|
||||||
|
teamIndex: 1,
|
||||||
|
side: 'blue' as const,
|
||||||
|
win: true,
|
||||||
|
objectives: objectives(),
|
||||||
|
bans: [],
|
||||||
|
participants: [participant],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
};
|
||||||
|
let resolveDataset: ((value: typeof dataset) => void) | undefined;
|
||||||
|
const datasetPromise = new Promise<typeof dataset>((resolve) => {
|
||||||
|
resolveDataset = resolve;
|
||||||
|
});
|
||||||
|
const setDetail = jest.fn().mockResolvedValue(undefined);
|
||||||
|
const cacheService = {
|
||||||
|
get: jest.fn().mockResolvedValue(null),
|
||||||
|
setDetail,
|
||||||
|
} as unknown as jest.Mocked<CommunityStatsCacheService>;
|
||||||
|
const service = new CommunityStatsService(
|
||||||
|
{} as ConnectionService,
|
||||||
|
cacheService,
|
||||||
|
{} as MatchStatsRepository,
|
||||||
|
{} as MatchStatsService,
|
||||||
|
);
|
||||||
|
const buildBaseDataset = jest.fn().mockReturnValue(datasetPromise);
|
||||||
|
(service as unknown as { buildBaseDataset: jest.Mock }).buildBaseDataset =
|
||||||
|
buildBaseDataset;
|
||||||
|
|
||||||
|
const first = service.getMatchDetail({ communityId, matchId });
|
||||||
|
const second = service.getMatchDetail({ communityId, matchId });
|
||||||
|
await Promise.resolve();
|
||||||
|
resolveDataset?.(dataset);
|
||||||
|
const [firstResponse, secondResponse] = await Promise.all([first, second]);
|
||||||
|
|
||||||
|
expect(firstResponse).toBe(secondResponse);
|
||||||
|
expect(buildBaseDataset).toHaveBeenCalledTimes(1);
|
||||||
|
expect(setDetail).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('includes internal match route fields in user internal history matches', async () => {
|
it('includes internal match route fields in user internal history matches', async () => {
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
|||||||
@@ -40,7 +40,8 @@ const DEFAULT_LIST_LIMIT = 20;
|
|||||||
const MAX_LIST_LIMIT = 50;
|
const MAX_LIST_LIMIT = 50;
|
||||||
const MAX_MATCH_SCAN = 300;
|
const MAX_MATCH_SCAN = 300;
|
||||||
const MIN_HIGHLIGHT_GAMES = 5;
|
const MIN_HIGHLIGHT_GAMES = 5;
|
||||||
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 3;
|
const MATCH_DETAIL_RESPONSE_CACHE_VERSION = 4;
|
||||||
|
const INCOMPLETE_MATCH_DETAIL_TTL_SECONDS = 60;
|
||||||
|
|
||||||
interface CommunityStatsContext {
|
interface CommunityStatsContext {
|
||||||
community: CommunityDocument;
|
community: CommunityDocument;
|
||||||
@@ -59,6 +60,10 @@ interface BaseDataset {
|
|||||||
@Injectable()
|
@Injectable()
|
||||||
export class CommunityStatsService {
|
export class CommunityStatsService {
|
||||||
private readonly logger = new Logger(CommunityStatsService.name);
|
private readonly logger = new Logger(CommunityStatsService.name);
|
||||||
|
private readonly matchDetailInFlight = new Map<
|
||||||
|
string,
|
||||||
|
Promise<InternalMatchDetailResponse>
|
||||||
|
>();
|
||||||
private readonly userInternalHistoryInFlight = new Map<
|
private readonly userInternalHistoryInFlight = new Map<
|
||||||
string,
|
string,
|
||||||
Promise<UserInternalHistoryResponse>
|
Promise<UserInternalHistoryResponse>
|
||||||
@@ -219,6 +224,27 @@ export class CommunityStatsService {
|
|||||||
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
await this.cacheService.get<InternalMatchDetailResponse>(key);
|
||||||
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
|
if (cached && isCompleteMatchDetailResponse(cached)) return cached;
|
||||||
|
|
||||||
|
const inFlight = this.matchDetailInFlight.get(key);
|
||||||
|
if (inFlight) return inFlight;
|
||||||
|
|
||||||
|
const promise = this.buildMatchDetailResponse(params, key);
|
||||||
|
this.matchDetailInFlight.set(key, promise);
|
||||||
|
try {
|
||||||
|
return await promise;
|
||||||
|
} finally {
|
||||||
|
if (this.matchDetailInFlight.get(key) === promise) {
|
||||||
|
this.matchDetailInFlight.delete(key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async buildMatchDetailResponse(
|
||||||
|
params: {
|
||||||
|
communityId: mongoose.Types.ObjectId;
|
||||||
|
matchId: mongoose.Types.ObjectId;
|
||||||
|
},
|
||||||
|
key: string,
|
||||||
|
): Promise<InternalMatchDetailResponse> {
|
||||||
const dataset = await this.buildBaseDataset(params.communityId, {
|
const dataset = await this.buildBaseDataset(params.communityId, {
|
||||||
seasonId: 'all',
|
seasonId: 'all',
|
||||||
});
|
});
|
||||||
@@ -246,6 +272,7 @@ export class CommunityStatsService {
|
|||||||
gameVersion: game.gameVersion,
|
gameVersion: game.gameVersion,
|
||||||
timeline: game.timeline ?? [],
|
timeline: game.timeline ?? [],
|
||||||
objectiveEvents: game.objectiveEvents ?? [],
|
objectiveEvents: game.objectiveEvents ?? [],
|
||||||
|
timelineEvents: game.timelineEvents ?? game.objectiveEvents ?? [],
|
||||||
teams: game.teams.map((team) => ({
|
teams: game.teams.map((team) => ({
|
||||||
teamIndex: team.teamIndex,
|
teamIndex: team.teamIndex,
|
||||||
side: team.side,
|
side: team.side,
|
||||||
@@ -253,6 +280,8 @@ export class CommunityStatsService {
|
|||||||
objectives: team.objectives,
|
objectives: team.objectives,
|
||||||
bans: team.bans ?? [],
|
bans: team.bans ?? [],
|
||||||
participants: team.participants.map((record) => ({
|
participants: team.participants.map((record) => ({
|
||||||
|
participantId: record.participantId,
|
||||||
|
checkpoints: record.checkpoints,
|
||||||
userId: record.userId,
|
userId: record.userId,
|
||||||
summonerName: record.summonerName,
|
summonerName: record.summonerName,
|
||||||
tagLine: record.tagLine,
|
tagLine: record.tagLine,
|
||||||
@@ -289,7 +318,15 @@ export class CommunityStatsService {
|
|||||||
})),
|
})),
|
||||||
})),
|
})),
|
||||||
};
|
};
|
||||||
await this.cacheService.setDetail(key, response);
|
if (gameDetails.every((game) => game.timelineLoaded === true)) {
|
||||||
|
await this.cacheService.setDetail(key, response);
|
||||||
|
} else {
|
||||||
|
await this.cacheService.set(
|
||||||
|
key,
|
||||||
|
response,
|
||||||
|
INCOMPLETE_MATCH_DETAIL_TTL_SECONDS,
|
||||||
|
);
|
||||||
|
}
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1160,6 +1197,7 @@ function isCompleteMatchDetailResponse(
|
|||||||
(game) =>
|
(game) =>
|
||||||
Array.isArray(game.timeline) &&
|
Array.isArray(game.timeline) &&
|
||||||
Array.isArray(game.objectiveEvents) &&
|
Array.isArray(game.objectiveEvents) &&
|
||||||
|
Array.isArray(game.timelineEvents) &&
|
||||||
game.teams.every(
|
game.teams.every(
|
||||||
(team) =>
|
(team) =>
|
||||||
Array.isArray(team.bans) &&
|
Array.isArray(team.bans) &&
|
||||||
@@ -1167,8 +1205,41 @@ function isCompleteMatchDetailResponse(
|
|||||||
(participant) =>
|
(participant) =>
|
||||||
typeof participant.tagLine === 'string' &&
|
typeof participant.tagLine === 'string' &&
|
||||||
Array.isArray(participant.itemBuild) &&
|
Array.isArray(participant.itemBuild) &&
|
||||||
Array.isArray(participant.skillBuild),
|
Array.isArray(participant.skillBuild) &&
|
||||||
|
isOptionalFiniteNumber(participant.participantId) &&
|
||||||
|
isCompleteParticipantCheckpoints(participant.checkpoints),
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isCompleteParticipantCheckpoints(value: unknown): boolean {
|
||||||
|
if (value === undefined) return true;
|
||||||
|
if (!isRecord(value)) return false;
|
||||||
|
return ['at10', 'at15'].every((key) => {
|
||||||
|
const checkpoint = value[key];
|
||||||
|
if (checkpoint === undefined) return true;
|
||||||
|
if (!isRecord(checkpoint)) return false;
|
||||||
|
return [
|
||||||
|
'timestamp',
|
||||||
|
'gold',
|
||||||
|
'cs',
|
||||||
|
'xp',
|
||||||
|
'kills',
|
||||||
|
'deaths',
|
||||||
|
'assists',
|
||||||
|
].every((field) => isFiniteNumber(checkpoint[field]));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function isOptionalFiniteNumber(value: unknown): boolean {
|
||||||
|
return value === undefined || isFiniteNumber(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isFiniteNumber(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isFinite(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||||
|
}
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
import type {
|
import type {
|
||||||
|
MatchStatsParticipantCheckpoints,
|
||||||
MatchStatsItemBuildEvent,
|
MatchStatsItemBuildEvent,
|
||||||
MatchStatsRunePerks,
|
MatchStatsRunePerks,
|
||||||
MatchStatsSkillBuildEvent,
|
MatchStatsSkillBuildEvent,
|
||||||
|
MatchStatsTimelineEvent,
|
||||||
RiotLane,
|
RiotLane,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -128,6 +130,7 @@ export interface InternalMatchDetailResponse {
|
|||||||
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
||||||
monsterSubType?: string;
|
monsterSubType?: string;
|
||||||
}>;
|
}>;
|
||||||
|
timelineEvents: MatchStatsTimelineEvent[];
|
||||||
teams: Array<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -143,6 +146,8 @@ export interface InternalMatchDetailResponse {
|
|||||||
};
|
};
|
||||||
bans: Array<{ championId: number; pickTurn: number }>;
|
bans: Array<{ championId: number; pickTurn: number }>;
|
||||||
participants: Array<{
|
participants: Array<{
|
||||||
|
participantId?: number;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
userId: string | null;
|
userId: string | null;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
|
|||||||
@@ -100,6 +100,24 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
it('builds rich set detail from raw Riot match data', () => {
|
it('builds rich set detail from raw Riot match data', () => {
|
||||||
const builder = new MatchStatsFragmentBuilder();
|
const builder = new MatchStatsFragmentBuilder();
|
||||||
const match = makeMatch();
|
const match = makeMatch();
|
||||||
|
const redUserId = new mongoose.Types.ObjectId();
|
||||||
|
match.participants.push({
|
||||||
|
userId: redUserId,
|
||||||
|
puuid: 'puuid-2',
|
||||||
|
gameName: 'Opponent',
|
||||||
|
profileIconId: 8,
|
||||||
|
});
|
||||||
|
match.teams[1].members.push({ userId: redUserId, assignedPosition: 'TOP' });
|
||||||
|
match.result?.games[0].participants.push({
|
||||||
|
userId: redUserId,
|
||||||
|
teamIndex: 2,
|
||||||
|
side: 'red',
|
||||||
|
championId: 24,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 3,
|
||||||
|
assists: 0,
|
||||||
|
win: false,
|
||||||
|
});
|
||||||
const raw = {
|
const raw = {
|
||||||
metadata: {
|
metadata: {
|
||||||
dataVersion: '2',
|
dataVersion: '2',
|
||||||
@@ -206,6 +224,51 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
],
|
],
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
raw.info.participants.push(
|
||||||
|
{
|
||||||
|
...raw.info.participants[0],
|
||||||
|
assists: 0,
|
||||||
|
championId: 24,
|
||||||
|
championName: 'Jax',
|
||||||
|
deaths: 3,
|
||||||
|
kills: 1,
|
||||||
|
participantId: 2,
|
||||||
|
puuid: 'puuid-2',
|
||||||
|
riotIdGameName: 'Opponent',
|
||||||
|
summonerId: 'summoner-2',
|
||||||
|
summonerName: 'Opponent',
|
||||||
|
teamId: 200,
|
||||||
|
win: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...raw.info.participants[0],
|
||||||
|
assists: 2,
|
||||||
|
championId: 64,
|
||||||
|
championName: 'LeeSin',
|
||||||
|
deaths: 0,
|
||||||
|
kills: 1,
|
||||||
|
participantId: 3,
|
||||||
|
puuid: 'puuid-3',
|
||||||
|
riotIdGameName: 'Jungler',
|
||||||
|
summonerId: 'summoner-3',
|
||||||
|
summonerName: 'Jungler',
|
||||||
|
teamId: 100,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
raw.info.teams.push({
|
||||||
|
bans: [],
|
||||||
|
objectives: {
|
||||||
|
baron: { first: false, kills: 0 },
|
||||||
|
champion: { first: false, kills: 3 },
|
||||||
|
dragon: { first: false, kills: 0 },
|
||||||
|
horde: { first: false, kills: 0 },
|
||||||
|
inhibitor: { first: false, kills: 0 },
|
||||||
|
riftHerald: { first: false, kills: 0 },
|
||||||
|
tower: { first: false, kills: 0 },
|
||||||
|
},
|
||||||
|
teamId: 200,
|
||||||
|
win: false,
|
||||||
|
});
|
||||||
const timeline = {
|
const timeline = {
|
||||||
metadata: {
|
metadata: {
|
||||||
dataVersion: '2',
|
dataVersion: '2',
|
||||||
@@ -218,7 +281,20 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
{
|
{
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
participantFrames: {
|
participantFrames: {
|
||||||
'1': { participantId: 1, totalGold: 500, xp: 0 },
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 500,
|
||||||
|
xp: 0,
|
||||||
|
minionsKilled: 0,
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
},
|
||||||
|
'2': {
|
||||||
|
participantId: 2,
|
||||||
|
totalGold: 500,
|
||||||
|
xp: 0,
|
||||||
|
minionsKilled: 0,
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -291,7 +367,137 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
},
|
},
|
||||||
],
|
],
|
||||||
participantFrames: {
|
participantFrames: {
|
||||||
'1': { participantId: 1, totalGold: 1_150, xp: 550 },
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 1_150,
|
||||||
|
xp: 550,
|
||||||
|
minionsKilled: 5,
|
||||||
|
jungleMinionsKilled: 1,
|
||||||
|
},
|
||||||
|
'2': {
|
||||||
|
participantId: 2,
|
||||||
|
totalGold: 1_050,
|
||||||
|
xp: 500,
|
||||||
|
minionsKilled: 4,
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 540_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 300_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 2,
|
||||||
|
assistingParticipantIds: [3],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 400_000,
|
||||||
|
killerId: 0,
|
||||||
|
victimId: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'BUILDING_KILL',
|
||||||
|
timestamp: 450_000,
|
||||||
|
killerId: 0,
|
||||||
|
teamId: 200,
|
||||||
|
buildingType: 'TOWER_BUILDING',
|
||||||
|
towerType: 'OUTER_TURRET',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'BUILDING_KILL',
|
||||||
|
timestamp: 450_000,
|
||||||
|
killerId: 1,
|
||||||
|
teamId: 200,
|
||||||
|
buildingType: 'INHIBITOR_BUILDING',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 500_000,
|
||||||
|
killerId: 3,
|
||||||
|
victimId: 2,
|
||||||
|
assistingParticipantIds: [1],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 4_900,
|
||||||
|
xp: 3_900,
|
||||||
|
minionsKilled: 72,
|
||||||
|
jungleMinionsKilled: 8,
|
||||||
|
},
|
||||||
|
'2': {
|
||||||
|
participantId: 2,
|
||||||
|
totalGold: 4_300,
|
||||||
|
xp: 3_500,
|
||||||
|
minionsKilled: 68,
|
||||||
|
jungleMinionsKilled: 2,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 590_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 5_200,
|
||||||
|
xp: 4_200,
|
||||||
|
minionsKilled: 80,
|
||||||
|
jungleMinionsKilled: 10,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 900_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 900_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: 2,
|
||||||
|
assistingParticipantIds: [3],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 8_100,
|
||||||
|
xp: 7_300,
|
||||||
|
minionsKilled: 130,
|
||||||
|
jungleMinionsKilled: 15,
|
||||||
|
},
|
||||||
|
'2': {
|
||||||
|
participantId: 2,
|
||||||
|
totalGold: 6_700,
|
||||||
|
xp: 6_100,
|
||||||
|
minionsKilled: 115,
|
||||||
|
jungleMinionsKilled: 5,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 1_800_000,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 12_500,
|
||||||
|
xp: 14_000,
|
||||||
|
minionsKilled: 205,
|
||||||
|
jungleMinionsKilled: 23,
|
||||||
|
},
|
||||||
|
'2': {
|
||||||
|
participantId: 2,
|
||||||
|
totalGold: 10_200,
|
||||||
|
xp: 12_700,
|
||||||
|
minionsKilled: 190,
|
||||||
|
jungleMinionsKilled: 10,
|
||||||
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -329,19 +535,105 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
{
|
{
|
||||||
timestamp: 0,
|
timestamp: 0,
|
||||||
blue: { gold: 500, xp: 0 },
|
blue: { gold: 500, xp: 0 },
|
||||||
red: { gold: 0, xp: 0 },
|
red: { gold: 500, xp: 0 },
|
||||||
goldDiff: 500,
|
goldDiff: 0,
|
||||||
xpDiff: 0,
|
xpDiff: 0,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
timestamp: 60,
|
timestamp: 60,
|
||||||
blue: { gold: 1_150, xp: 550 },
|
blue: { gold: 1_150, xp: 550 },
|
||||||
|
red: { gold: 1_050, xp: 500 },
|
||||||
|
goldDiff: 100,
|
||||||
|
xpDiff: 50,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 540,
|
||||||
|
blue: { gold: 4_900, xp: 3_900 },
|
||||||
|
red: { gold: 4_300, xp: 3_500 },
|
||||||
|
goldDiff: 600,
|
||||||
|
xpDiff: 400,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 590,
|
||||||
|
blue: { gold: 5_200, xp: 4_200 },
|
||||||
red: { gold: 0, xp: 0 },
|
red: { gold: 0, xp: 0 },
|
||||||
goldDiff: 1_150,
|
goldDiff: 5_200,
|
||||||
xpDiff: 550,
|
xpDiff: 4_200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 900,
|
||||||
|
blue: { gold: 8_100, xp: 7_300 },
|
||||||
|
red: { gold: 6_700, xp: 6_100 },
|
||||||
|
goldDiff: 1_400,
|
||||||
|
xpDiff: 1_200,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 1_800,
|
||||||
|
blue: { gold: 12_500, xp: 14_000 },
|
||||||
|
red: { gold: 10_200, xp: 12_700 },
|
||||||
|
goldDiff: 2_300,
|
||||||
|
xpDiff: 1_300,
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
expect(fragment.gameDetails[0].timelineEvents).toEqual([
|
||||||
|
{
|
||||||
|
timestamp: 20,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'dragon',
|
||||||
|
monsterSubType: 'FIRE_DRAGON',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 30,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'elderDragon',
|
||||||
|
monsterSubType: 'ELDER_DRAGON',
|
||||||
|
},
|
||||||
|
{ timestamp: 40, side: 'blue', type: 'voidGrub' },
|
||||||
|
{ timestamp: 50, side: 'blue', type: 'baron' },
|
||||||
|
{ timestamp: 55, side: 'blue', type: 'riftHerald' },
|
||||||
|
{
|
||||||
|
timestamp: 300,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'championKill',
|
||||||
|
killerParticipantId: 1,
|
||||||
|
victimParticipantId: 2,
|
||||||
|
assistingParticipantIds: [3],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 400,
|
||||||
|
type: 'championKill',
|
||||||
|
victimParticipantId: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 450,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'tower',
|
||||||
|
towerType: 'OUTER_TURRET',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 450,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'inhibitor',
|
||||||
|
killerParticipantId: 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 500,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'championKill',
|
||||||
|
killerParticipantId: 3,
|
||||||
|
victimParticipantId: 2,
|
||||||
|
assistingParticipantIds: [1],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 900,
|
||||||
|
side: 'blue',
|
||||||
|
type: 'championKill',
|
||||||
|
killerParticipantId: 1,
|
||||||
|
victimParticipantId: 2,
|
||||||
|
assistingParticipantIds: [3],
|
||||||
|
},
|
||||||
|
]);
|
||||||
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
|
expect(fragment.gameDetails[0].teams[0].bans).toEqual([
|
||||||
{ championId: 14, pickTurn: 1 },
|
{ championId: 14, pickTurn: 1 },
|
||||||
{ championId: 43, pickTurn: 2 },
|
{ championId: 43, pickTurn: 2 },
|
||||||
@@ -356,6 +648,27 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
voidGrub: 1,
|
voidGrub: 1,
|
||||||
});
|
});
|
||||||
expect(fragment.records[0]).toMatchObject({
|
expect(fragment.records[0]).toMatchObject({
|
||||||
|
participantId: 1,
|
||||||
|
checkpoints: {
|
||||||
|
at10: {
|
||||||
|
timestamp: 590,
|
||||||
|
gold: 5_200,
|
||||||
|
cs: 90,
|
||||||
|
xp: 4_200,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
},
|
||||||
|
at15: {
|
||||||
|
timestamp: 900,
|
||||||
|
gold: 8_100,
|
||||||
|
cs: 145,
|
||||||
|
xp: 7_300,
|
||||||
|
kills: 2,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
championLevel: 15,
|
championLevel: 15,
|
||||||
cs: 228,
|
cs: 228,
|
||||||
damageDealtToChampions: 18_765,
|
damageDealtToChampions: 18_765,
|
||||||
@@ -392,5 +705,118 @@ describe('MatchStatsFragmentBuilder', () => {
|
|||||||
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
|
{ timestamp: 45, skillSlot: 3, level: 2, levelUpType: 'NORMAL' },
|
||||||
],
|
],
|
||||||
});
|
});
|
||||||
|
expect(fragment.records[1]).toMatchObject({
|
||||||
|
participantId: 2,
|
||||||
|
checkpoints: {
|
||||||
|
at15: {
|
||||||
|
timestamp: 900,
|
||||||
|
gold: 6_700,
|
||||||
|
cs: 120,
|
||||||
|
xp: 6_100,
|
||||||
|
kills: 0,
|
||||||
|
deaths: 3,
|
||||||
|
assists: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
expect(fragment.records[1].checkpoints).not.toHaveProperty('at10');
|
||||||
|
|
||||||
|
const timelineWithoutEvents = {
|
||||||
|
...timeline,
|
||||||
|
info: {
|
||||||
|
...timeline.info,
|
||||||
|
frames: timeline.info.frames.map((frame) => ({
|
||||||
|
...frame,
|
||||||
|
events: [],
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
} as RiotMatchTimelineDto;
|
||||||
|
const objectiveFallback = builder.buildFragment({
|
||||||
|
match,
|
||||||
|
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
|
||||||
|
timelineByRiotMatchId: new Map([['KR_1', timelineWithoutEvents]]),
|
||||||
|
});
|
||||||
|
expect(objectiveFallback.gameDetails[0].teams[0].objectives).toMatchObject({
|
||||||
|
baron: 1,
|
||||||
|
dragon: 2,
|
||||||
|
elderDragon: 0,
|
||||||
|
riftHerald: 0,
|
||||||
|
voidGrub: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
const dragonOnlyTimeline = {
|
||||||
|
...timeline,
|
||||||
|
info: {
|
||||||
|
...timeline.info,
|
||||||
|
frames: timeline.info.frames.map((frame) => ({
|
||||||
|
...frame,
|
||||||
|
events: (frame.events ?? []).filter(
|
||||||
|
(event) =>
|
||||||
|
event.type !== 'ELITE_MONSTER_KILL' ||
|
||||||
|
event.monsterType === 'DRAGON',
|
||||||
|
),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
} as RiotMatchTimelineDto;
|
||||||
|
const partialObjectiveFallback = builder.buildFragment({
|
||||||
|
match,
|
||||||
|
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
|
||||||
|
timelineByRiotMatchId: new Map([['KR_1', dragonOnlyTimeline]]),
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
partialObjectiveFallback.gameDetails[0].teams[0].objectives,
|
||||||
|
).toMatchObject({
|
||||||
|
baron: 1,
|
||||||
|
dragon: 1,
|
||||||
|
elderDragon: 1,
|
||||||
|
riftHerald: 0,
|
||||||
|
voidGrub: 3,
|
||||||
|
});
|
||||||
|
|
||||||
|
const shortMatch = {
|
||||||
|
...match,
|
||||||
|
result: {
|
||||||
|
...match.result!,
|
||||||
|
games: match.result!.games.map((game) => ({
|
||||||
|
...game,
|
||||||
|
gameDuration: 599,
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
} as MatchDocument;
|
||||||
|
const shortFragment = builder.buildFragment({
|
||||||
|
match: shortMatch,
|
||||||
|
rawByRiotMatchId: new Map([
|
||||||
|
[
|
||||||
|
'KR_1',
|
||||||
|
{
|
||||||
|
...raw,
|
||||||
|
info: { ...raw.info, gameDuration: 599 },
|
||||||
|
} as RiotMatchDto,
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
timelineByRiotMatchId: new Map([
|
||||||
|
['KR_1', timeline as RiotMatchTimelineDto],
|
||||||
|
]),
|
||||||
|
});
|
||||||
|
expect(
|
||||||
|
shortFragment.records.every((record) => record.checkpoints === undefined),
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
const invalidIntervalTimeline = {
|
||||||
|
...timeline,
|
||||||
|
info: { ...timeline.info, frameInterval: Number.NaN },
|
||||||
|
} as RiotMatchTimelineDto;
|
||||||
|
const invalidIntervalFragment = builder.buildFragment({
|
||||||
|
match,
|
||||||
|
rawByRiotMatchId: new Map([['KR_1', raw as RiotMatchDto]]),
|
||||||
|
timelineByRiotMatchId: new Map([['KR_1', invalidIntervalTimeline]]),
|
||||||
|
});
|
||||||
|
expect(invalidIntervalFragment.gameDetails[0].timelineLoaded).toBe(false);
|
||||||
|
expect(invalidIntervalFragment.gameDetails[0].timeline).toEqual([]);
|
||||||
|
expect(
|
||||||
|
invalidIntervalFragment.records.every(
|
||||||
|
(record) => record.checkpoints === undefined,
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -3,10 +3,13 @@ import mongoose from 'mongoose';
|
|||||||
import type {
|
import type {
|
||||||
MatchDocument,
|
MatchDocument,
|
||||||
MatchGameResultParticipant,
|
MatchGameResultParticipant,
|
||||||
|
MatchStatsCheckpoint,
|
||||||
MatchStatsItemBuildEvent,
|
MatchStatsItemBuildEvent,
|
||||||
MatchStatsObjectiveEvent,
|
MatchStatsObjectiveEvent,
|
||||||
MatchStatsObjectiveSummary,
|
MatchStatsObjectiveSummary,
|
||||||
|
MatchStatsParticipantCheckpoints,
|
||||||
MatchStatsSkillBuildEvent,
|
MatchStatsSkillBuildEvent,
|
||||||
|
MatchStatsTimelineEvent,
|
||||||
MatchStatsTimelinePoint,
|
MatchStatsTimelinePoint,
|
||||||
TeamSide,
|
TeamSide,
|
||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
@@ -27,13 +30,17 @@ interface ParticipantBuildEvents {
|
|||||||
skills: MatchStatsSkillBuildEvent[];
|
skills: MatchStatsSkillBuildEvent[];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface TimelineProjection {
|
||||||
|
objectiveEvents: MatchStatsObjectiveEvent[];
|
||||||
|
timelineEvents: MatchStatsTimelineEvent[];
|
||||||
|
}
|
||||||
|
|
||||||
@Injectable()
|
@Injectable()
|
||||||
export class MatchStatsFragmentBuilder {
|
export class MatchStatsFragmentBuilder {
|
||||||
public buildFragment(params: {
|
public buildFragment(params: {
|
||||||
match: MatchDocument;
|
match: MatchDocument;
|
||||||
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
rawByRiotMatchId: Map<string, RiotMatchDto>;
|
||||||
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
|
timelineByRiotMatchId?: Map<string, RiotMatchTimelineDto>;
|
||||||
timelineLoadAttempted?: boolean;
|
|
||||||
}): MatchStatsFragment {
|
}): MatchStatsFragment {
|
||||||
const games = [...(params.match.result?.games ?? [])].sort(
|
const games = [...(params.match.result?.games ?? [])].sort(
|
||||||
(left, right) => left.gameNumber - right.gameNumber,
|
(left, right) => left.gameNumber - right.gameNumber,
|
||||||
@@ -43,13 +50,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
const raw = params.rawByRiotMatchId.get(game.riotMatchId);
|
||||||
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
|
const timeline = params.timelineByRiotMatchId?.get(game.riotMatchId);
|
||||||
return raw
|
return raw
|
||||||
? this.toGameDetail(
|
? this.toGameDetail(params.match, game, raw, timeline)
|
||||||
params.match,
|
|
||||||
game,
|
|
||||||
raw,
|
|
||||||
timeline,
|
|
||||||
params.timelineLoadAttempted === true,
|
|
||||||
)
|
|
||||||
: this.toFallbackGameDetail(params.match, game);
|
: this.toFallbackGameDetail(params.match, game);
|
||||||
});
|
});
|
||||||
const records = gameDetails.flatMap((detail) =>
|
const records = gameDetails.flatMap((detail) =>
|
||||||
@@ -130,8 +131,10 @@ export class MatchStatsFragmentBuilder {
|
|||||||
game: NonNullable<MatchDocument['result']>['games'][number],
|
game: NonNullable<MatchDocument['result']>['games'][number],
|
||||||
raw: RiotMatchDto,
|
raw: RiotMatchDto,
|
||||||
timeline?: RiotMatchTimelineDto,
|
timeline?: RiotMatchTimelineDto,
|
||||||
timelineLoadAttempted = false,
|
|
||||||
): InternalGameDetail {
|
): InternalGameDetail {
|
||||||
|
const usableTimeline = isUsableTimeline(timeline, raw.info.gameDuration)
|
||||||
|
? timeline
|
||||||
|
: undefined;
|
||||||
const puuidByUserId = new Map(
|
const puuidByUserId = new Map(
|
||||||
match.participants
|
match.participants
|
||||||
.filter((participant) => participant.puuid)
|
.filter((participant) => participant.puuid)
|
||||||
@@ -158,14 +161,18 @@ export class MatchStatsFragmentBuilder {
|
|||||||
raw,
|
raw,
|
||||||
rawTeamIdBySide,
|
rawTeamIdBySide,
|
||||||
);
|
);
|
||||||
const objectiveEvents = this.toObjectiveEvents(
|
const { objectiveEvents, timelineEvents } = this.toTimelineEvents(
|
||||||
timeline,
|
usableTimeline,
|
||||||
rawTeamIdBySide,
|
rawTeamIdBySide,
|
||||||
sideByParticipantId,
|
sideByParticipantId,
|
||||||
);
|
);
|
||||||
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
|
const timelineObjectives = this.toTimelineObjectives(objectiveEvents);
|
||||||
const buildEventsByParticipantId =
|
const buildEventsByParticipantId =
|
||||||
this.toBuildEventsByParticipantId(timeline);
|
this.toBuildEventsByParticipantId(usableTimeline);
|
||||||
|
const checkpointsByParticipantId = this.toCheckpointsByParticipantId(
|
||||||
|
usableTimeline,
|
||||||
|
raw.info.gameDuration,
|
||||||
|
);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
gameNumber: game.gameNumber,
|
gameNumber: game.gameNumber,
|
||||||
@@ -174,9 +181,10 @@ export class MatchStatsFragmentBuilder {
|
|||||||
gameDuration: game.gameDuration,
|
gameDuration: game.gameDuration,
|
||||||
gameVersion: raw.info.gameVersion,
|
gameVersion: raw.info.gameVersion,
|
||||||
winnerSide: game.winnerSide,
|
winnerSide: game.winnerSide,
|
||||||
timeline: this.toTimeline(raw, rawTeamIdBySide, timeline),
|
timeline: this.toTimeline(raw, rawTeamIdBySide, usableTimeline),
|
||||||
timelineLoaded: timelineLoadAttempted || Boolean(timeline),
|
timelineLoaded: Boolean(usableTimeline),
|
||||||
objectiveEvents,
|
objectiveEvents,
|
||||||
|
timelineEvents,
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => {
|
||||||
const teamIndex =
|
const teamIndex =
|
||||||
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
side === 'blue' ? game.blueTeamIndex : game.redTeamIndex;
|
||||||
@@ -202,7 +210,6 @@ export class MatchStatsFragmentBuilder {
|
|||||||
objectives: this.toObjectiveSummary(
|
objectives: this.toObjectiveSummary(
|
||||||
rawTeam,
|
rawTeam,
|
||||||
timelineObjectives.get(side),
|
timelineObjectives.get(side),
|
||||||
Boolean(timeline),
|
|
||||||
),
|
),
|
||||||
bans: (rawTeam?.bans ?? []).map((ban) => ({
|
bans: (rawTeam?.bans ?? []).map((ban) => ({
|
||||||
championId: ban.championId,
|
championId: ban.championId,
|
||||||
@@ -224,6 +231,9 @@ export class MatchStatsFragmentBuilder {
|
|||||||
rawParticipant.participantId,
|
rawParticipant.participantId,
|
||||||
)
|
)
|
||||||
: undefined,
|
: undefined,
|
||||||
|
checkpoints: rawParticipant
|
||||||
|
? checkpointsByParticipantId.get(rawParticipant.participantId)
|
||||||
|
: undefined,
|
||||||
teamKills,
|
teamKills,
|
||||||
teamDamage,
|
teamDamage,
|
||||||
});
|
});
|
||||||
@@ -246,6 +256,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
timeline: [],
|
timeline: [],
|
||||||
timelineLoaded: false,
|
timelineLoaded: false,
|
||||||
objectiveEvents: [],
|
objectiveEvents: [],
|
||||||
|
timelineEvents: [],
|
||||||
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
teams: (['blue', 'red'] as TeamSide[]).map((side) => ({
|
||||||
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
teamIndex: side === 'blue' ? game.blueTeamIndex : game.redTeamIndex,
|
||||||
side,
|
side,
|
||||||
@@ -273,6 +284,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant: MatchGameResultParticipant;
|
participant: MatchGameResultParticipant;
|
||||||
rawParticipant?: RiotMatchParticipantDto;
|
rawParticipant?: RiotMatchParticipantDto;
|
||||||
buildEvents?: ParticipantBuildEvents;
|
buildEvents?: ParticipantBuildEvents;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
teamKills: number;
|
teamKills: number;
|
||||||
teamDamage: number;
|
teamDamage: number;
|
||||||
}): InternalRecord {
|
}): InternalRecord {
|
||||||
@@ -282,6 +294,7 @@ export class MatchStatsFragmentBuilder {
|
|||||||
participant,
|
participant,
|
||||||
rawParticipant,
|
rawParticipant,
|
||||||
buildEvents,
|
buildEvents,
|
||||||
|
checkpoints,
|
||||||
teamKills,
|
teamKills,
|
||||||
teamDamage,
|
teamDamage,
|
||||||
} = params;
|
} = params;
|
||||||
@@ -319,6 +332,8 @@ export class MatchStatsFragmentBuilder {
|
|||||||
riotMatchId: game.riotMatchId,
|
riotMatchId: game.riotMatchId,
|
||||||
gameCreation: game.gameCreation,
|
gameCreation: game.gameCreation,
|
||||||
gameDuration: game.gameDuration,
|
gameDuration: game.gameDuration,
|
||||||
|
participantId: rawParticipant?.participantId,
|
||||||
|
checkpoints,
|
||||||
userId: participant.userId.toString(),
|
userId: participant.userId.toString(),
|
||||||
summonerName:
|
summonerName:
|
||||||
snapshot?.gameName ??
|
snapshot?.gameName ??
|
||||||
@@ -455,6 +470,107 @@ export class MatchStatsFragmentBuilder {
|
|||||||
return buildEventsByParticipantId;
|
return buildEventsByParticipantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private toCheckpointsByParticipantId(
|
||||||
|
timeline: RiotMatchTimelineDto | undefined,
|
||||||
|
gameDurationSeconds: number,
|
||||||
|
): Map<number, MatchStatsParticipantCheckpoints> {
|
||||||
|
const checkpointsByParticipantId = new Map<
|
||||||
|
number,
|
||||||
|
MatchStatsParticipantCheckpoints
|
||||||
|
>();
|
||||||
|
if (
|
||||||
|
!timeline?.info.frames.length ||
|
||||||
|
!Number.isFinite(timeline.info.frameInterval) ||
|
||||||
|
timeline.info.frameInterval <= 0
|
||||||
|
) {
|
||||||
|
return checkpointsByParticipantId;
|
||||||
|
}
|
||||||
|
|
||||||
|
const participantIds = new Set<number>();
|
||||||
|
const championKillEvents = timeline.info.frames.flatMap((frame) =>
|
||||||
|
(frame.events ?? []).filter((event) => event.type === 'CHAMPION_KILL'),
|
||||||
|
);
|
||||||
|
for (const frame of timeline.info.frames) {
|
||||||
|
for (const participantFrame of Object.values(frame.participantFrames)) {
|
||||||
|
participantIds.add(participantFrame.participantId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const targets = [
|
||||||
|
['at10', 600_000],
|
||||||
|
['at15', 900_000],
|
||||||
|
] as const;
|
||||||
|
for (const participantId of participantIds) {
|
||||||
|
const checkpoints: MatchStatsParticipantCheckpoints = {};
|
||||||
|
for (const [key, targetTimestamp] of targets) {
|
||||||
|
if (gameDurationSeconds * 1_000 < targetTimestamp) continue;
|
||||||
|
|
||||||
|
const selectedFrame = timeline.info.frames.reduce<
|
||||||
|
RiotMatchTimelineDto['info']['frames'][number] | undefined
|
||||||
|
>((latest, frame) => {
|
||||||
|
if (
|
||||||
|
frame.timestamp > targetTimestamp ||
|
||||||
|
!Object.values(frame.participantFrames).some(
|
||||||
|
(participantFrame) =>
|
||||||
|
participantFrame.participantId === participantId,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return latest;
|
||||||
|
}
|
||||||
|
return !latest || frame.timestamp > latest.timestamp ? frame : latest;
|
||||||
|
}, undefined);
|
||||||
|
if (
|
||||||
|
!selectedFrame ||
|
||||||
|
targetTimestamp - selectedFrame.timestamp >=
|
||||||
|
timeline.info.frameInterval
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const participantFrame = Object.values(
|
||||||
|
selectedFrame.participantFrames,
|
||||||
|
).find((frame) => frame.participantId === participantId);
|
||||||
|
if (
|
||||||
|
!participantFrame ||
|
||||||
|
typeof participantFrame.minionsKilled !== 'number' ||
|
||||||
|
!Number.isFinite(participantFrame.minionsKilled) ||
|
||||||
|
typeof participantFrame.jungleMinionsKilled !== 'number' ||
|
||||||
|
!Number.isFinite(participantFrame.jungleMinionsKilled)
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const checkpoint: MatchStatsCheckpoint = {
|
||||||
|
timestamp: Math.max(0, Math.round(selectedFrame.timestamp / 1_000)),
|
||||||
|
gold: participantFrame.totalGold,
|
||||||
|
cs:
|
||||||
|
participantFrame.minionsKilled +
|
||||||
|
participantFrame.jungleMinionsKilled,
|
||||||
|
xp: participantFrame.xp,
|
||||||
|
kills: 0,
|
||||||
|
deaths: 0,
|
||||||
|
assists: 0,
|
||||||
|
};
|
||||||
|
for (const event of championKillEvents) {
|
||||||
|
if (event.timestamp > selectedFrame.timestamp) continue;
|
||||||
|
if (event.killerId === participantId && event.killerId > 0) {
|
||||||
|
checkpoint.kills += 1;
|
||||||
|
}
|
||||||
|
if (event.victimId === participantId) checkpoint.deaths += 1;
|
||||||
|
if (event.assistingParticipantIds?.includes(participantId)) {
|
||||||
|
checkpoint.assists += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
checkpoints[key] = checkpoint;
|
||||||
|
}
|
||||||
|
if (checkpoints.at10 || checkpoints.at15) {
|
||||||
|
checkpointsByParticipantId.set(participantId, checkpoints);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return checkpointsByParticipantId;
|
||||||
|
}
|
||||||
|
|
||||||
private toTimeline(
|
private toTimeline(
|
||||||
raw: RiotMatchDto,
|
raw: RiotMatchDto,
|
||||||
rawTeamIdBySide: Map<TeamSide, number>,
|
rawTeamIdBySide: Map<TeamSide, number>,
|
||||||
@@ -511,65 +627,124 @@ export class MatchStatsFragmentBuilder {
|
|||||||
return sideByParticipantId;
|
return sideByParticipantId;
|
||||||
}
|
}
|
||||||
|
|
||||||
private toObjectiveEvents(
|
private toTimelineEvents(
|
||||||
timeline: RiotMatchTimelineDto | undefined,
|
timeline: RiotMatchTimelineDto | undefined,
|
||||||
rawTeamIdBySide: Map<TeamSide, number>,
|
rawTeamIdBySide: Map<TeamSide, number>,
|
||||||
sideByParticipantId: Map<number, TeamSide>,
|
sideByParticipantId: Map<number, TeamSide>,
|
||||||
): MatchStatsObjectiveEvent[] {
|
): TimelineProjection {
|
||||||
if (!timeline?.info.frames.length) return [];
|
if (!timeline?.info.frames.length) {
|
||||||
|
return { objectiveEvents: [], timelineEvents: [] };
|
||||||
|
}
|
||||||
|
|
||||||
const sideByTeamId = new Map<number, TeamSide>();
|
const sideByTeamId = new Map<number, TeamSide>();
|
||||||
for (const [side, teamId] of rawTeamIdBySide.entries()) {
|
for (const [side, teamId] of rawTeamIdBySide.entries()) {
|
||||||
sideByTeamId.set(teamId, side);
|
sideByTeamId.set(teamId, side);
|
||||||
}
|
}
|
||||||
|
|
||||||
const objectiveEvents: MatchStatsObjectiveEvent[] = [];
|
const projected: Array<{
|
||||||
|
sourceSequence: number;
|
||||||
|
event: MatchStatsTimelineEvent;
|
||||||
|
}> = [];
|
||||||
|
let sourceSequence = 0;
|
||||||
for (const frame of timeline.info.frames) {
|
for (const frame of timeline.info.frames) {
|
||||||
for (const event of frame.events ?? []) {
|
for (const event of frame.events ?? []) {
|
||||||
if (event.type !== 'ELITE_MONSTER_KILL') continue;
|
const currentSequence = sourceSequence;
|
||||||
const side =
|
sourceSequence += 1;
|
||||||
(typeof event.killerTeamId === 'number'
|
|
||||||
? sideByTeamId.get(event.killerTeamId)
|
|
||||||
: undefined) ??
|
|
||||||
(typeof event.killerId === 'number'
|
|
||||||
? sideByParticipantId.get(event.killerId)
|
|
||||||
: undefined);
|
|
||||||
if (!side) continue;
|
|
||||||
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
|
const timestamp = Math.max(0, Math.round(event.timestamp / 1000));
|
||||||
switch (event.monsterType) {
|
if (event.type === 'ELITE_MONSTER_KILL') {
|
||||||
case 'BARON_NASHOR':
|
const side =
|
||||||
objectiveEvents.push({ timestamp, side, type: 'baron' });
|
(typeof event.killerTeamId === 'number'
|
||||||
break;
|
? sideByTeamId.get(event.killerTeamId)
|
||||||
case 'RIFTHERALD':
|
: undefined) ??
|
||||||
objectiveEvents.push({ timestamp, side, type: 'riftHerald' });
|
(typeof event.killerId === 'number'
|
||||||
break;
|
? sideByParticipantId.get(event.killerId)
|
||||||
case 'HORDE':
|
: undefined);
|
||||||
objectiveEvents.push({ timestamp, side, type: 'voidGrub' });
|
if (!side) continue;
|
||||||
break;
|
const objectiveEvent = toObjectiveTimelineEvent({
|
||||||
case 'DRAGON':
|
timestamp,
|
||||||
if (event.monsterSubType === 'ELDER_DRAGON') {
|
side,
|
||||||
objectiveEvents.push({
|
monsterType: event.monsterType,
|
||||||
timestamp,
|
monsterSubType: event.monsterSubType,
|
||||||
side,
|
});
|
||||||
type: 'elderDragon',
|
if (objectiveEvent) {
|
||||||
monsterSubType: event.monsterSubType,
|
projected.push({
|
||||||
});
|
sourceSequence: currentSequence,
|
||||||
} else {
|
event: objectiveEvent,
|
||||||
objectiveEvents.push({
|
});
|
||||||
timestamp,
|
}
|
||||||
side,
|
continue;
|
||||||
type: 'dragon',
|
|
||||||
monsterSubType: event.monsterSubType,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
break;
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (event.type === 'CHAMPION_KILL') {
|
||||||
|
const side =
|
||||||
|
typeof event.killerId === 'number' && event.killerId > 0
|
||||||
|
? sideByParticipantId.get(event.killerId)
|
||||||
|
: undefined;
|
||||||
|
projected.push({
|
||||||
|
sourceSequence: currentSequence,
|
||||||
|
event: {
|
||||||
|
timestamp,
|
||||||
|
type: 'championKill',
|
||||||
|
...(side ? { side } : {}),
|
||||||
|
...(typeof event.killerId === 'number' && event.killerId > 0
|
||||||
|
? { killerParticipantId: event.killerId }
|
||||||
|
: {}),
|
||||||
|
...(typeof event.victimId === 'number' && event.victimId > 0
|
||||||
|
? { victimParticipantId: event.victimId }
|
||||||
|
: {}),
|
||||||
|
...(event.assistingParticipantIds
|
||||||
|
? { assistingParticipantIds: event.assistingParticipantIds }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (event.type !== 'BUILDING_KILL') continue;
|
||||||
|
const destroyedSide =
|
||||||
|
typeof event.teamId === 'number'
|
||||||
|
? sideByTeamId.get(event.teamId)
|
||||||
|
: undefined;
|
||||||
|
const side =
|
||||||
|
(typeof event.killerId === 'number' && event.killerId > 0
|
||||||
|
? sideByParticipantId.get(event.killerId)
|
||||||
|
: undefined) ??
|
||||||
|
(destroyedSide ? oppositeSide(destroyedSide) : undefined);
|
||||||
|
const type =
|
||||||
|
event.buildingType === 'TOWER_BUILDING'
|
||||||
|
? 'tower'
|
||||||
|
: event.buildingType === 'INHIBITOR_BUILDING'
|
||||||
|
? 'inhibitor'
|
||||||
|
: undefined;
|
||||||
|
if (!side || !type) continue;
|
||||||
|
projected.push({
|
||||||
|
sourceSequence: currentSequence,
|
||||||
|
event: {
|
||||||
|
timestamp,
|
||||||
|
side,
|
||||||
|
type,
|
||||||
|
...(typeof event.killerId === 'number' && event.killerId > 0
|
||||||
|
? { killerParticipantId: event.killerId }
|
||||||
|
: {}),
|
||||||
|
...(type === 'tower' && event.towerType
|
||||||
|
? { towerType: event.towerType }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return objectiveEvents.sort((left, right) => left.timestamp - right.timestamp);
|
const timelineEvents = projected
|
||||||
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
left.event.timestamp - right.event.timestamp ||
|
||||||
|
left.sourceSequence - right.sourceSequence,
|
||||||
|
)
|
||||||
|
.map(({ event }) => event);
|
||||||
|
return {
|
||||||
|
timelineEvents,
|
||||||
|
objectiveEvents: timelineEvents.filter(isObjectiveTimelineEvent),
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private toTimelineObjectives(
|
private toTimelineObjectives(
|
||||||
@@ -608,29 +783,29 @@ export class MatchStatsFragmentBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private toObjectiveSummary(
|
private toObjectiveSummary(
|
||||||
rawTeam:
|
rawTeam: RiotMatchDto['info']['teams'][number] | undefined,
|
||||||
| RiotMatchDto['info']['teams'][number]
|
|
||||||
| undefined,
|
|
||||||
timelineObjectives: MatchStatsObjectiveSummary | undefined,
|
timelineObjectives: MatchStatsObjectiveSummary | undefined,
|
||||||
hasTimeline: boolean,
|
|
||||||
): MatchStatsObjectiveSummary {
|
): MatchStatsObjectiveSummary {
|
||||||
const rawObjectives = rawTeam?.objectives;
|
const rawObjectives = rawTeam?.objectives;
|
||||||
|
const timelineDragon = timelineObjectives?.dragon ?? 0;
|
||||||
|
const timelineElder = timelineObjectives?.elderDragon ?? 0;
|
||||||
|
const hasProjectedDragon = timelineDragon + timelineElder > 0;
|
||||||
return {
|
return {
|
||||||
tower: rawObjectives?.tower?.kills ?? 0,
|
tower: rawObjectives?.tower?.kills ?? 0,
|
||||||
dragon: hasTimeline
|
dragon: hasProjectedDragon
|
||||||
? (timelineObjectives?.dragon ?? 0)
|
? timelineDragon
|
||||||
: (rawObjectives?.dragon?.kills ?? 0),
|
: (rawObjectives?.dragon?.kills ?? 0),
|
||||||
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
inhibitor: rawObjectives?.inhibitor?.kills ?? 0,
|
||||||
baron: hasTimeline
|
baron: (timelineObjectives?.baron ?? 0) > 0
|
||||||
? (timelineObjectives?.baron ?? 0)
|
? (timelineObjectives?.baron ?? 0)
|
||||||
: (rawObjectives?.baron?.kills ?? 0),
|
: (rawObjectives?.baron?.kills ?? 0),
|
||||||
riftHerald: hasTimeline
|
riftHerald: (timelineObjectives?.riftHerald ?? 0) > 0
|
||||||
? (timelineObjectives?.riftHerald ?? 0)
|
? (timelineObjectives?.riftHerald ?? 0)
|
||||||
: (rawObjectives?.riftHerald?.kills ?? 0),
|
: (rawObjectives?.riftHerald?.kills ?? 0),
|
||||||
voidGrub: hasTimeline
|
voidGrub: (timelineObjectives?.voidGrub ?? 0) > 0
|
||||||
? (timelineObjectives?.voidGrub ?? 0)
|
? (timelineObjectives?.voidGrub ?? 0)
|
||||||
: (rawObjectives?.horde?.kills ?? 0),
|
: (rawObjectives?.horde?.kills ?? 0),
|
||||||
elderDragon: timelineObjectives?.elderDragon ?? 0,
|
elderDragon: hasProjectedDragon ? timelineElder : 0,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -687,6 +862,79 @@ function toItemBuildType(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function toObjectiveTimelineEvent(params: {
|
||||||
|
timestamp: number;
|
||||||
|
side: TeamSide;
|
||||||
|
monsterType?: string;
|
||||||
|
monsterSubType?: string;
|
||||||
|
}): MatchStatsObjectiveEvent | null {
|
||||||
|
switch (params.monsterType) {
|
||||||
|
case 'BARON_NASHOR':
|
||||||
|
return { timestamp: params.timestamp, side: params.side, type: 'baron' };
|
||||||
|
case 'RIFTHERALD':
|
||||||
|
return {
|
||||||
|
timestamp: params.timestamp,
|
||||||
|
side: params.side,
|
||||||
|
type: 'riftHerald',
|
||||||
|
};
|
||||||
|
case 'HORDE':
|
||||||
|
return {
|
||||||
|
timestamp: params.timestamp,
|
||||||
|
side: params.side,
|
||||||
|
type: 'voidGrub',
|
||||||
|
};
|
||||||
|
case 'DRAGON':
|
||||||
|
return {
|
||||||
|
timestamp: params.timestamp,
|
||||||
|
side: params.side,
|
||||||
|
type:
|
||||||
|
params.monsterSubType === 'ELDER_DRAGON' ? 'elderDragon' : 'dragon',
|
||||||
|
monsterSubType: params.monsterSubType,
|
||||||
|
};
|
||||||
|
default:
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isObjectiveTimelineEvent(
|
||||||
|
event: MatchStatsTimelineEvent,
|
||||||
|
): event is MatchStatsObjectiveEvent {
|
||||||
|
return (
|
||||||
|
event.type === 'dragon' ||
|
||||||
|
event.type === 'elderDragon' ||
|
||||||
|
event.type === 'baron' ||
|
||||||
|
event.type === 'riftHerald' ||
|
||||||
|
event.type === 'voidGrub'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function oppositeSide(side: TeamSide): TeamSide {
|
||||||
|
return side === 'blue' ? 'red' : 'blue';
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUsableTimeline(
|
||||||
|
timeline: RiotMatchTimelineDto | undefined,
|
||||||
|
gameDurationSeconds: number,
|
||||||
|
): timeline is RiotMatchTimelineDto {
|
||||||
|
if (
|
||||||
|
!timeline ||
|
||||||
|
!Number.isFinite(timeline.info.frameInterval) ||
|
||||||
|
timeline.info.frameInterval <= 0 ||
|
||||||
|
!Array.isArray(timeline.info.frames) ||
|
||||||
|
timeline.info.frames.length === 0
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const finalTimestamp = Math.max(
|
||||||
|
...timeline.info.frames.map((frame) => frame.timestamp),
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
Number.isFinite(finalTimestamp) &&
|
||||||
|
Math.abs(gameDurationSeconds * 1_000 - finalTimestamp) <
|
||||||
|
timeline.info.frameInterval
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function round(value: number): number {
|
function round(value: number): number {
|
||||||
return Math.round(value * 10) / 10;
|
return Math.round(value * 10) / 10;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { ConnectionService } from '../global/database/connection.service';
|
|||||||
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
import { MatchStatsFragmentBuilder } from './match-stats-fragment.builder';
|
||||||
import { MatchStatsRepository } from './match-stats.repository';
|
import { MatchStatsRepository } from './match-stats.repository';
|
||||||
import { MatchStatsService } from './match-stats.service';
|
import { MatchStatsService } from './match-stats.service';
|
||||||
|
import { MATCH_STATS_BUILDER_VERSION } from './match-stats.types';
|
||||||
|
|
||||||
describe('MatchStatsService', () => {
|
describe('MatchStatsService', () => {
|
||||||
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
it('deletes an existing fragment when the match is no longer eligible', async () => {
|
||||||
@@ -158,8 +159,10 @@ describe('MatchStatsService', () => {
|
|||||||
match,
|
match,
|
||||||
rawByRiotMatchId: expect.any(Map),
|
rawByRiotMatchId: expect.any(Map),
|
||||||
timelineByRiotMatchId: expect.any(Map),
|
timelineByRiotMatchId: expect.any(Map),
|
||||||
timelineLoadAttempted: false,
|
|
||||||
});
|
});
|
||||||
|
expect(
|
||||||
|
builder.buildFragment.mock.calls[0][0].timelineByRiotMatchId,
|
||||||
|
).toHaveProperty('size', 0);
|
||||||
expect(repository.upsert).toHaveBeenCalledWith(
|
expect(repository.upsert).toHaveBeenCalledWith(
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
matchId,
|
matchId,
|
||||||
@@ -167,11 +170,169 @@ describe('MatchStatsService', () => {
|
|||||||
scheduledAt,
|
scheduledAt,
|
||||||
gameCreationMin: 1_000,
|
gameCreationMin: 1_000,
|
||||||
gameCreationMax: 2_000,
|
gameCreationMax: 2_000,
|
||||||
builderVersion: 9,
|
builderVersion: MATCH_STATS_BUILDER_VERSION,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('retries unusable timeline caches and stores a later usable fetch', async () => {
|
||||||
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
|
const match = {
|
||||||
|
_id: matchId,
|
||||||
|
communityId,
|
||||||
|
scheduledAt: new Date('2026-05-03T00:00:00.000Z'),
|
||||||
|
status: 'finished',
|
||||||
|
result: { games: [{ riotMatchId: 'KR_1' }] },
|
||||||
|
};
|
||||||
|
const emptyTimeline = {
|
||||||
|
info: { frameInterval: 60_000, frames: [] },
|
||||||
|
};
|
||||||
|
const partialTimeline = {
|
||||||
|
info: {
|
||||||
|
frameInterval: 60_000,
|
||||||
|
frames: [{ timestamp: 0, events: [] }],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const nonPositiveTimeline = {
|
||||||
|
info: {
|
||||||
|
frameInterval: 0,
|
||||||
|
frames: [timelineFrame(120_000)],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const truncatedTimeline = {
|
||||||
|
info: {
|
||||||
|
frameInterval: 60_000,
|
||||||
|
frames: [timelineFrame()],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const usableTimeline = {
|
||||||
|
metadata: {
|
||||||
|
dataVersion: '2',
|
||||||
|
matchId: 'KR_1',
|
||||||
|
participants: ['puuid-1'],
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
frameInterval: 60_000,
|
||||||
|
frames: [timelineFrame(120_000)],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const cachedTimelines = [
|
||||||
|
emptyTimeline,
|
||||||
|
partialTimeline,
|
||||||
|
nonPositiveTimeline,
|
||||||
|
truncatedTimeline,
|
||||||
|
];
|
||||||
|
let buildIndex = 0;
|
||||||
|
const riotFind = jest.fn().mockImplementation(() => ({
|
||||||
|
lean: () => ({
|
||||||
|
exec: jest.fn().mockResolvedValue([
|
||||||
|
{
|
||||||
|
matchId: 'KR_1',
|
||||||
|
raw: { info: { gameDuration: 120 } },
|
||||||
|
timeline: cachedTimelines[Math.min(buildIndex++, 3)],
|
||||||
|
},
|
||||||
|
]),
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
const updateExec = jest.fn().mockResolvedValue(undefined);
|
||||||
|
let storedUpdate:
|
||||||
|
| {
|
||||||
|
filter: unknown;
|
||||||
|
update: { $set: { timeline: unknown; timelineFetchedAt: Date } };
|
||||||
|
}
|
||||||
|
| undefined;
|
||||||
|
const updateOne = jest.fn(
|
||||||
|
(
|
||||||
|
filter: unknown,
|
||||||
|
update: { $set: { timeline: unknown; timelineFetchedAt: Date } },
|
||||||
|
) => {
|
||||||
|
storedUpdate = { filter, update };
|
||||||
|
return { exec: updateExec };
|
||||||
|
},
|
||||||
|
);
|
||||||
|
const connectionService = {
|
||||||
|
getModel: jest.fn().mockImplementation((name: string) => {
|
||||||
|
if (name === 'match') {
|
||||||
|
return Promise.resolve({ findById: () => queryResult(match, false) });
|
||||||
|
}
|
||||||
|
if (name === 'competition') {
|
||||||
|
return Promise.resolve({ findOne: () => queryResult(null) });
|
||||||
|
}
|
||||||
|
if (name === 'riotMatch') {
|
||||||
|
return Promise.resolve({ find: riotFind, updateOne });
|
||||||
|
}
|
||||||
|
if (name === 'community') {
|
||||||
|
return Promise.resolve({
|
||||||
|
findById: () => ({
|
||||||
|
select: () => queryResult({ riotRegion: 'asia' }),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return Promise.reject(new Error(`Unexpected model: ${name}`));
|
||||||
|
}),
|
||||||
|
} as unknown as ConnectionService;
|
||||||
|
const repository = {
|
||||||
|
upsert: jest.fn().mockResolvedValue(undefined),
|
||||||
|
deleteByMatch: jest.fn(),
|
||||||
|
deleteLegacyByMatch: jest.fn(),
|
||||||
|
} as unknown as jest.Mocked<MatchStatsRepository>;
|
||||||
|
type BuildParams = Parameters<
|
||||||
|
MatchStatsFragmentBuilder['buildFragment']
|
||||||
|
>[0];
|
||||||
|
const buildCalls: BuildParams[] = [];
|
||||||
|
const builtFragment = {
|
||||||
|
matchCard: { matchId: matchId.toString() },
|
||||||
|
records: [],
|
||||||
|
gameDetails: [],
|
||||||
|
userIds: [],
|
||||||
|
championIds: [],
|
||||||
|
gameCreationMin: 1_000,
|
||||||
|
gameCreationMax: 2_000,
|
||||||
|
} as ReturnType<MatchStatsFragmentBuilder['buildFragment']>;
|
||||||
|
const buildFragment = jest.fn((params: BuildParams) => {
|
||||||
|
buildCalls.push(params);
|
||||||
|
return builtFragment;
|
||||||
|
});
|
||||||
|
const builder = {
|
||||||
|
buildFragment,
|
||||||
|
} as unknown as jest.Mocked<MatchStatsFragmentBuilder>;
|
||||||
|
const getMatchTimeline = jest
|
||||||
|
.fn()
|
||||||
|
.mockRejectedValueOnce(new Error('temporary Riot failure'))
|
||||||
|
.mockRejectedValueOnce(new Error('temporary Riot failure'))
|
||||||
|
.mockRejectedValueOnce(new Error('temporary Riot failure'))
|
||||||
|
.mockResolvedValueOnce(usableTimeline);
|
||||||
|
const service = new MatchStatsService(
|
||||||
|
connectionService,
|
||||||
|
repository,
|
||||||
|
builder,
|
||||||
|
{ getMatchTimeline } as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
await service.buildAndUpsert(matchId, { includeTimeline: true });
|
||||||
|
await service.buildAndUpsert(matchId, { includeTimeline: true });
|
||||||
|
await service.buildAndUpsert(matchId, { includeTimeline: true });
|
||||||
|
await service.buildAndUpsert(matchId, { includeTimeline: true });
|
||||||
|
|
||||||
|
expect(getMatchTimeline).toHaveBeenCalledTimes(4);
|
||||||
|
expect(buildFragment).toHaveBeenCalledTimes(4);
|
||||||
|
expect(buildCalls[0].timelineByRiotMatchId).toHaveProperty('size', 0);
|
||||||
|
expect(buildCalls[1].timelineByRiotMatchId).toHaveProperty('size', 0);
|
||||||
|
expect(buildCalls[2].timelineByRiotMatchId?.get('KR_1')).toBeUndefined();
|
||||||
|
expect(buildCalls[3].timelineByRiotMatchId?.get('KR_1')).toBe(
|
||||||
|
usableTimeline,
|
||||||
|
);
|
||||||
|
for (const call of buildCalls) {
|
||||||
|
expect(call).not.toHaveProperty('timelineLoadAttempted');
|
||||||
|
}
|
||||||
|
expect(updateOne).toHaveBeenCalledTimes(1);
|
||||||
|
expect(storedUpdate?.filter).toEqual({ matchId: 'KR_1' });
|
||||||
|
expect(storedUpdate?.update.$set.timeline).toBe(usableTimeline);
|
||||||
|
expect(storedUpdate?.update.$set.timelineFetchedAt).toBeInstanceOf(Date);
|
||||||
|
expect(updateExec).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
it('builds from the Competition projection and records its source revision', async () => {
|
it('builds from the Competition projection and records its source revision', async () => {
|
||||||
const matchId = new mongoose.Types.ObjectId();
|
const matchId = new mongoose.Types.ObjectId();
|
||||||
const communityId = new mongoose.Types.ObjectId();
|
const communityId = new mongoose.Types.ObjectId();
|
||||||
@@ -451,3 +612,19 @@ function queryResult<T>(value: T, lean = true) {
|
|||||||
query.lean.mockReturnValue(query);
|
query.lean.mockReturnValue(query);
|
||||||
return lean ? query : { exec: query.exec };
|
return lean ? query : { exec: query.exec };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function timelineFrame(timestamp = 0) {
|
||||||
|
return {
|
||||||
|
timestamp,
|
||||||
|
events: [],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 500,
|
||||||
|
xp: 0,
|
||||||
|
minionsKilled: 0,
|
||||||
|
jungleMinionsKilled: 0,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -77,7 +77,7 @@ export class MatchStatsService {
|
|||||||
);
|
);
|
||||||
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
|
const timelineByRiotMatchId = new Map<string, RiotMatchTimelineDto>();
|
||||||
for (const doc of riotDocs) {
|
for (const doc of riotDocs) {
|
||||||
if (isRiotMatchTimelineDto(doc.timeline)) {
|
if (isUsableRiotMatchTimeline(doc.timeline, doc.raw)) {
|
||||||
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
|
timelineByRiotMatchId.set(doc.matchId, doc.timeline);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,6 +94,12 @@ export class MatchStatsService {
|
|||||||
doc.matchId,
|
doc.matchId,
|
||||||
{ region },
|
{ region },
|
||||||
);
|
);
|
||||||
|
if (!isUsableRiotMatchTimeline(timeline, doc.raw)) {
|
||||||
|
this.logger.warn(
|
||||||
|
`Ignored unusable match timeline for ${doc.matchId}.`,
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
await RiotMatchModel.updateOne(
|
await RiotMatchModel.updateOne(
|
||||||
{ matchId: doc.matchId },
|
{ matchId: doc.matchId },
|
||||||
{
|
{
|
||||||
@@ -118,7 +124,6 @@ export class MatchStatsService {
|
|||||||
match: sourceMatch,
|
match: sourceMatch,
|
||||||
rawByRiotMatchId,
|
rawByRiotMatchId,
|
||||||
timelineByRiotMatchId,
|
timelineByRiotMatchId,
|
||||||
timelineLoadAttempted: options.includeTimeline === true,
|
|
||||||
});
|
});
|
||||||
|
|
||||||
await this.repository.upsert({
|
await this.repository.upsert({
|
||||||
@@ -253,9 +258,65 @@ export class MatchStatsService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRiotMatchTimelineDto(value: unknown): value is RiotMatchTimelineDto {
|
function isUsableRiotMatchTimeline(
|
||||||
if (!isRecord(value) || !isRecord(value.info)) return false;
|
value: unknown,
|
||||||
return Array.isArray(value.info.frames);
|
rawMatch: unknown,
|
||||||
|
): value is RiotMatchTimelineDto {
|
||||||
|
if (
|
||||||
|
!isRecord(value) ||
|
||||||
|
!isRecord(value.info) ||
|
||||||
|
!isRecord(rawMatch) ||
|
||||||
|
!isRecord(rawMatch.info)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const frameInterval = finiteNumber(value.info.frameInterval);
|
||||||
|
const gameDuration = finiteNumber(rawMatch.info.gameDuration);
|
||||||
|
const frames = value.info.frames;
|
||||||
|
if (
|
||||||
|
frameInterval === undefined ||
|
||||||
|
frameInterval <= 0 ||
|
||||||
|
gameDuration === undefined ||
|
||||||
|
gameDuration < 0 ||
|
||||||
|
!Array.isArray(frames) ||
|
||||||
|
frames.length === 0 ||
|
||||||
|
!frames.every(isUsableTimelineFrame)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const lastTimestamp = Math.max(
|
||||||
|
...frames.map((frame) => (frame as { timestamp: number }).timestamp),
|
||||||
|
);
|
||||||
|
return Math.abs(gameDuration * 1_000 - lastTimestamp) < frameInterval;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isUsableTimelineFrame(value: unknown): boolean {
|
||||||
|
if (
|
||||||
|
!isRecord(value) ||
|
||||||
|
finiteNumber(value.timestamp) === undefined ||
|
||||||
|
!Array.isArray(value.events) ||
|
||||||
|
!value.events.every(
|
||||||
|
(event) =>
|
||||||
|
isRecord(event) &&
|
||||||
|
typeof event.type === 'string' &&
|
||||||
|
finiteNumber(event.timestamp) !== undefined,
|
||||||
|
) ||
|
||||||
|
!isRecord(value.participantFrames)
|
||||||
|
) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const participantFrames = Object.values(value.participantFrames);
|
||||||
|
return (
|
||||||
|
participantFrames.length > 0 &&
|
||||||
|
participantFrames.every(
|
||||||
|
(participantFrame) =>
|
||||||
|
isRecord(participantFrame) &&
|
||||||
|
finiteNumber(participantFrame.participantId) !== undefined &&
|
||||||
|
finiteNumber(participantFrame.totalGold) !== undefined &&
|
||||||
|
finiteNumber(participantFrame.xp) !== undefined,
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import type {
|
|||||||
} from '../global/database/schema';
|
} from '../global/database/schema';
|
||||||
import type { InternalMatchCardView } from './community-stats.types';
|
import type { InternalMatchCardView } from './community-stats.types';
|
||||||
|
|
||||||
export const MATCH_STATS_BUILDER_VERSION = 9;
|
export const MATCH_STATS_BUILDER_VERSION = 10;
|
||||||
|
|
||||||
export type InternalRecord = MatchStatsRecord;
|
export type InternalRecord = MatchStatsRecord;
|
||||||
export type InternalGameDetail = MatchStatsGameDetail;
|
export type InternalGameDetail = MatchStatsGameDetail;
|
||||||
|
|||||||
@@ -66,7 +66,10 @@ describe('CompetitionCommandService', () => {
|
|||||||
$inc: { revision: 1 },
|
$inc: { revision: 1 },
|
||||||
$set: { projection: PROJECTION },
|
$set: { projection: PROJECTION },
|
||||||
});
|
});
|
||||||
expect(casOptions).toMatchObject({ new: true, session: harness.session });
|
expect(casOptions).toMatchObject({
|
||||||
|
returnDocument: 'after',
|
||||||
|
session: harness.session,
|
||||||
|
});
|
||||||
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
|
expect(harness.session.abortTransaction).toHaveBeenCalledTimes(1);
|
||||||
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
|
expect(harness.session.commitTransaction).not.toHaveBeenCalled();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -321,7 +321,7 @@ export class CompetitionCommandService {
|
|||||||
phase: projection.phase,
|
phase: projection.phase,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ new: true, runValidators: true, session },
|
{ returnDocument: 'after', runValidators: true, session },
|
||||||
)
|
)
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
@@ -475,7 +475,7 @@ export class CompetitionCommandService {
|
|||||||
phase: projection.phase,
|
phase: projection.phase,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ new: true, runValidators: true, session },
|
{ returnDocument: 'after', runValidators: true, session },
|
||||||
)
|
)
|
||||||
.lean()
|
.lean()
|
||||||
.exec();
|
.exec();
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import { ConflictException, ForbiddenException } from '@nestjs/common';
|
import {
|
||||||
|
ConflictException,
|
||||||
|
ForbiddenException,
|
||||||
|
NotFoundException,
|
||||||
|
} from '@nestjs/common';
|
||||||
import { Types } from 'mongoose';
|
import { Types } from 'mongoose';
|
||||||
import { ConnectionService } from '../global/database/connection.service';
|
import { ConnectionService } from '../global/database/connection.service';
|
||||||
import { CompetitionQueryService } from './competition-query.service';
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
@@ -55,6 +59,38 @@ describe('CompetitionQueryService', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('resolves a team view from an explicit team id without a caller identity', async () => {
|
||||||
|
const harness = createHarness();
|
||||||
|
const service = createService(harness);
|
||||||
|
|
||||||
|
const result = await service.getTeamView({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
teamId: TEAM_A_ID,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toMatchObject({
|
||||||
|
teamId: TEAM_A_ID.toHexString(),
|
||||||
|
activeSeries: [expect.objectContaining({ seriesId: SERIES_ID })],
|
||||||
|
tournamentCodes: [
|
||||||
|
expect.objectContaining({ code: 'TEAM-A-SECRET-CODE' }),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
expect(JSON.stringify(result)).not.toContain('OPPONENT-SECRET-CODE');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not resolve a team view for an unknown team id', async () => {
|
||||||
|
const service = createService(createHarness());
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getTeamView({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
teamId: new Types.ObjectId('64c000000000000000000098'),
|
||||||
|
}),
|
||||||
|
).rejects.toBeInstanceOf(NotFoundException);
|
||||||
|
});
|
||||||
|
|
||||||
it('does not reveal a team view to an authenticated non-participant', async () => {
|
it('does not reveal a team view to an authenticated non-participant', async () => {
|
||||||
const service = createService(createHarness());
|
const service = createService(createHarness());
|
||||||
|
|
||||||
|
|||||||
@@ -22,6 +22,17 @@ export interface CompetitionScope {
|
|||||||
matchId: mongoose.Types.ObjectId;
|
matchId: mongoose.Types.ObjectId;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A team view is addressed either by the caller's membership (signed-in) or by
|
||||||
|
* an explicit team id. The explicit form exists so that the team progress page
|
||||||
|
* stays usable while community members have not all signed in yet.
|
||||||
|
*/
|
||||||
|
export type TeamViewScope = CompetitionScope &
|
||||||
|
(
|
||||||
|
| { userId: mongoose.Types.ObjectId; teamId?: undefined }
|
||||||
|
| { teamId: mongoose.Types.ObjectId; userId?: undefined }
|
||||||
|
);
|
||||||
|
|
||||||
interface CompetitionProjectionSource {
|
interface CompetitionProjectionSource {
|
||||||
series?: Array<Record<string, unknown>>;
|
series?: Array<Record<string, unknown>>;
|
||||||
gameSlots?: Array<Record<string, unknown>>;
|
gameSlots?: Array<Record<string, unknown>>;
|
||||||
@@ -68,15 +79,21 @@ export class CompetitionQueryService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
public async getTeamView(
|
public async getTeamView(
|
||||||
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
|
scope: TeamViewScope,
|
||||||
): Promise<TeamCompetitionViewResponse> {
|
): Promise<TeamCompetitionViewResponse> {
|
||||||
const competition = (await this.getCompetition(scope)) as Competition & {
|
const competition = (await this.getCompetition(scope)) as Competition & {
|
||||||
_id: PersistenceId;
|
_id: PersistenceId;
|
||||||
};
|
};
|
||||||
const team = competition.teams.find(({ members }) =>
|
const requestedTeamId = scope.teamId;
|
||||||
members.some(({ userId }) => sameId(userId, scope.userId)),
|
const team = requestedTeamId
|
||||||
);
|
? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId))
|
||||||
|
: competition.teams.find(({ members }) =>
|
||||||
|
members.some(({ userId }) => sameId(userId, scope.userId)),
|
||||||
|
);
|
||||||
if (!team) {
|
if (!team) {
|
||||||
|
if (requestedTeamId) {
|
||||||
|
throw new NotFoundException('Competition team not found.');
|
||||||
|
}
|
||||||
throw new ForbiddenException(
|
throw new ForbiddenException(
|
||||||
'Only a Competition team member may access the team view.',
|
'Only a Competition team member may access the team view.',
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ import { CompetitionController } from './competition.controller';
|
|||||||
import { CompetitionQueryService } from './competition-query.service';
|
import { CompetitionQueryService } from './competition-query.service';
|
||||||
|
|
||||||
describe('CompetitionController', () => {
|
describe('CompetitionController', () => {
|
||||||
it('marks only the detail endpoint public and writes a revision ETag', async () => {
|
it('marks the read endpoints public and writes a revision ETag', async () => {
|
||||||
const { controller, queryService } = createHarness();
|
const { controller, queryService } = createHarness();
|
||||||
const response = { setHeader: jest.fn() };
|
const response = { setHeader: jest.fn() };
|
||||||
|
|
||||||
@@ -17,18 +17,14 @@ describe('CompetitionController', () => {
|
|||||||
response as never,
|
response as never,
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(
|
for (const method of ['getDetail', 'getTeamView'] as const) {
|
||||||
Reflect.getMetadata(
|
expect(
|
||||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
Reflect.getMetadata(
|
||||||
CompetitionController.prototype.getDetail,
|
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
||||||
),
|
CompetitionController.prototype[method],
|
||||||
).toBe(true);
|
),
|
||||||
expect(
|
).toBe(true);
|
||||||
Reflect.getMetadata(
|
}
|
||||||
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
|
|
||||||
CompetitionController.prototype.getTeamView,
|
|
||||||
),
|
|
||||||
).not.toBe(true);
|
|
||||||
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
|
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
|
||||||
expect(result).toMatchObject({ revision: 7 });
|
expect(result).toMatchObject({ revision: 7 });
|
||||||
expect(queryService.getCompetition).toHaveBeenCalledWith({
|
expect(queryService.getCompetition).toHaveBeenCalledWith({
|
||||||
@@ -37,6 +33,65 @@ describe('CompetitionController', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('reads a team view by explicit team id without an authenticated caller', async () => {
|
||||||
|
const { controller, queryService } = createHarness();
|
||||||
|
queryService.getTeamView.mockResolvedValue({ revision: 7 });
|
||||||
|
const response = { setHeader: jest.fn() };
|
||||||
|
|
||||||
|
const result = await controller.getTeamView(
|
||||||
|
undefined,
|
||||||
|
COMMUNITY_ID,
|
||||||
|
MATCH_ID,
|
||||||
|
TEAM_A_ID.toHexString(),
|
||||||
|
response as never,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(queryService.getTeamView).toHaveBeenCalledWith({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
teamId: TEAM_A_ID,
|
||||||
|
});
|
||||||
|
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
|
||||||
|
expect(result).toMatchObject({ revision: 7 });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('falls back to the membership-scoped team view for a signed-in caller', async () => {
|
||||||
|
const { controller, queryService } = createHarness();
|
||||||
|
queryService.getTeamView.mockResolvedValue({ revision: 7 });
|
||||||
|
|
||||||
|
await controller.getTeamView(adminUser(), COMMUNITY_ID, MATCH_ID);
|
||||||
|
|
||||||
|
expect(queryService.getTeamView).toHaveBeenCalledWith({
|
||||||
|
communityId: COMMUNITY_ID,
|
||||||
|
matchId: MATCH_ID,
|
||||||
|
userId: ADMIN_ID,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects an anonymous team view request that names no team', async () => {
|
||||||
|
const { controller, queryService } = createHarness();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status: 401,
|
||||||
|
response: { error: { code: 'COMPETITION_TEAM_UNIDENTIFIED' } },
|
||||||
|
});
|
||||||
|
expect(queryService.getTeamView).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rejects a malformed team id', async () => {
|
||||||
|
const { controller, queryService } = createHarness();
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
controller.getTeamView(undefined, COMMUNITY_ID, MATCH_ID, 'not-an-id'),
|
||||||
|
).rejects.toMatchObject({
|
||||||
|
status: 422,
|
||||||
|
response: { error: { code: 'INVALID_COMPETITION_REQUEST' } },
|
||||||
|
});
|
||||||
|
expect(queryService.getTeamView).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
it('protects audit and mutation endpoints with admin roles', () => {
|
it('protects audit and mutation endpoints with admin roles', () => {
|
||||||
for (const method of [
|
for (const method of [
|
||||||
'listFacts',
|
'listFacts',
|
||||||
|
|||||||
@@ -63,20 +63,36 @@ export class CompetitionController {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Temporarily public: community members are not all signed in yet, so the
|
||||||
|
// team progress page addresses a team through an explicit `teamId` instead of
|
||||||
|
// the caller's identity. A signed-in caller with no `teamId` keeps the
|
||||||
|
// membership-scoped behaviour.
|
||||||
@Get('team')
|
@Get('team')
|
||||||
|
@AllowPublicAccess()
|
||||||
public async getTeamView(
|
public async getTeamView(
|
||||||
@CurrentUser() currentUser: UserDocument,
|
@CurrentUser() currentUser: UserDocument | undefined,
|
||||||
@Param('communityId', ParseObjectIdPipe)
|
@Param('communityId', ParseObjectIdPipe)
|
||||||
communityId: mongoose.Types.ObjectId,
|
communityId: mongoose.Types.ObjectId,
|
||||||
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
|
||||||
|
@Query('teamId') requestedTeamId?: string,
|
||||||
@Res({ passthrough: true }) response?: Response,
|
@Res({ passthrough: true }) response?: Response,
|
||||||
): Promise<TeamCompetitionViewResponse> {
|
): Promise<TeamCompetitionViewResponse> {
|
||||||
return this.translate(async () => {
|
return this.translate(async () => {
|
||||||
assertSameCommunity(currentUser, communityId);
|
const teamId = parseOptionalObjectId(requestedTeamId, 'teamId');
|
||||||
|
if (!teamId) {
|
||||||
|
if (!currentUser) {
|
||||||
|
throw apiHttpError(
|
||||||
|
401,
|
||||||
|
'COMPETITION_TEAM_UNIDENTIFIED',
|
||||||
|
'Sign in or provide a teamId query parameter to read a team view.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assertSameCommunity(currentUser, communityId);
|
||||||
|
}
|
||||||
const result = await this.queryService.getTeamView({
|
const result = await this.queryService.getTeamView({
|
||||||
communityId,
|
communityId,
|
||||||
matchId,
|
matchId,
|
||||||
userId: currentUser._id,
|
...(teamId ? { teamId } : { userId: currentUser!._id }),
|
||||||
});
|
});
|
||||||
response?.setHeader('ETag', revisionEtag(result.revision));
|
response?.setHeader('ETag', revisionEtag(result.revision));
|
||||||
return result;
|
return result;
|
||||||
@@ -298,6 +314,21 @@ function requireCommandHeaders(
|
|||||||
return revision;
|
return revision;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function parseOptionalObjectId(
|
||||||
|
value: string | undefined,
|
||||||
|
field: string,
|
||||||
|
): mongoose.Types.ObjectId | undefined {
|
||||||
|
if (value === undefined || value.trim().length === 0) return undefined;
|
||||||
|
if (!mongoose.isValidObjectId(value)) {
|
||||||
|
throw apiHttpError(
|
||||||
|
422,
|
||||||
|
'INVALID_COMPETITION_REQUEST',
|
||||||
|
`The ${field} query parameter must be a valid ObjectId.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return new mongoose.Types.ObjectId(value);
|
||||||
|
}
|
||||||
|
|
||||||
function requireRevisionHeader(ifMatch: string | undefined): number {
|
function requireRevisionHeader(ifMatch: string | undefined): number {
|
||||||
const revision = parseRevision(ifMatch);
|
const revision = parseRevision(ifMatch);
|
||||||
if (revision === undefined) {
|
if (revision === undefined) {
|
||||||
|
|||||||
@@ -1,5 +1,18 @@
|
|||||||
import { generateSeriesGraph } from './series-graph';
|
import { generateSeriesGraph } from './series-graph';
|
||||||
|
|
||||||
|
type GraphInput = Parameters<typeof generateSeriesGraph>[0];
|
||||||
|
type ExplicitRoundRobinPairing = {
|
||||||
|
roundNumber: number;
|
||||||
|
matchNumber: number;
|
||||||
|
teamAId: string;
|
||||||
|
teamBId: string;
|
||||||
|
};
|
||||||
|
type ExplicitRoundRobinGraphInput = Omit<GraphInput, 'format'> & {
|
||||||
|
format: Extract<GraphInput['format'], { type: 'round-robin' }> & {
|
||||||
|
pairings: readonly ExplicitRoundRobinPairing[];
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
describe('generateSeriesGraph', () => {
|
describe('generateSeriesGraph', () => {
|
||||||
it('generates a deterministic graph with stable opaque ids', () => {
|
it('generates a deterministic graph with stable opaque ids', () => {
|
||||||
const input = {
|
const input = {
|
||||||
@@ -112,8 +125,254 @@ describe('generateSeriesGraph', () => {
|
|||||||
expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' });
|
expect(error).toMatchObject({ code: 'INVALID_FIRST_TO_RULE' });
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('reproduces an explicit persisted round-robin schedule by TeamId and pairing position', () => {
|
||||||
|
const input: ExplicitRoundRobinGraphInput = {
|
||||||
|
competitionId: 'competition-persisted-round-robin',
|
||||||
|
teams: Array.from({ length: 8 }, (_, index) => ({
|
||||||
|
teamId: `team-${index + 1}`,
|
||||||
|
displayOrder: 8 - index,
|
||||||
|
seedNumber: index + 1,
|
||||||
|
})),
|
||||||
|
format: {
|
||||||
|
type: 'round-robin',
|
||||||
|
rule: fixedGames(1),
|
||||||
|
maxRounds: 3,
|
||||||
|
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
|
||||||
|
// Persisted schedules need not arrive in display order. Their explicit
|
||||||
|
// round/match positions, rather than array position, define identity.
|
||||||
|
pairings: [
|
||||||
|
pairing(3, 4, 'team-6', 'team-7'),
|
||||||
|
pairing(1, 2, 'team-3', 'team-4'),
|
||||||
|
pairing(2, 1, 'team-1', 'team-3'),
|
||||||
|
pairing(1, 4, 'team-7', 'team-8'),
|
||||||
|
pairing(3, 1, 'team-1', 'team-4'),
|
||||||
|
pairing(2, 3, 'team-5', 'team-7'),
|
||||||
|
pairing(1, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(3, 3, 'team-5', 'team-8'),
|
||||||
|
pairing(2, 4, 'team-6', 'team-8'),
|
||||||
|
pairing(1, 3, 'team-5', 'team-6'),
|
||||||
|
pairing(3, 2, 'team-2', 'team-3'),
|
||||||
|
pairing(2, 2, 'team-2', 'team-4'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const first = generateSeriesGraph(input);
|
||||||
|
const second = generateSeriesGraph({
|
||||||
|
...input,
|
||||||
|
format: {
|
||||||
|
...input.format,
|
||||||
|
pairings: [...input.format.pairings].reverse(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(second).toEqual(first);
|
||||||
|
expect(
|
||||||
|
first.map((series) => ({
|
||||||
|
code: series.code,
|
||||||
|
roundNumber: series.stage.roundNumber,
|
||||||
|
displayOrder: series.stage.displayOrder,
|
||||||
|
sources: series.slots.map((slot) => slot.source),
|
||||||
|
})),
|
||||||
|
).toEqual([
|
||||||
|
roundRobinSeries('RR_R1_M1', 1, 1, 'team-1', 'team-2'),
|
||||||
|
roundRobinSeries('RR_R1_M2', 1, 2, 'team-3', 'team-4'),
|
||||||
|
roundRobinSeries('RR_R1_M3', 1, 3, 'team-5', 'team-6'),
|
||||||
|
roundRobinSeries('RR_R1_M4', 1, 4, 'team-7', 'team-8'),
|
||||||
|
roundRobinSeries('RR_R2_M1', 2, 5, 'team-1', 'team-3'),
|
||||||
|
roundRobinSeries('RR_R2_M2', 2, 6, 'team-2', 'team-4'),
|
||||||
|
roundRobinSeries('RR_R2_M3', 2, 7, 'team-5', 'team-7'),
|
||||||
|
roundRobinSeries('RR_R2_M4', 2, 8, 'team-6', 'team-8'),
|
||||||
|
roundRobinSeries('RR_R3_M1', 3, 9, 'team-1', 'team-4'),
|
||||||
|
roundRobinSeries('RR_R3_M2', 3, 10, 'team-2', 'team-3'),
|
||||||
|
roundRobinSeries('RR_R3_M3', 3, 11, 'team-5', 'team-8'),
|
||||||
|
roundRobinSeries('RR_R3_M4', 3, 12, 'team-6', 'team-7'),
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
name: 'a TeamId that is absent from the Competition',
|
||||||
|
replacement: pairing(1, 1, 'team-1', 'team-9'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'the same TeamId in both slots',
|
||||||
|
replacement: pairing(1, 1, 'team-1', 'team-1'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'a non-positive round number',
|
||||||
|
replacement: pairing(0, 1, 'team-1', 'team-2'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'a non-positive match number',
|
||||||
|
replacement: pairing(1, 0, 'team-1', 'team-2'),
|
||||||
|
},
|
||||||
|
])(
|
||||||
|
'rejects an explicit round-robin pairing with $name',
|
||||||
|
({ replacement }) => {
|
||||||
|
const input = explicitRoundRobinInput([
|
||||||
|
replacement,
|
||||||
|
pairing(1, 2, 'team-3', 'team-4'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expectGraphError(input, 'INVALID_ROUND_ROBIN_PAIRING');
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
name: 'round and match position',
|
||||||
|
pairings: [
|
||||||
|
pairing(1, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(1, 1, 'team-3', 'team-4'),
|
||||||
|
],
|
||||||
|
code: 'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'opponents with reversed slots',
|
||||||
|
pairings: [
|
||||||
|
pairing(1, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(2, 1, 'team-2', 'team-1'),
|
||||||
|
],
|
||||||
|
code: 'DUPLICATE_ROUND_ROBIN_OPPONENTS',
|
||||||
|
},
|
||||||
|
])('rejects a duplicate explicit $name', ({ pairings, code }) => {
|
||||||
|
expectGraphError(explicitRoundRobinInput(pairings), code);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps distinct opponent pairs when opaque TeamIds contain delimiters', () => {
|
||||||
|
const input = explicitRoundRobinInput([
|
||||||
|
pairing(1, 1, 'a', 'b:c'),
|
||||||
|
pairing(1, 2, 'a:b', 'c'),
|
||||||
|
]);
|
||||||
|
input.format.maxRounds = 1;
|
||||||
|
input.teams = ['a', 'b:c', 'a:b', 'c'].map((teamId, index) => ({
|
||||||
|
teamId,
|
||||||
|
displayOrder: index + 1,
|
||||||
|
seedNumber: index + 1,
|
||||||
|
}));
|
||||||
|
|
||||||
|
expect(generateSeriesGraph(input)).toHaveLength(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('validates complete odd-team rounds and clamps maxRounds to the full schedule', () => {
|
||||||
|
const pairings = [
|
||||||
|
pairing(1, 1, 'team-2', 'team-5'),
|
||||||
|
pairing(1, 2, 'team-3', 'team-4'),
|
||||||
|
pairing(2, 1, 'team-1', 'team-5'),
|
||||||
|
pairing(2, 2, 'team-2', 'team-3'),
|
||||||
|
pairing(3, 1, 'team-1', 'team-4'),
|
||||||
|
pairing(3, 2, 'team-3', 'team-5'),
|
||||||
|
pairing(4, 1, 'team-1', 'team-3'),
|
||||||
|
pairing(4, 2, 'team-2', 'team-4'),
|
||||||
|
pairing(5, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(5, 2, 'team-4', 'team-5'),
|
||||||
|
];
|
||||||
|
const input = explicitRoundRobinInput(pairings);
|
||||||
|
input.teams = Array.from({ length: 5 }, (_, index) => ({
|
||||||
|
teamId: `team-${index + 1}`,
|
||||||
|
displayOrder: index + 1,
|
||||||
|
seedNumber: index + 1,
|
||||||
|
}));
|
||||||
|
input.format.maxRounds = 10;
|
||||||
|
|
||||||
|
expect(generateSeriesGraph(input)).toHaveLength(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{
|
||||||
|
name: 'an expected round',
|
||||||
|
pairings: [
|
||||||
|
pairing(1, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(1, 2, 'team-3', 'team-4'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'a match from an expected round',
|
||||||
|
pairings: [
|
||||||
|
pairing(1, 1, 'team-1', 'team-2'),
|
||||||
|
pairing(1, 2, 'team-3', 'team-4'),
|
||||||
|
pairing(2, 1, 'team-1', 'team-3'),
|
||||||
|
],
|
||||||
|
},
|
||||||
|
])('rejects explicit pairings missing $name', ({ pairings }) => {
|
||||||
|
expectGraphError(
|
||||||
|
explicitRoundRobinInput(pairings),
|
||||||
|
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
function firstTo(winsRequired: number, maxGames: number) {
|
function firstTo(winsRequired: number, maxGames: number) {
|
||||||
return { type: 'first-to' as const, winsRequired, maxGames };
|
return { type: 'first-to' as const, winsRequired, maxGames };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function expectGraphError(input: GraphInput, code: string): void {
|
||||||
|
try {
|
||||||
|
generateSeriesGraph(input);
|
||||||
|
throw new Error(`Expected graph error ${code}.`);
|
||||||
|
} catch (error) {
|
||||||
|
expect(error).toMatchObject({ code });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fixedGames(gameCount: number) {
|
||||||
|
return {
|
||||||
|
type: 'fixed-games' as const,
|
||||||
|
gameCount,
|
||||||
|
drawPolicy: 'allow' as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function pairing(
|
||||||
|
roundNumber: number,
|
||||||
|
matchNumber: number,
|
||||||
|
teamAId: string,
|
||||||
|
teamBId: string,
|
||||||
|
): ExplicitRoundRobinPairing {
|
||||||
|
return {
|
||||||
|
roundNumber,
|
||||||
|
matchNumber,
|
||||||
|
teamAId,
|
||||||
|
teamBId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function explicitRoundRobinInput(
|
||||||
|
pairings: readonly ExplicitRoundRobinPairing[],
|
||||||
|
): ExplicitRoundRobinGraphInput {
|
||||||
|
return {
|
||||||
|
competitionId: 'competition-explicit-round-robin-validation',
|
||||||
|
teams: Array.from({ length: 4 }, (_, index) => ({
|
||||||
|
teamId: `team-${index + 1}`,
|
||||||
|
displayOrder: index + 1,
|
||||||
|
seedNumber: index + 1,
|
||||||
|
})),
|
||||||
|
format: {
|
||||||
|
type: 'round-robin',
|
||||||
|
rule: fixedGames(1),
|
||||||
|
maxRounds: 2,
|
||||||
|
tieBreakers: ['series-wins', 'game-diff', 'head-to-head'],
|
||||||
|
pairings,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function roundRobinSeries(
|
||||||
|
code: string,
|
||||||
|
roundNumber: number,
|
||||||
|
displayOrder: number,
|
||||||
|
teamAId: string,
|
||||||
|
teamBId: string,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
code,
|
||||||
|
roundNumber,
|
||||||
|
displayOrder,
|
||||||
|
sources: [
|
||||||
|
{ type: 'team', teamId: teamAId },
|
||||||
|
{ type: 'team', teamId: teamBId },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -51,6 +51,11 @@ export interface SeriesDefinition {
|
|||||||
{ position: 'B'; source: ParticipantSource },
|
{ position: 'B'; source: ParticipantSource },
|
||||||
];
|
];
|
||||||
rule: SeriesRule;
|
rule: SeriesRule;
|
||||||
|
schedule?: {
|
||||||
|
date: string;
|
||||||
|
time: string | null;
|
||||||
|
timeZone: 'Asia/Seoul';
|
||||||
|
};
|
||||||
activation?: {
|
activation?: {
|
||||||
type: 'grand-final-reset-required';
|
type: 'grand-final-reset-required';
|
||||||
grandFinalSeriesId: string;
|
grandFinalSeriesId: string;
|
||||||
@@ -68,6 +73,13 @@ export interface CompetitionGraphTeam {
|
|||||||
seedNumber?: number;
|
seedNumber?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface RoundRobinPairing {
|
||||||
|
roundNumber: number;
|
||||||
|
matchNumber: number;
|
||||||
|
teamAId: string;
|
||||||
|
teamBId: string;
|
||||||
|
}
|
||||||
|
|
||||||
export type CompetitionGraphFormat =
|
export type CompetitionGraphFormat =
|
||||||
| {
|
| {
|
||||||
type: 'paired-series';
|
type: 'paired-series';
|
||||||
@@ -77,6 +89,7 @@ export type CompetitionGraphFormat =
|
|||||||
type: 'round-robin';
|
type: 'round-robin';
|
||||||
rule: FixedGamesSeriesRule;
|
rule: FixedGamesSeriesRule;
|
||||||
maxRounds?: number;
|
maxRounds?: number;
|
||||||
|
pairings?: readonly RoundRobinPairing[];
|
||||||
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
|
tieBreakers: readonly ['series-wins', 'game-diff', 'head-to-head'];
|
||||||
}
|
}
|
||||||
| {
|
| {
|
||||||
@@ -116,7 +129,7 @@ type TemplateParticipantSource =
|
|||||||
}
|
}
|
||||||
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
|
| { type: 'series-slot'; seriesCode: string; slot: SeriesSlot };
|
||||||
|
|
||||||
interface RoundRobinPairing {
|
interface CanonicalRoundRobinPairing {
|
||||||
roundNumber: number;
|
roundNumber: number;
|
||||||
teamAIndex: number;
|
teamAIndex: number;
|
||||||
teamBIndex: number;
|
teamBIndex: number;
|
||||||
@@ -143,12 +156,7 @@ export function generateSeriesGraph(
|
|||||||
);
|
);
|
||||||
break;
|
break;
|
||||||
case 'round-robin':
|
case 'round-robin':
|
||||||
graph = generateRoundRobinGraph(
|
graph = generateRoundRobinGraph(input.competitionId, teams, input.format);
|
||||||
input.competitionId,
|
|
||||||
teams,
|
|
||||||
input.format.rule,
|
|
||||||
input.format.maxRounds,
|
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
case 'double-elimination':
|
case 'double-elimination':
|
||||||
graph = generateDoubleEliminationGraph(
|
graph = generateDoubleEliminationGraph(
|
||||||
@@ -200,10 +208,9 @@ function generatePairedSeriesGraph(
|
|||||||
function generateRoundRobinGraph(
|
function generateRoundRobinGraph(
|
||||||
competitionId: string,
|
competitionId: string,
|
||||||
teams: CompetitionGraphTeam[],
|
teams: CompetitionGraphTeam[],
|
||||||
rule: FixedGamesSeriesRule,
|
format: Extract<CompetitionGraphFormat, { type: 'round-robin' }>,
|
||||||
maxRounds?: number,
|
|
||||||
): SeriesDefinition[] {
|
): SeriesDefinition[] {
|
||||||
assertFixedGamesRule(rule);
|
assertFixedGamesRule(format.rule);
|
||||||
if (teams.length < 2) {
|
if (teams.length < 2) {
|
||||||
throw graphError(
|
throw graphError(
|
||||||
'INVALID_ROUND_ROBIN_TEAM_COUNT',
|
'INVALID_ROUND_ROBIN_TEAM_COUNT',
|
||||||
@@ -211,13 +218,16 @@ function generateRoundRobinGraph(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const pairings = roundRobinPairings(teams.length, maxRounds);
|
const pairings = format.pairings
|
||||||
const matchNumberByRound = new Map<number, number>();
|
? validateExplicitRoundRobinPairings(
|
||||||
|
teams,
|
||||||
|
format.pairings,
|
||||||
|
format.maxRounds,
|
||||||
|
)
|
||||||
|
: canonicalRoundRobinPairings(teams, format.maxRounds);
|
||||||
|
|
||||||
return pairings.map((pairing, index) => {
|
return pairings.map((pairing, index) => {
|
||||||
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
|
const code = `RR_R${pairing.roundNumber}_M${pairing.matchNumber}`;
|
||||||
matchNumberByRound.set(pairing.roundNumber, matchNumber);
|
|
||||||
const code = `RR_R${pairing.roundNumber}_M${matchNumber}`;
|
|
||||||
return createSeriesDefinition({
|
return createSeriesDefinition({
|
||||||
competitionId,
|
competitionId,
|
||||||
code,
|
code,
|
||||||
@@ -225,14 +235,139 @@ function generateRoundRobinGraph(
|
|||||||
roundNumber: pairing.roundNumber,
|
roundNumber: pairing.roundNumber,
|
||||||
displayOrder: index + 1,
|
displayOrder: index + 1,
|
||||||
sources: [
|
sources: [
|
||||||
{ type: 'team', teamId: teams[pairing.teamAIndex].teamId },
|
{ type: 'team', teamId: pairing.teamAId },
|
||||||
{ type: 'team', teamId: teams[pairing.teamBIndex].teamId },
|
{ type: 'team', teamId: pairing.teamBId },
|
||||||
],
|
],
|
||||||
rule,
|
rule: format.rule,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function canonicalRoundRobinPairings(
|
||||||
|
teams: CompetitionGraphTeam[],
|
||||||
|
maxRounds?: number,
|
||||||
|
): RoundRobinPairing[] {
|
||||||
|
const matchNumberByRound = new Map<number, number>();
|
||||||
|
return roundRobinPairings(teams.length, maxRounds).map((pairing) => {
|
||||||
|
const matchNumber = (matchNumberByRound.get(pairing.roundNumber) ?? 0) + 1;
|
||||||
|
matchNumberByRound.set(pairing.roundNumber, matchNumber);
|
||||||
|
return {
|
||||||
|
roundNumber: pairing.roundNumber,
|
||||||
|
matchNumber,
|
||||||
|
teamAId: teams[pairing.teamAIndex].teamId,
|
||||||
|
teamBId: teams[pairing.teamBIndex].teamId,
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateExplicitRoundRobinPairings(
|
||||||
|
teams: CompetitionGraphTeam[],
|
||||||
|
pairings: readonly RoundRobinPairing[],
|
||||||
|
maxRounds?: number,
|
||||||
|
): RoundRobinPairing[] {
|
||||||
|
if (pairings.length === 0) {
|
||||||
|
throw graphError(
|
||||||
|
'INVALID_ROUND_ROBIN_PAIRING',
|
||||||
|
'Explicit round-robin pairings cannot be empty.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const teamIds = new Set(teams.map(({ teamId }) => teamId));
|
||||||
|
const positions = new Set<string>();
|
||||||
|
const opponentPairs = new Set<string>();
|
||||||
|
const teamsByRound = new Map<number, Set<string>>();
|
||||||
|
const sorted = pairings
|
||||||
|
.map((pairing) => ({ ...pairing }))
|
||||||
|
.sort(
|
||||||
|
(left, right) =>
|
||||||
|
left.roundNumber - right.roundNumber ||
|
||||||
|
left.matchNumber - right.matchNumber,
|
||||||
|
);
|
||||||
|
|
||||||
|
for (const pairing of sorted) {
|
||||||
|
if (
|
||||||
|
!Number.isInteger(pairing.roundNumber) ||
|
||||||
|
pairing.roundNumber < 1 ||
|
||||||
|
!Number.isInteger(pairing.matchNumber) ||
|
||||||
|
pairing.matchNumber < 1 ||
|
||||||
|
(maxRounds !== undefined && pairing.roundNumber > maxRounds) ||
|
||||||
|
!teamIds.has(pairing.teamAId) ||
|
||||||
|
!teamIds.has(pairing.teamBId) ||
|
||||||
|
pairing.teamAId === pairing.teamBId
|
||||||
|
) {
|
||||||
|
throw graphError(
|
||||||
|
'INVALID_ROUND_ROBIN_PAIRING',
|
||||||
|
'Every explicit round-robin pairing needs a valid position and two known, distinct teams.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const position = `${pairing.roundNumber}:${pairing.matchNumber}`;
|
||||||
|
if (positions.has(position)) {
|
||||||
|
throw graphError(
|
||||||
|
'DUPLICATE_ROUND_ROBIN_PAIRING_POSITION',
|
||||||
|
`Round-robin pairing position ${position} occurs more than once.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
positions.add(position);
|
||||||
|
|
||||||
|
const opponents = JSON.stringify([pairing.teamAId, pairing.teamBId].sort());
|
||||||
|
if (opponentPairs.has(opponents)) {
|
||||||
|
throw graphError(
|
||||||
|
'DUPLICATE_ROUND_ROBIN_OPPONENTS',
|
||||||
|
'A round-robin opponent pair occurs more than once.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
opponentPairs.add(opponents);
|
||||||
|
|
||||||
|
const roundTeams = teamsByRound.get(pairing.roundNumber) ?? new Set();
|
||||||
|
if (roundTeams.has(pairing.teamAId) || roundTeams.has(pairing.teamBId)) {
|
||||||
|
throw graphError(
|
||||||
|
'INVALID_ROUND_ROBIN_PAIRING',
|
||||||
|
'A team cannot appear in multiple Series in the same round.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
roundTeams.add(pairing.teamAId);
|
||||||
|
roundTeams.add(pairing.teamBId);
|
||||||
|
teamsByRound.set(pairing.roundNumber, roundTeams);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const roundNumber of new Set(
|
||||||
|
sorted.map((pairing) => pairing.roundNumber),
|
||||||
|
)) {
|
||||||
|
const matches = sorted.filter(
|
||||||
|
(pairing) => pairing.roundNumber === roundNumber,
|
||||||
|
);
|
||||||
|
if (matches.some((pairing, index) => pairing.matchNumber !== index + 1)) {
|
||||||
|
throw graphError(
|
||||||
|
'INVALID_ROUND_ROBIN_PAIRING',
|
||||||
|
`Round ${roundNumber} match numbers must be contiguous from one.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const expectedRoundCount = roundRobinRoundCount(teams.length, maxRounds);
|
||||||
|
const expectedMatchesPerRound = Math.floor(teams.length / 2);
|
||||||
|
for (
|
||||||
|
let roundNumber = 1;
|
||||||
|
roundNumber <= expectedRoundCount;
|
||||||
|
roundNumber += 1
|
||||||
|
) {
|
||||||
|
const matchCount = (teamsByRound.get(roundNumber)?.size ?? 0) / 2;
|
||||||
|
if (matchCount !== expectedMatchesPerRound) {
|
||||||
|
throw graphError(
|
||||||
|
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
|
||||||
|
`Round ${roundNumber} must contain ${expectedMatchesPerRound} Series.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (teamsByRound.size !== expectedRoundCount) {
|
||||||
|
throw graphError(
|
||||||
|
'INCOMPLETE_ROUND_ROBIN_PAIRINGS',
|
||||||
|
`Explicit round-robin pairings must contain rounds 1 through ${expectedRoundCount}.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return sorted;
|
||||||
|
}
|
||||||
|
|
||||||
function generateDoubleEliminationGraph(
|
function generateDoubleEliminationGraph(
|
||||||
competitionId: string,
|
competitionId: string,
|
||||||
teams: CompetitionGraphTeam[],
|
teams: CompetitionGraphTeam[],
|
||||||
@@ -436,20 +571,13 @@ function ruleForStage(
|
|||||||
function roundRobinPairings(
|
function roundRobinPairings(
|
||||||
teamCount: number,
|
teamCount: number,
|
||||||
maxRounds?: number,
|
maxRounds?: number,
|
||||||
): RoundRobinPairing[] {
|
): CanonicalRoundRobinPairing[] {
|
||||||
const bye = -1;
|
const bye = -1;
|
||||||
const rotating = Array.from({ length: teamCount }, (_, index) => index);
|
const rotating = Array.from({ length: teamCount }, (_, index) => index);
|
||||||
if (rotating.length % 2 === 1) rotating.push(bye);
|
if (rotating.length % 2 === 1) rotating.push(bye);
|
||||||
|
|
||||||
const fullRoundCount = rotating.length - 1;
|
const roundCount = roundRobinRoundCount(teamCount, maxRounds);
|
||||||
const requestedRounds =
|
const pairings: CanonicalRoundRobinPairing[] = [];
|
||||||
maxRounds === undefined
|
|
||||||
? fullRoundCount
|
|
||||||
: Number.isFinite(maxRounds)
|
|
||||||
? Math.floor(maxRounds)
|
|
||||||
: fullRoundCount;
|
|
||||||
const roundCount = Math.max(0, Math.min(fullRoundCount, requestedRounds));
|
|
||||||
const pairings: RoundRobinPairing[] = [];
|
|
||||||
|
|
||||||
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
|
for (let roundIndex = 0; roundIndex < roundCount; roundIndex += 1) {
|
||||||
for (let index = 0; index < rotating.length / 2; index += 1) {
|
for (let index = 0; index < rotating.length / 2; index += 1) {
|
||||||
@@ -472,6 +600,17 @@ function roundRobinPairings(
|
|||||||
return pairings;
|
return pairings;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function roundRobinRoundCount(teamCount: number, maxRounds?: number): number {
|
||||||
|
const fullRoundCount = teamCount % 2 === 0 ? teamCount - 1 : teamCount;
|
||||||
|
const requestedRounds =
|
||||||
|
maxRounds === undefined
|
||||||
|
? fullRoundCount
|
||||||
|
: Number.isFinite(maxRounds)
|
||||||
|
? Math.floor(maxRounds)
|
||||||
|
: fullRoundCount;
|
||||||
|
return Math.max(0, Math.min(fullRoundCount, requestedRounds));
|
||||||
|
}
|
||||||
|
|
||||||
function normalizeTeams(
|
function normalizeTeams(
|
||||||
teams: readonly CompetitionGraphTeam[],
|
teams: readonly CompetitionGraphTeam[],
|
||||||
): CompetitionGraphTeam[] {
|
): CompetitionGraphTeam[] {
|
||||||
|
|||||||
@@ -1,6 +1,110 @@
|
|||||||
import { projectSeries } from './series-projector';
|
import { projectSeries } from './series-projector';
|
||||||
|
|
||||||
describe('projectSeries', () => {
|
describe('projectSeries', () => {
|
||||||
|
it.each([
|
||||||
|
['a known local time', '21:30'],
|
||||||
|
['an unknown local time', null],
|
||||||
|
] as const)('preserves an optional Series schedule with %s', (_, time) => {
|
||||||
|
const schedule = {
|
||||||
|
date: '2026-07-15',
|
||||||
|
time,
|
||||||
|
timeZone: 'Asia/Seoul' as const,
|
||||||
|
};
|
||||||
|
const definition = {
|
||||||
|
...seriesDefinition({
|
||||||
|
id: `series-scheduled-${time ?? 'unknown'}`,
|
||||||
|
stage: 'upper',
|
||||||
|
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
|
||||||
|
}),
|
||||||
|
schedule,
|
||||||
|
};
|
||||||
|
|
||||||
|
const projection = projectSeries({
|
||||||
|
definition,
|
||||||
|
participants: ['team-8', 'team-3'],
|
||||||
|
facts: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(projection).toMatchObject({
|
||||||
|
status: 'ready',
|
||||||
|
schedule,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps an existing definition without a schedule explicitly unscheduled', () => {
|
||||||
|
const definition = seriesDefinition({
|
||||||
|
id: 'series-unscheduled',
|
||||||
|
stage: 'upper',
|
||||||
|
rule: { type: 'first-to', winsRequired: 1, maxGames: 1 },
|
||||||
|
});
|
||||||
|
|
||||||
|
const projection = projectSeries({
|
||||||
|
definition,
|
||||||
|
participants: ['team-8', 'team-3'],
|
||||||
|
facts: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(projection).not.toHaveProperty('schedule');
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[
|
||||||
|
'an impossible calendar date',
|
||||||
|
{ date: '2026-02-30', time: '21:30', timeZone: 'Asia/Seoul' },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'an out-of-range local time',
|
||||||
|
{ date: '2026-07-15', time: '24:00', timeZone: 'Asia/Seoul' },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'a non-canonical time zone',
|
||||||
|
{ date: '2026-07-15', time: '21:30', timeZone: 'UTC' },
|
||||||
|
],
|
||||||
|
])('rejects a Series schedule with %s', (_, schedule) => {
|
||||||
|
const definition = {
|
||||||
|
...seriesDefinition({
|
||||||
|
id: `series-invalid-schedule-${schedule.date}-${schedule.time}`,
|
||||||
|
stage: 'upper',
|
||||||
|
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
|
||||||
|
}),
|
||||||
|
schedule,
|
||||||
|
} as unknown as Parameters<typeof projectSeries>[0]['definition'];
|
||||||
|
|
||||||
|
expectInvariant(
|
||||||
|
() =>
|
||||||
|
projectSeries({
|
||||||
|
definition,
|
||||||
|
participants: ['team-8', 'team-3'],
|
||||||
|
facts: [],
|
||||||
|
}),
|
||||||
|
'SERIES_DEFINITION_INVALID',
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([null, false, ''])(
|
||||||
|
'rejects a non-object Series schedule value %p',
|
||||||
|
(schedule) => {
|
||||||
|
const definition = {
|
||||||
|
...seriesDefinition({
|
||||||
|
id: 'series-invalid-schedule-shape',
|
||||||
|
stage: 'upper',
|
||||||
|
rule: { type: 'first-to' as const, winsRequired: 1, maxGames: 1 },
|
||||||
|
}),
|
||||||
|
schedule,
|
||||||
|
} as unknown as Parameters<typeof projectSeries>[0]['definition'];
|
||||||
|
|
||||||
|
expectInvariant(
|
||||||
|
() =>
|
||||||
|
projectSeries({
|
||||||
|
definition,
|
||||||
|
participants: ['team-8', 'team-3'],
|
||||||
|
facts: [],
|
||||||
|
}),
|
||||||
|
'SERIES_DEFINITION_INVALID',
|
||||||
|
);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('keeps a fixed-games pair in progress until every game slot is filled', () => {
|
it('keeps a fixed-games pair in progress until every game slot is filled', () => {
|
||||||
const definition = seriesDefinition({
|
const definition = seriesDefinition({
|
||||||
id: 'series-pair',
|
id: 'series-pair',
|
||||||
|
|||||||
@@ -13,6 +13,12 @@ export type SeriesRule =
|
|||||||
drawPolicy: 'allow' | 'tiebreak-required';
|
drawPolicy: 'allow' | 'tiebreak-required';
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export interface SeriesSchedule {
|
||||||
|
date: string;
|
||||||
|
time: string | null;
|
||||||
|
timeZone: 'Asia/Seoul';
|
||||||
|
}
|
||||||
|
|
||||||
export interface SeriesDefinitionLike {
|
export interface SeriesDefinitionLike {
|
||||||
id: string;
|
id: string;
|
||||||
code?: string;
|
code?: string;
|
||||||
@@ -26,6 +32,7 @@ export interface SeriesDefinitionLike {
|
|||||||
source: Readonly<Record<string, unknown>>;
|
source: Readonly<Record<string, unknown>>;
|
||||||
}>;
|
}>;
|
||||||
rule: SeriesRule;
|
rule: SeriesRule;
|
||||||
|
schedule?: SeriesSchedule;
|
||||||
gameSlots: ReadonlyArray<{
|
gameSlots: ReadonlyArray<{
|
||||||
id: string;
|
id: string;
|
||||||
seriesId: string;
|
seriesId: string;
|
||||||
@@ -75,6 +82,7 @@ interface SeriesProjectionBase {
|
|||||||
code?: string;
|
code?: string;
|
||||||
stage: SeriesDefinitionLike['stage'];
|
stage: SeriesDefinitionLike['stage'];
|
||||||
rule: SeriesRule;
|
rule: SeriesRule;
|
||||||
|
schedule?: SeriesSchedule;
|
||||||
entries: [SeriesProjectionEntry, SeriesProjectionEntry];
|
entries: [SeriesProjectionEntry, SeriesProjectionEntry];
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -311,6 +319,15 @@ function validateDefinition(definition: SeriesDefinitionLike): void {
|
|||||||
`Series ${definition.id} must define exactly the local A and B slots`,
|
`Series ${definition.id} must define exactly the local A and B slots`,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const schedule: unknown = definition.schedule;
|
||||||
|
if (schedule !== undefined) {
|
||||||
|
assertCompetitionInvariant(
|
||||||
|
isSeriesSchedule(schedule),
|
||||||
|
'SERIES_DEFINITION_INVALID',
|
||||||
|
`Series ${definition.id} has an invalid schedule`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const requiredSlots =
|
const requiredSlots =
|
||||||
definition.rule.type === 'fixed-games'
|
definition.rule.type === 'fixed-games'
|
||||||
? definition.rule.gameCount
|
? definition.rule.gameCount
|
||||||
@@ -753,6 +770,7 @@ function projectionBase(
|
|||||||
...(definition.code ? { code: definition.code } : {}),
|
...(definition.code ? { code: definition.code } : {}),
|
||||||
stage: definition.stage,
|
stage: definition.stage,
|
||||||
rule: definition.rule,
|
rule: definition.rule,
|
||||||
|
...(definition.schedule ? { schedule: { ...definition.schedule } } : {}),
|
||||||
entries: [
|
entries: [
|
||||||
{ slot: 'A', teamId: participants[0], gameWins: 0 },
|
{ slot: 'A', teamId: participants[0], gameWins: 0 },
|
||||||
{ slot: 'B', teamId: participants[1], gameWins: 0 },
|
{ slot: 'B', teamId: participants[1], gameWins: 0 },
|
||||||
@@ -760,6 +778,35 @@ function projectionBase(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function isValidLocalDate(value: string): boolean {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||||
|
if (!match) return false;
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
const date = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
return (
|
||||||
|
date.getUTCFullYear() === year &&
|
||||||
|
date.getUTCMonth() === month - 1 &&
|
||||||
|
date.getUTCDate() === day
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSeriesSchedule(value: unknown): value is SeriesSchedule {
|
||||||
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const schedule = value as Record<string, unknown>;
|
||||||
|
return (
|
||||||
|
typeof schedule.date === 'string' &&
|
||||||
|
isValidLocalDate(schedule.date) &&
|
||||||
|
(schedule.time === null ||
|
||||||
|
(typeof schedule.time === 'string' &&
|
||||||
|
/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(schedule.time))) &&
|
||||||
|
schedule.timeZone === 'Asia/Seoul'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function entriesFor(
|
function entriesFor(
|
||||||
participants: [string, string],
|
participants: [string, string],
|
||||||
winsByTeam: Map<string, number>,
|
winsByTeam: Map<string, number>,
|
||||||
|
|||||||
@@ -1,9 +1,75 @@
|
|||||||
|
import mongoose from 'mongoose';
|
||||||
import {
|
import {
|
||||||
|
ConnectionService,
|
||||||
resolveMongoAppName,
|
resolveMongoAppName,
|
||||||
resolveMongoConnectionOptions,
|
resolveMongoConnectionOptions,
|
||||||
resolveMongoDbName,
|
resolveMongoDbName,
|
||||||
} from './connection.service';
|
} from './connection.service';
|
||||||
|
|
||||||
|
function createFakeConnection(connectionId: string) {
|
||||||
|
const models: Record<string, unknown> = {};
|
||||||
|
return {
|
||||||
|
readyState: mongoose.ConnectionStates.connected,
|
||||||
|
models,
|
||||||
|
model: jest.fn((name: string) => {
|
||||||
|
const model = { connectionId, modelName: name };
|
||||||
|
models[name] = model;
|
||||||
|
return model;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('ConnectionService', () => {
|
||||||
|
afterEach(() => {
|
||||||
|
jest.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shares one MongoDB connection across concurrent initialization calls', async () => {
|
||||||
|
const connection = createFakeConnection('shared');
|
||||||
|
const createConnection = jest
|
||||||
|
.spyOn(mongoose, 'createConnection')
|
||||||
|
.mockReturnValue({
|
||||||
|
asPromise: jest.fn().mockResolvedValue(connection),
|
||||||
|
} as never);
|
||||||
|
const service = new ConnectionService({
|
||||||
|
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
const [first, second] = await Promise.all([
|
||||||
|
service.getConnection(),
|
||||||
|
service.getConnection(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(first).toBe(connection);
|
||||||
|
expect(second).toBe(connection);
|
||||||
|
expect(createConnection).toHaveBeenCalledTimes(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rebuilds models from the replacement connection after disconnect', async () => {
|
||||||
|
const firstConnection = createFakeConnection('first');
|
||||||
|
const secondConnection = createFakeConnection('second');
|
||||||
|
jest
|
||||||
|
.spyOn(mongoose, 'createConnection')
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
asPromise: jest.fn().mockResolvedValue(firstConnection),
|
||||||
|
} as never)
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
asPromise: jest.fn().mockResolvedValue(secondConnection),
|
||||||
|
} as never);
|
||||||
|
const service = new ConnectionService({
|
||||||
|
get: jest.fn().mockResolvedValue('mongodb://localhost/test'),
|
||||||
|
} as never);
|
||||||
|
|
||||||
|
const firstModel = await service.getModel('match');
|
||||||
|
firstConnection.readyState = mongoose.ConnectionStates.disconnected;
|
||||||
|
const secondModel = await service.getModel('match');
|
||||||
|
|
||||||
|
expect(firstModel).toMatchObject({ connectionId: 'first' });
|
||||||
|
expect(secondModel).toMatchObject({ connectionId: 'second' });
|
||||||
|
expect(secondModel).not.toBe(firstModel);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe('resolveMongoDbName', () => {
|
describe('resolveMongoDbName', () => {
|
||||||
it('uses production database only for prod', () => {
|
it('uses production database only for prod', () => {
|
||||||
expect(resolveMongoDbName('prod')).toBe('lolympus');
|
expect(resolveMongoDbName('prod')).toBe('lolympus');
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ export function resolveMongoConnectionOptions(
|
|||||||
export class ConnectionService implements OnModuleInit {
|
export class ConnectionService implements OnModuleInit {
|
||||||
private readonly logger = new Logger(ConnectionService.name);
|
private readonly logger = new Logger(ConnectionService.name);
|
||||||
private connection: mongoose.Connection | null = null;
|
private connection: mongoose.Connection | null = null;
|
||||||
|
private connectionPromise: Promise<mongoose.Connection> | null = null;
|
||||||
constructor(private readonly secretService: SecretService) {}
|
constructor(private readonly secretService: SecretService) {}
|
||||||
|
|
||||||
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
|
||||||
@@ -51,35 +52,49 @@ export class ConnectionService implements OnModuleInit {
|
|||||||
return this.connection;
|
return this.connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const pendingConnection = this.connectionPromise ?? this.openConnection();
|
||||||
|
this.connectionPromise = pendingConnection;
|
||||||
|
try {
|
||||||
|
return await pendingConnection;
|
||||||
|
} finally {
|
||||||
|
if (this.connectionPromise === pendingConnection) {
|
||||||
|
this.connectionPromise = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async openConnection(): Promise<mongoose.Connection> {
|
||||||
const connectionString = await this.secretService.get(
|
const connectionString = await this.secretService.get(
|
||||||
'MONGODB_CONNECTION_STRING',
|
'MONGODB_CONNECTION_STRING',
|
||||||
);
|
);
|
||||||
const dbName = resolveMongoDbName();
|
const dbName = resolveMongoDbName();
|
||||||
const appName = resolveMongoAppName();
|
const appName = resolveMongoAppName();
|
||||||
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
|
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
|
||||||
const defaultConnection = await mongoose
|
const connection = await mongoose
|
||||||
.createConnection(connectionString, connectionOptions)
|
.createConnection(connectionString, connectionOptions)
|
||||||
.asPromise();
|
.asPromise();
|
||||||
this.connection = defaultConnection;
|
|
||||||
|
this.connection = connection;
|
||||||
|
this.tournamentModels = null;
|
||||||
this.logger.log(
|
this.logger.log(
|
||||||
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
|
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
|
||||||
connectionOptions.autoIndex === true
|
connectionOptions.autoIndex === true
|
||||||
}`,
|
}`,
|
||||||
);
|
);
|
||||||
|
|
||||||
return this.connection;
|
return connection;
|
||||||
}
|
}
|
||||||
|
|
||||||
public async getModel<K extends keyof TournamentModelTypes>(
|
public async getModel<K extends keyof TournamentModelTypes>(
|
||||||
modelKey: K,
|
modelKey: K,
|
||||||
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
|
||||||
|
const connection = await this.getConnection();
|
||||||
if (this.tournamentModels)
|
if (this.tournamentModels)
|
||||||
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
return this.tournamentModels.get(modelKey) as mongoose.Model<
|
||||||
TournamentModelTypes[K]
|
TournamentModelTypes[K]
|
||||||
>;
|
>;
|
||||||
|
|
||||||
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
|
||||||
const connection = await this.getConnection();
|
|
||||||
|
|
||||||
tournamentModelDefinitions.forEach((modelDefinition) => {
|
tournamentModelDefinitions.forEach((modelDefinition) => {
|
||||||
applyMongoosePerformancePlugin(modelDefinition.schema);
|
applyMongoosePerformancePlugin(modelDefinition.schema);
|
||||||
|
|||||||
+1287
-21
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -33,12 +33,73 @@ describe('migrateCompetitionDomain', () => {
|
|||||||
factCount: 1,
|
factCount: 1,
|
||||||
assignmentCount: 1,
|
assignmentCount: 1,
|
||||||
});
|
});
|
||||||
|
if (result.matches[0].status !== 'ready') {
|
||||||
|
throw new Error('Expected a ready dry-run result.');
|
||||||
|
}
|
||||||
|
expect(result.matches[0].planHash).toMatch(/^sha256:[a-f0-9]{64}$/);
|
||||||
|
const repeated = await migrateCompetitionDomain(db);
|
||||||
|
expect(repeated.matches[0]).toMatchObject({ status: 'ready' });
|
||||||
|
if (repeated.matches[0].status !== 'ready') {
|
||||||
|
throw new Error('Expected a repeated ready dry-run result.');
|
||||||
|
}
|
||||||
|
expect(repeated.matches[0].planHash).toBe(result.matches[0].planHash);
|
||||||
expect(startSession).not.toHaveBeenCalled();
|
expect(startSession).not.toHaveBeenCalled();
|
||||||
expect(db.writeCount).toBe(0);
|
expect(db.writeCount).toBe(0);
|
||||||
expect(db.docs('competition')).toHaveLength(0);
|
expect(db.docs('competition')).toHaveLength(0);
|
||||||
expect(db.createdIndexes).toHaveLength(0);
|
expect(db.createdIndexes).toHaveLength(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('reports apply-time global identity conflicts during dry-run without writes', async () => {
|
||||||
|
const riotMatchId = 'KR_DRY_RUN_GLOBAL_CONFLICT';
|
||||||
|
const match = readyMatch(riotMatchId);
|
||||||
|
const conflictingFactId = objectId();
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [match],
|
||||||
|
riotMatch: [riotArchive(riotMatchId)],
|
||||||
|
tournamentCode: [usedTournamentCode(match, riotMatchId)],
|
||||||
|
competition_fact: [
|
||||||
|
{
|
||||||
|
_id: conflictingFactId,
|
||||||
|
competitionId: objectId(),
|
||||||
|
type: 'game-accepted',
|
||||||
|
evidence: { type: 'riot', riotMatchId },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const dryRun = await migrateCompetitionDomain(db);
|
||||||
|
|
||||||
|
expect(dryRun.summary).toMatchObject({
|
||||||
|
scanned: 1,
|
||||||
|
ready: 0,
|
||||||
|
applied: 0,
|
||||||
|
quarantined: 1,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
expect(dryRun.matches[0]).toMatchObject({ status: 'quarantined' });
|
||||||
|
if (dryRun.matches[0].status !== 'quarantined') {
|
||||||
|
throw new Error('Expected a quarantined dry-run result.');
|
||||||
|
}
|
||||||
|
const conflict = dryRun.matches[0].reasons.find(
|
||||||
|
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
||||||
|
);
|
||||||
|
expect(conflict?.details?.collection).toBe('competition_fact');
|
||||||
|
expect(conflict?.details?.indexName).toBe('evidence.riotMatchId_1');
|
||||||
|
expect(conflict?.details?.conflictingDocumentId).toBe(
|
||||||
|
conflictingFactId.toHexString(),
|
||||||
|
);
|
||||||
|
expect(db.writeCount).toBe(0);
|
||||||
|
expect(db.createdIndexes).toHaveLength(0);
|
||||||
|
|
||||||
|
const applied = await migrateCompetitionDomain(db, {
|
||||||
|
dryRun: false,
|
||||||
|
startSession: () => Promise.resolve(new FakeSession()),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(applied.summary).toMatchObject({ applied: 0, quarantined: 1 });
|
||||||
|
expect(applied.matches[0]).toEqual(dryRun.matches[0]);
|
||||||
|
});
|
||||||
|
|
||||||
it.each([
|
it.each([
|
||||||
['absent', (match: AnyDoc) => delete match.gameMode],
|
['absent', (match: AnyDoc) => delete match.gameMode],
|
||||||
['null', (match: AnyDoc) => (match.gameMode = null)],
|
['null', (match: AnyDoc) => (match.gameMode = null)],
|
||||||
@@ -157,6 +218,188 @@ describe('migrateCompetitionDomain', () => {
|
|||||||
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
|
expect(sessions[1]).toMatchObject({ committed: 1, aborted: 0, ended: 1 });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('persists the source voidedAt timestamp without synthesizing it from usedAt', async () => {
|
||||||
|
const match = readyMatch('KR_VOIDED_TIMESTAMP');
|
||||||
|
const code = usedTournamentCode(match, 'KR_VOIDED_TIMESTAMP');
|
||||||
|
code.state = 'voided';
|
||||||
|
code.voidedAt = new Date('2026-07-03T00:00:00.000Z');
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [match],
|
||||||
|
riotMatch: [riotArchive('KR_VOIDED_TIMESTAMP')],
|
||||||
|
tournamentCode: [code],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await migrateCompetitionDomain(db, {
|
||||||
|
dryRun: false,
|
||||||
|
startSession: () => Promise.resolve(new FakeSession()),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result.summary).toMatchObject({ applied: 1, failed: 0 });
|
||||||
|
expect(db.docs('tournament_code_assignment')).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
state: 'voided',
|
||||||
|
voidedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('hydrates Riot occurrence evidence and persists the normalized used transition idempotently', async () => {
|
||||||
|
const riotMatchId = 'KR_LEGACY_USED_TRANSITION';
|
||||||
|
const match = readyMatch(riotMatchId);
|
||||||
|
match.updatedAt = new Date('2026-07-03T00:06:00.000Z');
|
||||||
|
const legacyOccurrenceAt = new Date(1_782_864_000_000 + 1800 * 1000);
|
||||||
|
const code = usedTournamentCode(match, riotMatchId);
|
||||||
|
code.reservedAt = new Date('2026-07-03T00:00:00.000Z');
|
||||||
|
code.usedAt = legacyOccurrenceAt;
|
||||||
|
code.updatedAt = new Date('2026-07-03T00:05:00.000Z');
|
||||||
|
const originalCode = canonical(code);
|
||||||
|
const archive = riotArchive(riotMatchId);
|
||||||
|
archive.raw = {
|
||||||
|
info: {
|
||||||
|
gameCreation: 1_782_864_000_000,
|
||||||
|
gameEndTimestamp: legacyOccurrenceAt.getTime(),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [match],
|
||||||
|
riotMatch: [archive],
|
||||||
|
tournamentCode: [code],
|
||||||
|
});
|
||||||
|
|
||||||
|
const dryRun = await migrateCompetitionDomain(db);
|
||||||
|
|
||||||
|
expect(dryRun.summary).toMatchObject({
|
||||||
|
ready: 1,
|
||||||
|
quarantined: 0,
|
||||||
|
warnings: 1,
|
||||||
|
});
|
||||||
|
const warning = dryRun.matches[0].warnings.find(
|
||||||
|
({ code: warningCode }) =>
|
||||||
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
||||||
|
);
|
||||||
|
expect(warning?.details).toMatchObject({
|
||||||
|
originalReservedAt: '2026-07-03T00:00:00.000Z',
|
||||||
|
originalUsedAt: legacyOccurrenceAt.toISOString(),
|
||||||
|
sourceUpdatedAt: '2026-07-03T00:05:00.000Z',
|
||||||
|
normalizedUsedAt: '2026-07-03T00:05:00.000Z',
|
||||||
|
legacyOccurrenceSource: 'riot-archive-gameEndTimestamp',
|
||||||
|
riotMatchId,
|
||||||
|
strategy: 'use-persisted-transition-time',
|
||||||
|
});
|
||||||
|
expect(db.writeCount).toBe(0);
|
||||||
|
|
||||||
|
const firstApply = await migrateCompetitionDomain(db, {
|
||||||
|
dryRun: false,
|
||||||
|
startSession: () => Promise.resolve(new FakeSession()),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(firstApply.summary).toMatchObject({ applied: 1, failed: 0 });
|
||||||
|
expect(db.docs('tournament_code_assignment')).toContainEqual(
|
||||||
|
expect.objectContaining({
|
||||||
|
state: 'used',
|
||||||
|
reservedAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
usedAt: new Date('2026-07-03T00:05:00.000Z'),
|
||||||
|
createdAt: new Date('2026-07-03T00:00:00.000Z'),
|
||||||
|
updatedAt: new Date('2026-07-03T00:05:00.000Z'),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
expect(canonical(db.docs('tournamentCode')[0])).toBe(originalCode);
|
||||||
|
|
||||||
|
const replay = await migrateCompetitionDomain(db, {
|
||||||
|
dryRun: false,
|
||||||
|
startSession: () => Promise.resolve(new FakeSession()),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(replay.summary).toMatchObject({
|
||||||
|
applied: 0,
|
||||||
|
alreadyApplied: 1,
|
||||||
|
failed: 0,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
[
|
||||||
|
'raw.info.gameCreation',
|
||||||
|
{ raw: { info: { gameCreation: 1_782_864_000_000 } } },
|
||||||
|
],
|
||||||
|
[
|
||||||
|
'top-level gameCreation',
|
||||||
|
{
|
||||||
|
gameCreation: 1_782_864_000_000,
|
||||||
|
raw: { metadata: { matchId: 'KR_GAME_CREATION_FALLBACK' } },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
])(
|
||||||
|
'hydrates the %s Riot occurrence fallback',
|
||||||
|
async (_label, archiveFields) => {
|
||||||
|
const riotMatchId = 'KR_GAME_CREATION_FALLBACK';
|
||||||
|
const match = readyMatch(riotMatchId);
|
||||||
|
const code = usedTournamentCode(match, riotMatchId);
|
||||||
|
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
|
||||||
|
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
|
||||||
|
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
|
||||||
|
const archive = Object.assign(riotArchive(riotMatchId), archiveFields);
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [match],
|
||||||
|
riotMatch: [archive],
|
||||||
|
tournamentCode: [code],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await migrateCompetitionDomain(db);
|
||||||
|
|
||||||
|
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
|
||||||
|
const warning = result.matches[0].warnings.find(
|
||||||
|
({ code: warningCode }) =>
|
||||||
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
||||||
|
);
|
||||||
|
expect(warning?.details).toMatchObject({
|
||||||
|
originalUsedAt: '2026-07-01T00:00:00.000Z',
|
||||||
|
normalizedUsedAt: '2026-07-01T00:20:00.000Z',
|
||||||
|
legacyOccurrenceSource: 'riot-archive-gameCreation',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
['null', null],
|
||||||
|
['blank', ''],
|
||||||
|
['invalid', 'not-a-date'],
|
||||||
|
])(
|
||||||
|
'falls back to archive gameCreation when gameEndTimestamp is %s',
|
||||||
|
async (_label, invalidGameEnd) => {
|
||||||
|
const riotMatchId = 'KR_INVALID_ARCHIVE_GAME_END';
|
||||||
|
const match = readyMatch(riotMatchId);
|
||||||
|
const code = usedTournamentCode(match, riotMatchId);
|
||||||
|
code.reservedAt = new Date('2026-07-01T00:10:00.000Z');
|
||||||
|
code.usedAt = new Date('2026-07-01T00:00:00.000Z');
|
||||||
|
code.updatedAt = new Date('2026-07-01T00:20:00.000Z');
|
||||||
|
const archive = riotArchive(riotMatchId);
|
||||||
|
archive.raw = {
|
||||||
|
info: {
|
||||||
|
gameEndTimestamp: invalidGameEnd,
|
||||||
|
gameCreation: 1_782_864_000_000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [match],
|
||||||
|
riotMatch: [archive],
|
||||||
|
tournamentCode: [code],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await migrateCompetitionDomain(db);
|
||||||
|
|
||||||
|
expect(result.summary).toMatchObject({ ready: 1, quarantined: 0 });
|
||||||
|
const warning = result.matches[0].warnings.find(
|
||||||
|
({ code: warningCode }) =>
|
||||||
|
warningCode === 'LEGACY_USED_CODE_TRANSITION_TIME_NORMALIZED',
|
||||||
|
);
|
||||||
|
expect(warning?.details).toMatchObject({
|
||||||
|
legacyOccurrenceSource: 'riot-archive-gameCreation',
|
||||||
|
});
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
|
it('quarantines an ambiguous Match without changing any legacy Match field', async () => {
|
||||||
const match = ambiguousMatch();
|
const match = ambiguousMatch();
|
||||||
const before = canonical(match);
|
const before = canonical(match);
|
||||||
@@ -364,6 +607,46 @@ describe('migrateCompetitionDomain', () => {
|
|||||||
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
|
expect(db.docs('competition_migration_quarantine')).toHaveLength(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('detects the same global identity collision between dry-run plans as sequential apply', async () => {
|
||||||
|
const riotMatchId = 'KR_SHARED_DRY_RUN_MIGRATION';
|
||||||
|
const firstMatch = readyMatch(riotMatchId);
|
||||||
|
const secondMatch = readyMatch(riotMatchId);
|
||||||
|
const db = new MemoryMigrationDb({
|
||||||
|
match: [firstMatch, secondMatch],
|
||||||
|
riotMatch: [riotArchive(riotMatchId)],
|
||||||
|
tournamentCode: [
|
||||||
|
usedTournamentCode(firstMatch, riotMatchId),
|
||||||
|
usedTournamentCode(secondMatch, riotMatchId),
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const dryRun = await migrateCompetitionDomain(db);
|
||||||
|
|
||||||
|
expect(dryRun.summary).toMatchObject({ ready: 1, quarantined: 1 });
|
||||||
|
expect(dryRun.matches.map(({ status }) => status)).toEqual([
|
||||||
|
'ready',
|
||||||
|
'quarantined',
|
||||||
|
]);
|
||||||
|
expect(dryRun.matches[1]).toMatchObject({ status: 'quarantined' });
|
||||||
|
if (dryRun.matches[1].status !== 'quarantined') {
|
||||||
|
throw new Error('Expected the second dry-run result to be quarantined.');
|
||||||
|
}
|
||||||
|
expect(
|
||||||
|
dryRun.matches[1].reasons.some(
|
||||||
|
({ code }) => code === 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
expect(db.writeCount).toBe(0);
|
||||||
|
|
||||||
|
const applied = await migrateCompetitionDomain(db, {
|
||||||
|
dryRun: false,
|
||||||
|
startSession: () => Promise.resolve(new FakeSession()),
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(applied.summary).toMatchObject({ applied: 1, quarantined: 1 });
|
||||||
|
expect(applied.matches[1]).toEqual(dryRun.matches[1]);
|
||||||
|
});
|
||||||
|
|
||||||
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
|
it('resumes repeated limited apply runs after the durable Match checkpoint', async () => {
|
||||||
const firstMatch = readyMatch('KR_BATCH_1');
|
const firstMatch = readyMatch('KR_BATCH_1');
|
||||||
const secondMatch = readyMatch('KR_BATCH_2');
|
const secondMatch = readyMatch('KR_BATCH_2');
|
||||||
|
|||||||
@@ -98,6 +98,7 @@ export type CompetitionDomainMigrationMatchResult =
|
|||||||
status: 'ready' | 'applied';
|
status: 'ready' | 'applied';
|
||||||
factCount: number;
|
factCount: number;
|
||||||
assignmentCount: number;
|
assignmentCount: number;
|
||||||
|
planHash: string;
|
||||||
})
|
})
|
||||||
| (CompetitionDomainMigrationMatchBase & {
|
| (CompetitionDomainMigrationMatchBase & {
|
||||||
status: 'already-applied';
|
status: 'already-applied';
|
||||||
@@ -206,11 +207,17 @@ export async function migrateCompetitionDomain(
|
|||||||
resumeStart.startedAfterMatchId,
|
resumeStart.startedAfterMatchId,
|
||||||
);
|
);
|
||||||
const matches: CompetitionDomainMigrationMatchResult[] = [];
|
const matches: CompetitionDomainMigrationMatchResult[] = [];
|
||||||
|
const dryRunUniquenessClaims = new Map<string, ClaimedUniqueIdentity>();
|
||||||
let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
|
let checkpointAfterMatchId = resumeStart.startedAfterMatchId;
|
||||||
let haltedOnFailure = false;
|
let haltedOnFailure = false;
|
||||||
for (const [index, scannedMatch] of scan.matches.entries()) {
|
for (const [index, scannedMatch] of scan.matches.entries()) {
|
||||||
const result = dryRun
|
const result = dryRun
|
||||||
? await inspectMatch(db, scannedMatch, migrationRunId)
|
? await inspectMatch(
|
||||||
|
db,
|
||||||
|
scannedMatch,
|
||||||
|
migrationRunId,
|
||||||
|
dryRunUniquenessClaims,
|
||||||
|
)
|
||||||
: await applyMatch(db, scannedMatch, migrationRunId, options);
|
: await applyMatch(db, scannedMatch, migrationRunId, options);
|
||||||
matches.push(result);
|
matches.push(result);
|
||||||
options.onProgress?.({
|
options.onProgress?.({
|
||||||
@@ -433,6 +440,7 @@ async function inspectMatch(
|
|||||||
db: CompetitionDomainMigrationDb,
|
db: CompetitionDomainMigrationDb,
|
||||||
scannedMatch: AnyDocument,
|
scannedMatch: AnyDocument,
|
||||||
migrationRunId: string,
|
migrationRunId: string,
|
||||||
|
uniquenessClaims: Map<string, ClaimedUniqueIdentity>,
|
||||||
): Promise<CompetitionDomainMigrationMatchResult> {
|
): Promise<CompetitionDomainMigrationMatchResult> {
|
||||||
const matchId = idString(scannedMatch._id);
|
const matchId = idString(scannedMatch._id);
|
||||||
try {
|
try {
|
||||||
@@ -450,6 +458,21 @@ async function inspectMatch(
|
|||||||
|
|
||||||
const legacy = await hydrateLegacyMatch(db, scannedMatch);
|
const legacy = await hydrateLegacyMatch(db, scannedMatch);
|
||||||
const plan = planCompetitionMigration(legacy, { migrationRunId });
|
const plan = planCompetitionMigration(legacy, { migrationRunId });
|
||||||
|
if (plan.status === 'ready') {
|
||||||
|
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
|
||||||
|
db,
|
||||||
|
plan,
|
||||||
|
{ claims: uniquenessClaims },
|
||||||
|
);
|
||||||
|
if (uniquenessConflicts.length > 0) {
|
||||||
|
return {
|
||||||
|
status: 'quarantined',
|
||||||
|
matchId,
|
||||||
|
warnings: plan.warnings,
|
||||||
|
reasons: uniquenessConflicts,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
return planResult(matchId, plan);
|
return planResult(matchId, plan);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
return failedResult(matchId, error);
|
return failedResult(matchId, error);
|
||||||
@@ -521,7 +544,7 @@ async function applyMatch(
|
|||||||
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
|
const uniquenessConflicts = await findReadyPlanUniquenessConflicts(
|
||||||
db,
|
db,
|
||||||
plan,
|
plan,
|
||||||
session,
|
{ session },
|
||||||
);
|
);
|
||||||
if (uniquenessConflicts.length > 0) {
|
if (uniquenessConflicts.length > 0) {
|
||||||
await persistQuarantine(
|
await persistQuarantine(
|
||||||
@@ -577,6 +600,7 @@ async function applyMatch(
|
|||||||
competitionId,
|
competitionId,
|
||||||
factCount: plan.facts.length,
|
factCount: plan.facts.length,
|
||||||
assignmentCount: plan.assignments.length,
|
assignmentCount: plan.assignments.length,
|
||||||
|
planHash: readyPlanHash(plan),
|
||||||
warnings: plan.warnings,
|
warnings: plan.warnings,
|
||||||
};
|
};
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -592,12 +616,21 @@ interface UniqueIdentityCheck {
|
|||||||
indexName: string;
|
indexName: string;
|
||||||
filter: Record<string, unknown>;
|
filter: Record<string, unknown>;
|
||||||
expectedDocumentId: string;
|
expectedDocumentId: string;
|
||||||
|
expectedCompetitionId?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ClaimedUniqueIdentity {
|
||||||
|
documentId: string;
|
||||||
|
competitionId?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function findReadyPlanUniquenessConflicts(
|
async function findReadyPlanUniquenessConflicts(
|
||||||
db: CompetitionDomainMigrationDb,
|
db: CompetitionDomainMigrationDb,
|
||||||
plan: ReadyCompetitionMigrationPlan,
|
plan: ReadyCompetitionMigrationPlan,
|
||||||
session: CompetitionDomainMigrationSession,
|
options: {
|
||||||
|
session?: CompetitionDomainMigrationSession;
|
||||||
|
claims?: Map<string, ClaimedUniqueIdentity>;
|
||||||
|
} = {},
|
||||||
): Promise<CompetitionMigrationIssue[]> {
|
): Promise<CompetitionMigrationIssue[]> {
|
||||||
const checks: UniqueIdentityCheck[] = [
|
const checks: UniqueIdentityCheck[] = [
|
||||||
{
|
{
|
||||||
@@ -619,6 +652,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
ordinalWithinRevision: fact.ordinalWithinRevision,
|
ordinalWithinRevision: fact.ordinalWithinRevision,
|
||||||
},
|
},
|
||||||
expectedDocumentId: fact.id,
|
expectedDocumentId: fact.id,
|
||||||
|
expectedCompetitionId: fact.competitionId,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
collection: 'competition_fact',
|
collection: 'competition_fact',
|
||||||
@@ -629,6 +663,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
ordinalWithinRevision: fact.ordinalWithinRevision,
|
ordinalWithinRevision: fact.ordinalWithinRevision,
|
||||||
},
|
},
|
||||||
expectedDocumentId: fact.id,
|
expectedDocumentId: fact.id,
|
||||||
|
expectedCompetitionId: fact.competitionId,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
|
if (fact.type === 'game-accepted' && fact.evidence.type === 'riot') {
|
||||||
@@ -640,6 +675,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
'evidence.riotMatchId': fact.evidence.riotMatchId,
|
'evidence.riotMatchId': fact.evidence.riotMatchId,
|
||||||
},
|
},
|
||||||
expectedDocumentId: fact.id,
|
expectedDocumentId: fact.id,
|
||||||
|
expectedCompetitionId: fact.competitionId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -655,6 +691,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
state: { $in: ['reserved', 'used'] },
|
state: { $in: ['reserved', 'used'] },
|
||||||
},
|
},
|
||||||
expectedDocumentId: assignment.id,
|
expectedDocumentId: assignment.id,
|
||||||
|
expectedCompetitionId: assignment.competitionId,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
collection: 'tournament_code_assignment',
|
collection: 'tournament_code_assignment',
|
||||||
@@ -664,6 +701,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
state: { $in: ['reserved', 'used'] },
|
state: { $in: ['reserved', 'used'] },
|
||||||
},
|
},
|
||||||
expectedDocumentId: assignment.id,
|
expectedDocumentId: assignment.id,
|
||||||
|
expectedCompetitionId: assignment.competitionId,
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -673,6 +711,7 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
indexName: 'riotMatchId_1',
|
indexName: 'riotMatchId_1',
|
||||||
filter: { riotMatchId: assignment.riotMatchId },
|
filter: { riotMatchId: assignment.riotMatchId },
|
||||||
expectedDocumentId: assignment.id,
|
expectedDocumentId: assignment.id,
|
||||||
|
expectedCompetitionId: assignment.competitionId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -680,30 +719,66 @@ async function findReadyPlanUniquenessConflicts(
|
|||||||
const conflicts: CompetitionMigrationIssue[] = [];
|
const conflicts: CompetitionMigrationIssue[] = [];
|
||||||
// Mongo sessions do not support parallel operations inside one transaction.
|
// Mongo sessions do not support parallel operations inside one transaction.
|
||||||
for (const check of checks) {
|
for (const check of checks) {
|
||||||
|
const claim = options.claims?.get(uniqueIdentityKey(check));
|
||||||
|
if (claim && claim.documentId !== check.expectedDocumentId) {
|
||||||
|
conflicts.push(
|
||||||
|
uniqueIdentityConflict(check, {
|
||||||
|
_id: persistenceId(claim.documentId),
|
||||||
|
...(claim.competitionId
|
||||||
|
? { competitionId: persistenceId(claim.competitionId) }
|
||||||
|
: {}),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
const existing = await db
|
const existing = await db
|
||||||
.collection(check.collection)
|
.collection(check.collection)
|
||||||
.findOne(check.filter, { session });
|
.findOne(
|
||||||
|
check.filter,
|
||||||
|
options.session ? { session: options.session } : undefined,
|
||||||
|
);
|
||||||
if (!existing || idString(existing._id) === check.expectedDocumentId) {
|
if (!existing || idString(existing._id) === check.expectedDocumentId) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
conflicts.push({
|
conflicts.push(uniqueIdentityConflict(check, existing));
|
||||||
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
}
|
||||||
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
|
if (conflicts.length === 0 && options.claims) {
|
||||||
details: {
|
for (const check of checks) {
|
||||||
collection: check.collection,
|
options.claims.set(uniqueIdentityKey(check), {
|
||||||
indexName: check.indexName,
|
documentId: check.expectedDocumentId,
|
||||||
key: canonicalValue(check.filter) as Record<string, unknown>,
|
...(check.expectedCompetitionId
|
||||||
expectedDocumentId: check.expectedDocumentId,
|
? { competitionId: check.expectedCompetitionId }
|
||||||
conflictingDocumentId: idString(existing._id),
|
|
||||||
...(existing.competitionId
|
|
||||||
? { conflictingCompetitionId: idString(existing.competitionId) }
|
|
||||||
: {}),
|
: {}),
|
||||||
},
|
});
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
return conflicts;
|
return conflicts;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function uniqueIdentityKey(check: UniqueIdentityCheck): string {
|
||||||
|
return `${check.collection}:${check.indexName}:${canonicalJson(check.filter)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function uniqueIdentityConflict(
|
||||||
|
check: UniqueIdentityCheck,
|
||||||
|
existing: AnyDocument,
|
||||||
|
): CompetitionMigrationIssue {
|
||||||
|
return {
|
||||||
|
code: 'GLOBAL_UNIQUE_INDEX_CONFLICT',
|
||||||
|
message: `Migration input conflicts with ${check.collection}.${check.indexName}.`,
|
||||||
|
details: {
|
||||||
|
collection: check.collection,
|
||||||
|
indexName: check.indexName,
|
||||||
|
key: canonicalValue(check.filter) as Record<string, unknown>,
|
||||||
|
expectedDocumentId: check.expectedDocumentId,
|
||||||
|
conflictingDocumentId: idString(existing._id),
|
||||||
|
...(existing.competitionId
|
||||||
|
? { conflictingCompetitionId: idString(existing.competitionId) }
|
||||||
|
: {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
async function hydrateLegacyMatch(
|
async function hydrateLegacyMatch(
|
||||||
db: CompetitionDomainMigrationDb,
|
db: CompetitionDomainMigrationDb,
|
||||||
match: AnyDocument,
|
match: AnyDocument,
|
||||||
@@ -781,15 +856,67 @@ function hydrateLegacyGameEvidence(
|
|||||||
typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0
|
typeof game.payloadHash === 'string' && game.payloadHash.trim().length > 0
|
||||||
? game.payloadHash
|
? game.payloadHash
|
||||||
: undefined;
|
: undefined;
|
||||||
|
const archiveRaw = isRecord(archive.raw) ? archive.raw : undefined;
|
||||||
|
const archiveInfo = isRecord(archiveRaw?.info) ? archiveRaw.info : undefined;
|
||||||
|
const riotGameEndEvidence = resolveRiotGameEndEvidence(
|
||||||
|
archiveInfo,
|
||||||
|
archive.gameCreation,
|
||||||
|
);
|
||||||
return {
|
return {
|
||||||
...game,
|
...game,
|
||||||
riotArchivePresent: true,
|
riotArchivePresent: true,
|
||||||
|
...(riotGameEndEvidence === undefined
|
||||||
|
? {}
|
||||||
|
: {
|
||||||
|
riotGameEndedAt: riotGameEndEvidence.value,
|
||||||
|
riotGameEndedAtSource: riotGameEndEvidence.source,
|
||||||
|
}),
|
||||||
payloadHash:
|
payloadHash:
|
||||||
existingPayloadHash ??
|
existingPayloadHash ??
|
||||||
`sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`,
|
`sha256:${createNodeHash(canonicalJson(archive.raw ?? archive))}`,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function resolveRiotGameEndEvidence(
|
||||||
|
archiveInfo: Record<string, unknown> | undefined,
|
||||||
|
archiveGameCreation: unknown,
|
||||||
|
):
|
||||||
|
| {
|
||||||
|
value: unknown;
|
||||||
|
source: 'gameEndTimestamp' | 'gameCreation';
|
||||||
|
}
|
||||||
|
| undefined {
|
||||||
|
const candidates = [
|
||||||
|
{
|
||||||
|
value: archiveInfo?.gameEndTimestamp,
|
||||||
|
source: 'gameEndTimestamp' as const,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
value: archiveInfo?.gameCreation,
|
||||||
|
source: 'gameCreation' as const,
|
||||||
|
},
|
||||||
|
{ value: archiveGameCreation, source: 'gameCreation' as const },
|
||||||
|
];
|
||||||
|
return candidates.find(({ value }) => isValidRiotTimestamp(value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidRiotTimestamp(value: unknown): boolean {
|
||||||
|
if (value === undefined || value === null || value === '') return false;
|
||||||
|
if (typeof value === 'string' && value.trim() === '') return false;
|
||||||
|
if (typeof value === 'number' && !Number.isFinite(value)) return false;
|
||||||
|
const normalized =
|
||||||
|
typeof value === 'number' && value < 10_000_000_000 ? value * 1000 : value;
|
||||||
|
try {
|
||||||
|
const date =
|
||||||
|
normalized instanceof Date
|
||||||
|
? normalized
|
||||||
|
: new Date(normalized as string | number);
|
||||||
|
return !Number.isNaN(date.getTime());
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function upsertReadyPlan(
|
async function upsertReadyPlan(
|
||||||
db: CompetitionDomainMigrationDb,
|
db: CompetitionDomainMigrationDb,
|
||||||
plan: ReadyCompetitionMigrationPlan,
|
plan: ReadyCompetitionMigrationPlan,
|
||||||
@@ -1085,12 +1212,18 @@ function assignmentForPersistence(
|
|||||||
): AnyDocument {
|
): AnyDocument {
|
||||||
const reservedAt = new Date(assignment.reservedAt);
|
const reservedAt = new Date(assignment.reservedAt);
|
||||||
const updatedAt = new Date(
|
const updatedAt = new Date(
|
||||||
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
|
assignment.voidedAt ??
|
||||||
|
assignment.releasedAt ??
|
||||||
|
assignment.usedAt ??
|
||||||
|
assignment.reservedAt,
|
||||||
);
|
);
|
||||||
const voidedAt =
|
const voidedAt =
|
||||||
assignment.state === 'voided'
|
assignment.state === 'voided'
|
||||||
? new Date(
|
? new Date(
|
||||||
assignment.releasedAt ?? assignment.usedAt ?? assignment.reservedAt,
|
assignment.voidedAt ??
|
||||||
|
assignment.releasedAt ??
|
||||||
|
assignment.usedAt ??
|
||||||
|
assignment.reservedAt,
|
||||||
)
|
)
|
||||||
: undefined;
|
: undefined;
|
||||||
return {
|
return {
|
||||||
@@ -1138,10 +1271,23 @@ function planResult(
|
|||||||
competitionId: plan.competition.id,
|
competitionId: plan.competition.id,
|
||||||
factCount: plan.facts.length,
|
factCount: plan.facts.length,
|
||||||
assignmentCount: plan.assignments.length,
|
assignmentCount: plan.assignments.length,
|
||||||
|
planHash: readyPlanHash(plan),
|
||||||
warnings: plan.warnings,
|
warnings: plan.warnings,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function readyPlanHash(plan: ReadyCompetitionMigrationPlan): string {
|
||||||
|
return `sha256:${createHash('sha256')
|
||||||
|
.update(
|
||||||
|
canonicalJson({
|
||||||
|
competition: plan.competition,
|
||||||
|
facts: plan.facts,
|
||||||
|
assignments: plan.assignments,
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.digest('hex')}`;
|
||||||
|
}
|
||||||
|
|
||||||
function failedResult(
|
function failedResult(
|
||||||
matchId: string,
|
matchId: string,
|
||||||
error: unknown,
|
error: unknown,
|
||||||
|
|||||||
@@ -940,6 +940,21 @@ export interface MatchStatsSkillBuildEvent {
|
|||||||
levelUpType?: string;
|
levelUpType?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MatchStatsCheckpoint {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchStatsParticipantCheckpoints {
|
||||||
|
at10?: MatchStatsCheckpoint;
|
||||||
|
at15?: MatchStatsCheckpoint;
|
||||||
|
}
|
||||||
|
|
||||||
export interface MatchStatsRecord {
|
export interface MatchStatsRecord {
|
||||||
matchId: string;
|
matchId: string;
|
||||||
title: string;
|
title: string;
|
||||||
@@ -948,6 +963,8 @@ export interface MatchStatsRecord {
|
|||||||
riotMatchId: string;
|
riotMatchId: string;
|
||||||
gameCreation: number;
|
gameCreation: number;
|
||||||
gameDuration: number;
|
gameDuration: number;
|
||||||
|
participantId?: number;
|
||||||
|
checkpoints?: MatchStatsParticipantCheckpoints;
|
||||||
userId: string;
|
userId: string;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
@@ -994,6 +1011,7 @@ export interface MatchStatsGameDetail {
|
|||||||
timeline: MatchStatsTimelinePoint[];
|
timeline: MatchStatsTimelinePoint[];
|
||||||
timelineLoaded?: boolean;
|
timelineLoaded?: boolean;
|
||||||
objectiveEvents: MatchStatsObjectiveEvent[];
|
objectiveEvents: MatchStatsObjectiveEvent[];
|
||||||
|
timelineEvents?: MatchStatsTimelineEvent[];
|
||||||
teams: Array<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -1021,6 +1039,28 @@ export interface MatchStatsObjectiveEvent {
|
|||||||
monsterSubType?: string;
|
monsterSubType?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MatchStatsChampionKillEvent {
|
||||||
|
timestamp: number;
|
||||||
|
side?: TeamSide;
|
||||||
|
type: 'championKill';
|
||||||
|
killerParticipantId?: number;
|
||||||
|
victimParticipantId?: number;
|
||||||
|
assistingParticipantIds?: number[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface MatchStatsBuildingEvent {
|
||||||
|
timestamp: number;
|
||||||
|
side: TeamSide;
|
||||||
|
type: 'tower' | 'inhibitor';
|
||||||
|
killerParticipantId?: number;
|
||||||
|
towerType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type MatchStatsTimelineEvent =
|
||||||
|
| MatchStatsObjectiveEvent
|
||||||
|
| MatchStatsChampionKillEvent
|
||||||
|
| MatchStatsBuildingEvent;
|
||||||
|
|
||||||
export interface MatchStatsTimelinePoint {
|
export interface MatchStatsTimelinePoint {
|
||||||
timestamp: number;
|
timestamp: number;
|
||||||
blue: { gold: number; xp: number };
|
blue: { gold: number; xp: number };
|
||||||
|
|||||||
@@ -214,4 +214,52 @@ describe('RiotMatchService', () => {
|
|||||||
levelUpType: 'NORMAL',
|
levelUpType: 'NORMAL',
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('rejects non-numeric champion kill victim ids', async () => {
|
||||||
|
const payload = {
|
||||||
|
metadata: {
|
||||||
|
dataVersion: '2',
|
||||||
|
matchId: 'KR_8188913502',
|
||||||
|
participants: ['puuid-1'],
|
||||||
|
},
|
||||||
|
info: {
|
||||||
|
frameInterval: 60_000,
|
||||||
|
frames: [
|
||||||
|
{
|
||||||
|
timestamp: 60_000,
|
||||||
|
events: [
|
||||||
|
{
|
||||||
|
type: 'CHAMPION_KILL',
|
||||||
|
timestamp: 30_000,
|
||||||
|
killerId: 1,
|
||||||
|
victimId: '2',
|
||||||
|
},
|
||||||
|
],
|
||||||
|
participantFrames: {
|
||||||
|
'1': {
|
||||||
|
participantId: 1,
|
||||||
|
totalGold: 1_150,
|
||||||
|
xp: 550,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const riotClientService = {
|
||||||
|
get: jest.fn(
|
||||||
|
<T>(_path: string, _options: unknown, parser?: RiotResponseParser<T>) =>
|
||||||
|
Promise.resolve().then(() =>
|
||||||
|
parser ? parser(payload) : (payload as T),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
} as unknown as RiotClientService;
|
||||||
|
const service = new RiotMatchService(riotClientService);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
service.getMatchTimeline('KR_8188913502', { region: 'asia' }),
|
||||||
|
).rejects.toThrow(
|
||||||
|
'timeline.info.frames[0].events[0].victimId must be a finite number when present.',
|
||||||
|
);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
@@ -415,6 +415,10 @@ function parseTimelineEvent(
|
|||||||
value.type,
|
value.type,
|
||||||
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
|
`timeline.info.frames[${frameIndex}].events[${eventIndex}].type`,
|
||||||
),
|
),
|
||||||
|
victimId: optionalNumber(
|
||||||
|
value.victimId,
|
||||||
|
`timeline.info.frames[${frameIndex}].events[${eventIndex}].victimId`,
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -291,6 +291,7 @@ export interface RiotMatchTimelineEventDto extends Record<string, unknown> {
|
|||||||
skillSlot?: number;
|
skillSlot?: number;
|
||||||
teamId?: number;
|
teamId?: number;
|
||||||
towerType?: string;
|
towerType?: string;
|
||||||
|
victimId?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RiotMatchTimelineParticipantFrameDto
|
export interface RiotMatchTimelineParticipantFrameDto
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ describe('CompetitionAssignmentProvisioner', () => {
|
|||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
new: true,
|
returnDocument: 'after',
|
||||||
session: harness.session,
|
session: harness.session,
|
||||||
sort: { expiresAt: 1 },
|
sort: { expiresAt: 1 },
|
||||||
}),
|
}),
|
||||||
@@ -122,14 +122,14 @@ describe('CompetitionAssignmentProvisioner', () => {
|
|||||||
expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith(
|
expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
{ _id: assignmentId, state: 'reserved' },
|
{ _id: assignmentId, state: 'reserved' },
|
||||||
{ $set: expect.objectContaining({ state: 'released' }) },
|
{ $set: expect.objectContaining({ state: 'released' }) },
|
||||||
{ new: true, session: harness.session },
|
{ returnDocument: 'after', session: harness.session },
|
||||||
);
|
);
|
||||||
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
|
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
|
||||||
{ _id: harness.codeId, state: 'reserved' },
|
{ _id: harness.codeId, state: 'reserved' },
|
||||||
expect.objectContaining({
|
expect.objectContaining({
|
||||||
$set: expect.objectContaining({ state: 'released' }),
|
$set: expect.objectContaining({ state: 'released' }),
|
||||||
}),
|
}),
|
||||||
{ new: true, session: harness.session },
|
{ returnDocument: 'after', session: harness.session },
|
||||||
);
|
);
|
||||||
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
|
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
|
||||||
{ _id: harness.matchId },
|
{ _id: harness.matchId },
|
||||||
|
|||||||
@@ -156,7 +156,7 @@ export class CompetitionAssignmentProvisioner {
|
|||||||
const assignment = (await params.AssignmentModel.findOneAndUpdate(
|
const assignment = (await params.AssignmentModel.findOneAndUpdate(
|
||||||
{ _id: params.assignment._id, state: 'reserved' },
|
{ _id: params.assignment._id, state: 'reserved' },
|
||||||
{ $set: { state: 'released', releasedAt } },
|
{ $set: { state: 'released', releasedAt } },
|
||||||
{ new: true, session },
|
{ returnDocument: 'after', session },
|
||||||
).exec()) as AssignmentRecord | null;
|
).exec()) as AssignmentRecord | null;
|
||||||
if (!assignment) {
|
if (!assignment) {
|
||||||
await session.commitTransaction();
|
await session.commitTransaction();
|
||||||
@@ -173,7 +173,7 @@ export class CompetitionAssignmentProvisioner {
|
|||||||
reservedAt: 1,
|
reservedAt: 1,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ new: true, session },
|
{ returnDocument: 'after', session },
|
||||||
).exec()) as CodeRecord | null;
|
).exec()) as CodeRecord | null;
|
||||||
if (!code) {
|
if (!code) {
|
||||||
throw new Error(
|
throw new Error(
|
||||||
@@ -354,7 +354,7 @@ export class CompetitionAssignmentProvisioner {
|
|||||||
gameNumber: params.displayNumber,
|
gameNumber: params.displayNumber,
|
||||||
},
|
},
|
||||||
{ $set: { gameNumber: params.displayNumber } },
|
{ $set: { gameNumber: params.displayNumber } },
|
||||||
{ new: true, session: params.session },
|
{ returnDocument: 'after', session: params.session },
|
||||||
).exec()) as CodeRecord | null;
|
).exec()) as CodeRecord | null;
|
||||||
if (promoted) return promoted;
|
if (promoted) return promoted;
|
||||||
}
|
}
|
||||||
@@ -377,7 +377,11 @@ export class CompetitionAssignmentProvisioner {
|
|||||||
reservedAt: new Date(),
|
reservedAt: new Date(),
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{ new: true, session: params.session, sort: { expiresAt: 1 } },
|
{
|
||||||
|
returnDocument: 'after',
|
||||||
|
session: params.session,
|
||||||
|
sort: { expiresAt: 1 },
|
||||||
|
},
|
||||||
).exec()) as CodeRecord | null;
|
).exec()) as CodeRecord | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -110,7 +110,7 @@ export class CompetitionOutboxProcessor
|
|||||||
$unset: { lastError: 1 },
|
$unset: { lastError: 1 },
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
new: true,
|
returnDocument: 'after',
|
||||||
sort: { availableAt: 1, revision: 1, _id: 1 },
|
sort: { availableAt: 1, revision: 1, _id: 1 },
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
|||||||
VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d
|
VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d
|
||||||
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
VITE_MSAL_AUTHORITY=https://login.microsoftonline.com/5ef88004-e953-4b04-93db-64bbf49c6863
|
||||||
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
VITE_MSAL_API_SCOPE=api://15fb5a20-47e0-44fa-9a41-b50ca9d0e7e3/lolympus-tournament-support-dev
|
||||||
VITE_MSAL_REDIRECT_URI=https://release-83.lolympus.pages.dev/auth/callback
|
VITE_MSAL_REDIRECT_URI=https://release-86.lolympus.pages.dev/auth/callback
|
||||||
VITE_NEW_RELIC_ENABLED=true
|
VITE_NEW_RELIC_ENABLED=true
|
||||||
VITE_NEW_RELIC_APPLICATION_ID=601654991
|
VITE_NEW_RELIC_APPLICATION_ID=601654991
|
||||||
VITE_NEW_RELIC_ACCOUNT_ID=8100154
|
VITE_NEW_RELIC_ACCOUNT_ID=8100154
|
||||||
@@ -11,6 +11,6 @@ VITE_NEW_RELIC_AGENT_ID=601654991
|
|||||||
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
|
VITE_NEW_RELIC_LICENSE_KEY=NRJS-caad7f6e90b92fe88de
|
||||||
VITE_NEW_RELIC_TRUST_KEY=8100154
|
VITE_NEW_RELIC_TRUST_KEY=8100154
|
||||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||||
VITE_NEW_RELIC_APPLICATION_VERSION=83
|
VITE_NEW_RELIC_APPLICATION_VERSION=86
|
||||||
VITE_NEW_RELIC_RELEASE_ID=release-83
|
VITE_NEW_RELIC_RELEASE_ID=release-86
|
||||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||||
@@ -257,12 +257,15 @@ export function useCompetition(
|
|||||||
export function useTeamCompetition(
|
export function useTeamCompetition(
|
||||||
matchId: string | undefined,
|
matchId: string | undefined,
|
||||||
communityId = DEFAULT_COMMUNITY_ID,
|
communityId = DEFAULT_COMMUNITY_ID,
|
||||||
|
teamId?: string,
|
||||||
) {
|
) {
|
||||||
return useQuery({
|
return useQuery({
|
||||||
queryKey: ['competition-team', communityId, matchId ?? null],
|
queryKey: ['competition-team', communityId, matchId ?? null, teamId ?? null],
|
||||||
queryFn: () =>
|
queryFn: () =>
|
||||||
apiFetch<TeamCompetitionViewResponse>(
|
apiFetch<TeamCompetitionViewResponse>(
|
||||||
`/communities/${communityId}/matches/${matchId}/competition/team`,
|
`/communities/${communityId}/matches/${matchId}/competition/team${
|
||||||
|
teamId ? `?teamId=${encodeURIComponent(teamId)}` : ''
|
||||||
|
}`,
|
||||||
),
|
),
|
||||||
enabled: Boolean(communityId && matchId),
|
enabled: Boolean(communityId && matchId),
|
||||||
retry: false,
|
retry: false,
|
||||||
|
|||||||
@@ -701,6 +701,24 @@ export interface ApiInternalMatchDetailResponse {
|
|||||||
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
type: 'dragon' | 'elderDragon' | 'baron' | 'riftHerald' | 'voidGrub';
|
||||||
monsterSubType?: string;
|
monsterSubType?: string;
|
||||||
}>;
|
}>;
|
||||||
|
timelineEvents?: Array<{
|
||||||
|
timestamp: number;
|
||||||
|
side?: TeamSide;
|
||||||
|
type:
|
||||||
|
| 'dragon'
|
||||||
|
| 'elderDragon'
|
||||||
|
| 'baron'
|
||||||
|
| 'riftHerald'
|
||||||
|
| 'voidGrub'
|
||||||
|
| 'championKill'
|
||||||
|
| 'tower'
|
||||||
|
| 'inhibitor';
|
||||||
|
monsterSubType?: string;
|
||||||
|
killerParticipantId?: number;
|
||||||
|
victimParticipantId?: number;
|
||||||
|
assistingParticipantIds?: number[];
|
||||||
|
towerType?: string;
|
||||||
|
}>;
|
||||||
teams: Array<{
|
teams: Array<{
|
||||||
teamIndex: number;
|
teamIndex: number;
|
||||||
side: TeamSide;
|
side: TeamSide;
|
||||||
@@ -716,6 +734,27 @@ export interface ApiInternalMatchDetailResponse {
|
|||||||
};
|
};
|
||||||
bans: Array<{ championId: number; pickTurn: number }>;
|
bans: Array<{ championId: number; pickTurn: number }>;
|
||||||
participants: Array<{
|
participants: Array<{
|
||||||
|
participantId?: number;
|
||||||
|
checkpoints?: {
|
||||||
|
at10?: {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
};
|
||||||
|
at15?: {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
};
|
||||||
|
};
|
||||||
userId: string | null;
|
userId: string | null;
|
||||||
summonerName: string;
|
summonerName: string;
|
||||||
tagLine: string;
|
tagLine: string;
|
||||||
|
|||||||
@@ -6,6 +6,14 @@ import {
|
|||||||
} from "../lib/ddragon";
|
} from "../lib/ddragon";
|
||||||
import { teamIndexLabel } from "../lib/league";
|
import { teamIndexLabel } from "../lib/league";
|
||||||
import { LANE_LABELS } from "../lib/riot-history";
|
import { LANE_LABELS } from "../lib/riot-history";
|
||||||
|
import {
|
||||||
|
DEFAULT_LANE_CHECKPOINT,
|
||||||
|
pairLaneParticipants,
|
||||||
|
resolveCheckpointComparison,
|
||||||
|
type LaneCheckpointKey,
|
||||||
|
type LaneParticipantLike,
|
||||||
|
type NormalizedLanePosition,
|
||||||
|
} from "../lib/internal-game-matchups";
|
||||||
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
|
import { ItemIcon, RuneIcon, RuneStyleIcon } from "./ItemTooltip";
|
||||||
|
|
||||||
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
||||||
@@ -13,6 +21,7 @@ export type InternalGameDetailTab = "scoreboard" | "matchup" | "build";
|
|||||||
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
|
type InternalGameDetail = ApiInternalMatchDetailResponse["games"][number];
|
||||||
type InternalGameTeam = InternalGameDetail["teams"][number];
|
type InternalGameTeam = InternalGameDetail["teams"][number];
|
||||||
type InternalGameParticipant = InternalGameTeam["participants"][number];
|
type InternalGameParticipant = InternalGameTeam["participants"][number];
|
||||||
|
type CheckpointParticipant = InternalGameParticipant & LaneParticipantLike;
|
||||||
type DdragonManifestData = DdragonManifest | null | undefined;
|
type DdragonManifestData = DdragonManifest | null | undefined;
|
||||||
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
|
type RuneStyleEntry = DdragonManifest["runesReforged"][number];
|
||||||
|
|
||||||
@@ -44,8 +53,6 @@ const STAT_PERK_LABELS: Record<number, string> = {
|
|||||||
5011: "체력",
|
5011: "체력",
|
||||||
};
|
};
|
||||||
|
|
||||||
const LANE_SORT_ORDER = ["TOP", "JUNGLE", "MIDDLE", "BOTTOM", "UTILITY"];
|
|
||||||
|
|
||||||
function formatDuration(seconds: number) {
|
function formatDuration(seconds: number) {
|
||||||
const minutes = Math.floor(seconds / 60);
|
const minutes = Math.floor(seconds / 60);
|
||||||
const rest = seconds % 60;
|
const rest = seconds % 60;
|
||||||
@@ -56,6 +63,11 @@ function formatNumber(value: number) {
|
|||||||
return new Intl.NumberFormat("ko-KR").format(value);
|
return new Intl.NumberFormat("ko-KR").format(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatSignedNumber(value: number) {
|
||||||
|
if (value === 0) return "0";
|
||||||
|
return `${value > 0 ? "+" : "-"}${formatNumber(Math.abs(value))}`;
|
||||||
|
}
|
||||||
|
|
||||||
function sideTone(side: TeamSide) {
|
function sideTone(side: TeamSide) {
|
||||||
return side === "blue"
|
return side === "blue"
|
||||||
? {
|
? {
|
||||||
@@ -111,11 +123,6 @@ function runeStyleSelection(
|
|||||||
return participant.perks.styles?.find((style) => style.styleId === styleId);
|
return participant.perks.styles?.find((style) => style.styleId === styleId);
|
||||||
}
|
}
|
||||||
|
|
||||||
function laneSortValue(position: string) {
|
|
||||||
const index = LANE_SORT_ORDER.indexOf(position);
|
|
||||||
return index === -1 ? 99 : index;
|
|
||||||
}
|
|
||||||
|
|
||||||
function ChampionCell({
|
function ChampionCell({
|
||||||
participant,
|
participant,
|
||||||
manifest,
|
manifest,
|
||||||
@@ -648,12 +655,14 @@ function SkillBuildPanel({
|
|||||||
|
|
||||||
function MatchupMetricRow({
|
function MatchupMetricRow({
|
||||||
label,
|
label,
|
||||||
|
difference,
|
||||||
blueLead,
|
blueLead,
|
||||||
redLead,
|
redLead,
|
||||||
blueText,
|
blueText,
|
||||||
redText,
|
redText,
|
||||||
}: {
|
}: {
|
||||||
label: string;
|
label: string;
|
||||||
|
difference?: string;
|
||||||
blueLead: boolean;
|
blueLead: boolean;
|
||||||
redLead: boolean;
|
redLead: boolean;
|
||||||
blueText: string;
|
blueText: string;
|
||||||
@@ -668,8 +677,13 @@ function MatchupMetricRow({
|
|||||||
>
|
>
|
||||||
{blueText}
|
{blueText}
|
||||||
</span>
|
</span>
|
||||||
<span className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
<span className="min-w-16 text-center text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
||||||
{label}
|
<span className="block">{label}</span>
|
||||||
|
{difference ? (
|
||||||
|
<span className="mt-0.5 block normal-case text-base-content/50">
|
||||||
|
{difference}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
</span>
|
</span>
|
||||||
<span
|
<span
|
||||||
className={`tabular-nums ${
|
className={`tabular-nums ${
|
||||||
@@ -682,101 +696,172 @@ function MatchupMetricRow({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function LaneMatchupCard({
|
function checkpointKda(kills: number, deaths: number, assists: number) {
|
||||||
blue,
|
return deaths === 0 ? kills + assists : (kills + assists) / deaths;
|
||||||
red,
|
}
|
||||||
detail,
|
|
||||||
|
function LaneParticipantIdentity({
|
||||||
|
participant,
|
||||||
manifest,
|
manifest,
|
||||||
|
align,
|
||||||
|
ambiguous,
|
||||||
}: {
|
}: {
|
||||||
blue: InternalGameParticipant;
|
participant: CheckpointParticipant | null;
|
||||||
red: InternalGameParticipant;
|
|
||||||
detail: ApiInternalMatchDetailResponse;
|
|
||||||
manifest: DdragonManifestData;
|
manifest: DdragonManifestData;
|
||||||
|
align: "left" | "right";
|
||||||
|
ambiguous: boolean;
|
||||||
}) {
|
}) {
|
||||||
const laneLabel =
|
if (!participant) {
|
||||||
LANE_LABELS[blue.teamPosition] ??
|
return (
|
||||||
LANE_LABELS[red.teamPosition] ??
|
<div
|
||||||
blue.teamPosition ??
|
className={`min-w-0 text-[11px] font-bold text-base-content/30 ${
|
||||||
"-";
|
align === "right" ? "text-right" : "text-left"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{ambiguous ? "포지션 중복" : "선수 없음"}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const metrics = [
|
const championName =
|
||||||
{
|
|
||||||
key: "kda",
|
|
||||||
label: "KDA",
|
|
||||||
blueValue:
|
|
||||||
blue.deaths === 0
|
|
||||||
? blue.kills + blue.assists
|
|
||||||
: (blue.kills + blue.assists) / blue.deaths,
|
|
||||||
redValue:
|
|
||||||
red.deaths === 0
|
|
||||||
? red.kills + red.assists
|
|
||||||
: (red.kills + red.assists) / red.deaths,
|
|
||||||
blueText: `${blue.kills}/${blue.deaths}/${blue.assists}`,
|
|
||||||
redText: `${red.kills}/${red.deaths}/${red.assists}`,
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "gold",
|
|
||||||
label: "골드",
|
|
||||||
blueValue: blue.gold,
|
|
||||||
redValue: red.gold,
|
|
||||||
blueText: formatNumber(blue.gold),
|
|
||||||
redText: formatNumber(red.gold),
|
|
||||||
},
|
|
||||||
{
|
|
||||||
key: "cs",
|
|
||||||
label: "CS",
|
|
||||||
blueValue: blue.cs,
|
|
||||||
redValue: red.cs,
|
|
||||||
blueText: `${blue.cs} (${blue.csPerMin}/m)`,
|
|
||||||
redText: `${red.cs} (${red.csPerMin}/m)`,
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
const championName = (participant: InternalGameParticipant) =>
|
|
||||||
championDisplayName(manifest, participant.championId) ??
|
championDisplayName(manifest, participant.championId) ??
|
||||||
String(participant.championId);
|
String(participant.championId);
|
||||||
|
const details = (
|
||||||
|
<div className={`min-w-0 ${align === "right" ? "text-right" : ""}`}>
|
||||||
|
<div className="truncate text-xs font-bold text-base-content">
|
||||||
|
{participant.summonerName}
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-[11px] text-base-content/40">
|
||||||
|
{championName}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`flex min-w-0 items-center gap-2 ${
|
||||||
|
align === "right" ? "justify-end" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{align === "right" ? details : null}
|
||||||
|
<ChampionAvatar participant={participant} manifest={manifest} />
|
||||||
|
{align === "left" ? details : null}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LaneMatchupCard({
|
||||||
|
position,
|
||||||
|
blue,
|
||||||
|
red,
|
||||||
|
ambiguousBlue,
|
||||||
|
ambiguousRed,
|
||||||
|
checkpointKey,
|
||||||
|
manifest,
|
||||||
|
}: {
|
||||||
|
position: NormalizedLanePosition;
|
||||||
|
blue: CheckpointParticipant | null;
|
||||||
|
red: CheckpointParticipant | null;
|
||||||
|
ambiguousBlue: boolean;
|
||||||
|
ambiguousRed: boolean;
|
||||||
|
checkpointKey: LaneCheckpointKey;
|
||||||
|
manifest: DdragonManifestData;
|
||||||
|
}) {
|
||||||
|
const laneLabel = LANE_LABELS[position] ?? position;
|
||||||
|
const comparison = resolveCheckpointComparison(blue, red, checkpointKey);
|
||||||
|
const metrics = comparison
|
||||||
|
? [
|
||||||
|
{
|
||||||
|
key: "gold",
|
||||||
|
label: "골드",
|
||||||
|
difference: `GD ${formatSignedNumber(comparison.goldDiff)}`,
|
||||||
|
blueValue: comparison.blue.gold,
|
||||||
|
redValue: comparison.red.gold,
|
||||||
|
blueText: formatNumber(comparison.blue.gold),
|
||||||
|
redText: formatNumber(comparison.red.gold),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "cs",
|
||||||
|
label: "CS",
|
||||||
|
difference: `CSD ${formatSignedNumber(comparison.csDiff)}`,
|
||||||
|
blueValue: comparison.blue.cs,
|
||||||
|
redValue: comparison.red.cs,
|
||||||
|
blueText: formatNumber(comparison.blue.cs),
|
||||||
|
redText: formatNumber(comparison.red.cs),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "xp",
|
||||||
|
label: "경험치",
|
||||||
|
difference: `XPD ${formatSignedNumber(comparison.xpDiff)}`,
|
||||||
|
blueValue: comparison.blue.xp,
|
||||||
|
redValue: comparison.red.xp,
|
||||||
|
blueText: formatNumber(comparison.blue.xp),
|
||||||
|
redText: formatNumber(comparison.red.xp),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "kda",
|
||||||
|
label: "K / D / A",
|
||||||
|
blueValue: checkpointKda(
|
||||||
|
comparison.blue.kills,
|
||||||
|
comparison.blue.deaths,
|
||||||
|
comparison.blue.assists,
|
||||||
|
),
|
||||||
|
redValue: checkpointKda(
|
||||||
|
comparison.red.kills,
|
||||||
|
comparison.red.deaths,
|
||||||
|
comparison.red.assists,
|
||||||
|
),
|
||||||
|
blueText: `${comparison.blue.kills}/${comparison.blue.deaths}/${comparison.blue.assists}`,
|
||||||
|
redText: `${comparison.red.kills}/${comparison.red.deaths}/${comparison.red.assists}`,
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: [];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="overflow-hidden border border-base-content/10 bg-base-100">
|
<div className="overflow-hidden border border-base-content/10 bg-base-100">
|
||||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 border-b border-base-content/8 bg-base-content/[0.015] px-3 py-2">
|
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 border-b border-base-content/8 bg-base-content/[0.015] px-3 py-2">
|
||||||
<div className="flex min-w-0 items-center justify-end gap-2">
|
<LaneParticipantIdentity
|
||||||
<div className="min-w-0 text-right">
|
participant={blue}
|
||||||
<div className="truncate text-xs font-bold text-base-content">
|
manifest={manifest}
|
||||||
{blue.summonerName}
|
align="right"
|
||||||
</div>
|
ambiguous={ambiguousBlue}
|
||||||
<div className="truncate text-[11px] text-base-content/40">
|
/>
|
||||||
{championName(blue)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<ChampionAvatar participant={blue} manifest={manifest} />
|
|
||||||
</div>
|
|
||||||
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
|
<span className="border border-base-content/10 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider text-base-content/45">
|
||||||
{laneLabel}
|
{laneLabel}
|
||||||
</span>
|
</span>
|
||||||
<div className="flex min-w-0 items-center gap-2">
|
<LaneParticipantIdentity
|
||||||
<ChampionAvatar participant={red} manifest={manifest} />
|
participant={red}
|
||||||
<div className="min-w-0">
|
manifest={manifest}
|
||||||
<div className="truncate text-xs font-bold text-base-content">
|
align="left"
|
||||||
{red.summonerName}
|
ambiguous={ambiguousRed}
|
||||||
</div>
|
/>
|
||||||
<div className="truncate text-[11px] text-base-content/40">
|
</div>
|
||||||
{championName(red)}
|
{comparison ? (
|
||||||
</div>
|
<>
|
||||||
|
<div className="divide-y divide-base-content/5">
|
||||||
|
{metrics.map((metric) => (
|
||||||
|
<MatchupMetricRow
|
||||||
|
key={`${position}-${checkpointKey}-${metric.key}`}
|
||||||
|
label={metric.label}
|
||||||
|
difference={metric.difference}
|
||||||
|
blueLead={metric.blueValue > metric.redValue}
|
||||||
|
redLead={metric.redValue > metric.blueValue}
|
||||||
|
blueText={metric.blueText}
|
||||||
|
redText={metric.redText}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<div className="border-t border-base-content/5 px-3 py-1.5 text-center text-[10px] font-bold text-base-content/30">
|
||||||
|
실제 기준 {formatDuration(comparison.blue.timestamp)} · {formatDuration(comparison.red.timestamp)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="px-3 py-7 text-center text-xs font-bold text-base-content/35">
|
||||||
|
{ambiguousBlue || ambiguousRed
|
||||||
|
? "포지션이 중복되어 상대를 확정할 수 없습니다"
|
||||||
|
: "선택한 시점의 라인전 데이터가 없습니다"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
)}
|
||||||
<div className="divide-y divide-base-content/5">
|
|
||||||
{metrics.map((metric) => (
|
|
||||||
<MatchupMetricRow
|
|
||||||
key={`${detail.match.matchId}-${blue.teamPosition}-${metric.key}`}
|
|
||||||
label={metric.label}
|
|
||||||
blueLead={metric.blueValue > metric.redValue}
|
|
||||||
redLead={metric.redValue > metric.blueValue}
|
|
||||||
blueText={metric.blueText}
|
|
||||||
redText={metric.redText}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -790,6 +875,8 @@ function LaneMatchupPanel({
|
|||||||
detail: ApiInternalMatchDetailResponse;
|
detail: ApiInternalMatchDetailResponse;
|
||||||
manifest: DdragonManifestData;
|
manifest: DdragonManifestData;
|
||||||
}) {
|
}) {
|
||||||
|
const [checkpointKey, setCheckpointKey] =
|
||||||
|
useState<LaneCheckpointKey>(DEFAULT_LANE_CHECKPOINT);
|
||||||
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||||
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||||
|
|
||||||
@@ -801,40 +888,64 @@ function LaneMatchupPanel({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const blueSorted = [...blueTeam.participants].sort(
|
const matchups = pairLaneParticipants(
|
||||||
(left, right) =>
|
blueTeam.participants as CheckpointParticipant[],
|
||||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
redTeam.participants as CheckpointParticipant[],
|
||||||
);
|
|
||||||
const redSorted = [...redTeam.participants].sort(
|
|
||||||
(left, right) =>
|
|
||||||
laneSortValue(left.teamPosition) - laneSortValue(right.teamPosition),
|
|
||||||
);
|
);
|
||||||
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
|
const blueTeamName = getTeamName(detail, blueTeam.teamIndex);
|
||||||
const redTeamName = getTeamName(detail, redTeam.teamIndex);
|
const redTeamName = getTeamName(detail, redTeam.teamIndex);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="overflow-hidden border border-base-content/10 bg-base-100">
|
<section className="overflow-hidden border border-base-content/10 bg-base-100">
|
||||||
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 border-b border-base-content/8 px-4 py-3 text-xs font-bold">
|
<div className="border-b border-base-content/8 px-4 py-3">
|
||||||
<span className="truncate text-right text-blue-400">
|
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-3 text-xs font-bold">
|
||||||
{blueTeamName}
|
<span className="truncate text-right text-blue-400">
|
||||||
</span>
|
{blueTeamName}
|
||||||
<span className="text-base-content/20">VS</span>
|
</span>
|
||||||
<span className="truncate text-red-400">{redTeamName}</span>
|
<span className="text-base-content/20">VS</span>
|
||||||
|
<span className="truncate text-red-400">{redTeamName}</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mx-auto mt-3 flex w-fit border border-base-content/10"
|
||||||
|
role="group"
|
||||||
|
aria-label="라인전 비교 시점"
|
||||||
|
>
|
||||||
|
{(["at10", "at15"] as const).map((key) => (
|
||||||
|
<button
|
||||||
|
key={key}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={checkpointKey === key}
|
||||||
|
onClick={() => setCheckpointKey(key)}
|
||||||
|
className={`border-r border-base-content/8 px-4 py-1.5 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
|
||||||
|
checkpointKey === key
|
||||||
|
? "bg-primary text-primary-content"
|
||||||
|
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{key === "at10" ? "10분" : "15분"}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
<div className="grid gap-3 p-4 lg:grid-cols-2">
|
||||||
{blueSorted.map((blue, index) => {
|
{matchups.length > 0 ? (
|
||||||
const red = redSorted[index];
|
matchups.map((matchup) => (
|
||||||
if (!red) return null;
|
|
||||||
return (
|
|
||||||
<LaneMatchupCard
|
<LaneMatchupCard
|
||||||
key={`matchup-${blue.teamPosition}-${blue.summonerName}`}
|
key={`matchup-${matchup.position}`}
|
||||||
blue={blue}
|
position={matchup.position}
|
||||||
red={red}
|
blue={matchup.blue}
|
||||||
detail={detail}
|
red={matchup.red}
|
||||||
|
ambiguousBlue={matchup.ambiguousBlue}
|
||||||
|
ambiguousRed={matchup.ambiguousRed}
|
||||||
|
checkpointKey={checkpointKey}
|
||||||
manifest={manifest}
|
manifest={manifest}
|
||||||
/>
|
/>
|
||||||
);
|
))
|
||||||
})}
|
) : (
|
||||||
|
<div className="py-10 text-center text-sm font-bold text-base-content/35 lg:col-span-2">
|
||||||
|
비교 가능한 포지션 정보가 없습니다
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import type {
|
||||||
|
CommunityId,
|
||||||
|
CompetitionTeamView,
|
||||||
|
MatchId,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { ChevronRight } from "lucide-react";
|
||||||
|
import { Link } from "react-router";
|
||||||
|
import {
|
||||||
|
competitionHistoryGameDetailPath,
|
||||||
|
formatCompetitionHistoryTime,
|
||||||
|
formatSeriesGameDuration,
|
||||||
|
type CompetitionSeriesHistoryRow,
|
||||||
|
} from "./competition-series-history";
|
||||||
|
|
||||||
|
export function CompetitionGameHistory({
|
||||||
|
games,
|
||||||
|
teamById,
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
historyBackTo,
|
||||||
|
}: {
|
||||||
|
games: CompetitionSeriesHistoryRow["games"];
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
communityId: CommunityId;
|
||||||
|
matchId: MatchId;
|
||||||
|
historyBackTo: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<ol className="border-t border-base-content/10 bg-base-content/[0.02] px-4 py-1">
|
||||||
|
{games.map((game) => {
|
||||||
|
const duration = formatSeriesGameDuration(game.durationSeconds);
|
||||||
|
const winnerName = teamById.get(game.winnerTeamId)?.name ?? "알 수 없는 팀";
|
||||||
|
const detailPath = competitionHistoryGameDetailPath(
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
game,
|
||||||
|
);
|
||||||
|
const content = (
|
||||||
|
<GameHistoryRowContent
|
||||||
|
game={game}
|
||||||
|
winnerName={winnerName}
|
||||||
|
duration={duration}
|
||||||
|
linked={detailPath !== null}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<li
|
||||||
|
key={game.id}
|
||||||
|
className="border-b border-base-content/8 last:border-b-0"
|
||||||
|
>
|
||||||
|
{detailPath ? (
|
||||||
|
<Link
|
||||||
|
to={detailPath}
|
||||||
|
state={{
|
||||||
|
backTo: historyBackTo,
|
||||||
|
backLabel: "경기 일정·결과로 돌아가기",
|
||||||
|
}}
|
||||||
|
className="grid min-h-14 items-center px-2 py-2 text-xs leading-5 text-base-content transition-colors hover:bg-primary/[0.06] active:bg-primary/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary motion-reduce:transition-none"
|
||||||
|
>
|
||||||
|
{content}
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<div className="grid min-h-14 items-center px-2 py-2 text-xs leading-5 text-base-content">
|
||||||
|
{content}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ol>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function GameHistoryRowContent({
|
||||||
|
game,
|
||||||
|
winnerName,
|
||||||
|
duration,
|
||||||
|
linked,
|
||||||
|
}: {
|
||||||
|
game: CompetitionSeriesHistoryRow["games"][number];
|
||||||
|
winnerName: string;
|
||||||
|
duration: string | null;
|
||||||
|
linked: boolean;
|
||||||
|
}) {
|
||||||
|
const startedAt = formatCompetitionHistoryTime(game.startedAt);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="grid w-full min-w-0 grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 gap-y-1.5 md:grid-cols-[minmax(10rem,1fr)_minmax(12rem,2fr)_minmax(10rem,1fr)] md:gap-4">
|
||||||
|
<span className="col-span-2 row-start-1 min-w-0 break-words text-center font-semibold leading-5 md:col-span-1 md:col-start-2 md:row-start-1">
|
||||||
|
{winnerName} 승
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span className="col-start-1 row-start-2 flex min-w-0 items-center gap-3 text-content-muted md:col-start-1 md:row-start-1">
|
||||||
|
<span className="shrink-0 font-bold leading-5">
|
||||||
|
{game.ordinal}게임
|
||||||
|
</span>
|
||||||
|
{startedAt ? (
|
||||||
|
<time
|
||||||
|
dateTime={game.startedAt}
|
||||||
|
className="shrink-0 font-mono leading-5 tabular-nums"
|
||||||
|
>
|
||||||
|
{startedAt}
|
||||||
|
</time>
|
||||||
|
) : (
|
||||||
|
<span className="shrink-0 font-mono leading-5 tabular-nums">
|
||||||
|
<span aria-hidden="true">—</span>
|
||||||
|
<span className="sr-only">시작 시각 기록 없음</span>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span className="col-start-2 row-start-2 flex min-w-0 items-center justify-end gap-3 leading-5 md:col-start-3 md:row-start-1">
|
||||||
|
<span className="shrink-0 text-right font-mono tabular-nums text-content-muted">
|
||||||
|
{duration ? (
|
||||||
|
<>
|
||||||
|
<span className="sr-only">경기 시간 </span>
|
||||||
|
{duration}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<span aria-hidden="true">—</span>
|
||||||
|
<span className="sr-only">경기 시간 기록 없음</span>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
{linked && (
|
||||||
|
<span className="flex shrink-0 items-center justify-end gap-0.5 font-bold text-content-subtle">
|
||||||
|
<span>상세 분석</span>
|
||||||
|
<ChevronRight
|
||||||
|
className="h-3.5 w-3.5 shrink-0 text-primary"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,21 +5,55 @@ import type {
|
|||||||
TeamId,
|
TeamId,
|
||||||
} from "@lolympus/contracts";
|
} from "@lolympus/contracts";
|
||||||
import { Link } from "react-router";
|
import { Link } from "react-router";
|
||||||
|
import { CompetitionSeriesHistory } from "./CompetitionSeriesHistory";
|
||||||
|
import { DoubleEliminationBracket } from "./DoubleEliminationBracket";
|
||||||
|
import { createCompetitionSeriesHistory } from "./competition-series-history";
|
||||||
|
import { createCompetitionBracketLayout } from "./competition-display-layout";
|
||||||
|
import { bracketRoundLabel } from "./double-elimination-bracket-layout";
|
||||||
import { RoundRobinTable } from "./RoundRobinTable";
|
import { RoundRobinTable } from "./RoundRobinTable";
|
||||||
import { SeriesScoreCard } from "./SeriesScoreCard";
|
import { SeriesScoreCard } from "./SeriesScoreCard";
|
||||||
|
|
||||||
export function CompetitionResults({
|
export function CompetitionResults({
|
||||||
competition,
|
competition,
|
||||||
|
view = "all",
|
||||||
}: {
|
}: {
|
||||||
competition: CompetitionDetailResponse;
|
competition: CompetitionDetailResponse;
|
||||||
|
view?: "all" | "bracket" | "games";
|
||||||
}) {
|
}) {
|
||||||
const { projection } = competition;
|
const { projection } = competition;
|
||||||
const teamById = new Map(
|
const teamById = new Map(
|
||||||
competition.teams.map((team) => [team.teamId, team]),
|
competition.teams.map((team) => [team.teamId, team]),
|
||||||
);
|
);
|
||||||
|
const seriesHistory =
|
||||||
|
view === "bracket" ? [] : createCompetitionSeriesHistory(projection);
|
||||||
|
|
||||||
|
if (view === "games") {
|
||||||
|
const hasSeriesHistory = seriesHistory.length > 0;
|
||||||
|
return (
|
||||||
|
<div className="mb-6">
|
||||||
|
{hasSeriesHistory ? (
|
||||||
|
<CompetitionSeriesHistory
|
||||||
|
communityId={competition.communityId}
|
||||||
|
matchId={competition.matchId}
|
||||||
|
history={seriesHistory}
|
||||||
|
teamById={teamById}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p
|
||||||
|
className="border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/45"
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
예정되거나 기록된 공식 경기가 없습니다.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
const seriesById = new Map(
|
const seriesById = new Map(
|
||||||
projection.series.map((series) => [series.seriesId, series]),
|
projection.series.map((series) => [series.seriesId, series]),
|
||||||
);
|
);
|
||||||
|
const doubleEliminationLayout = createCompetitionBracketLayout(competition);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mb-6 space-y-4" aria-labelledby="competition-heading">
|
<section className="mb-6 space-y-4" aria-labelledby="competition-heading">
|
||||||
@@ -29,7 +63,7 @@ export function CompetitionResults({
|
|||||||
Competition
|
Competition
|
||||||
</p>
|
</p>
|
||||||
<h2 id="competition-heading" className="mt-1 text-lg font-bold">
|
<h2 id="competition-heading" className="mt-1 text-lg font-bold">
|
||||||
공식 경기 결과
|
공식 경기 일정·결과
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
@@ -40,7 +74,7 @@ export function CompetitionResults({
|
|||||||
to={`/match/${competition.matchId}/team`}
|
to={`/match/${competition.matchId}/team`}
|
||||||
className="border border-base-content/10 px-2.5 py-1.5 text-xs font-bold text-base-content/55 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
className="border border-base-content/10 px-2.5 py-1.5 text-xs font-bold text-base-content/55 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
>
|
>
|
||||||
내 팀 진행
|
팀 진행
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -54,18 +88,20 @@ export function CompetitionResults({
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
{projection.rounds.length > 0 ? (
|
{projection.rounds.length > 0 ? (
|
||||||
<div className="overflow-x-auto pb-2">
|
projection.formatType === "double-elimination" &&
|
||||||
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
|
doubleEliminationLayout ? (
|
||||||
{projection.rounds.map((round) => (
|
<DoubleEliminationBracket
|
||||||
<RoundColumn
|
projection={projection}
|
||||||
key={`${round.stage}:${round.roundNumber ?? 0}`}
|
layout={doubleEliminationLayout}
|
||||||
round={round}
|
teamById={teamById}
|
||||||
seriesById={seriesById}
|
/>
|
||||||
teamById={teamById}
|
) : (
|
||||||
/>
|
<GenericRoundGrid
|
||||||
))}
|
rounds={projection.rounds}
|
||||||
</div>
|
seriesById={seriesById}
|
||||||
</div>
|
teamById={teamById}
|
||||||
|
/>
|
||||||
|
)
|
||||||
) : (
|
) : (
|
||||||
<p
|
<p
|
||||||
className="border border-dashed border-base-content/15 px-4 py-5 text-sm text-base-content/45"
|
className="border border-dashed border-base-content/15 px-4 py-5 text-sm text-base-content/45"
|
||||||
@@ -75,32 +111,46 @@ export function CompetitionResults({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{projection.games.length > 0 && (
|
{view === "all" && (
|
||||||
<div className="border border-base-content/10 bg-base-content/[0.02] p-4">
|
<CompetitionSeriesHistory
|
||||||
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
|
communityId={competition.communityId}
|
||||||
완료된 게임
|
matchId={competition.matchId}
|
||||||
</h3>
|
history={seriesHistory}
|
||||||
<ul className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
|
teamById={teamById}
|
||||||
{projection.games.map((game) => (
|
/>
|
||||||
<li
|
|
||||||
key={game.id}
|
|
||||||
className="flex items-center justify-between gap-3 border border-base-content/8 bg-base-100 px-3 py-2 text-xs"
|
|
||||||
>
|
|
||||||
<span className="text-base-content/45">
|
|
||||||
Game {game.displayNumber}
|
|
||||||
</span>
|
|
||||||
<span className="truncate font-semibold">
|
|
||||||
{teamById.get(game.winnerTeamId)?.name ?? "알 수 없는 팀"} 승
|
|
||||||
</span>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
</div>
|
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function GenericRoundGrid({
|
||||||
|
rounds,
|
||||||
|
seriesById,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
rounds: BracketRoundView[];
|
||||||
|
seriesById: Map<
|
||||||
|
string,
|
||||||
|
CompetitionDetailResponse["projection"]["series"][number]
|
||||||
|
>;
|
||||||
|
teamById: Map<TeamId, CompetitionDetailResponse["teams"][number]>;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="overflow-x-auto pb-2">
|
||||||
|
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
|
||||||
|
{rounds.map((round) => (
|
||||||
|
<RoundColumn
|
||||||
|
key={`${round.stage}:${round.roundNumber ?? 0}`}
|
||||||
|
round={round}
|
||||||
|
seriesById={seriesById}
|
||||||
|
teamById={teamById}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function RoundColumn({
|
function RoundColumn({
|
||||||
round,
|
round,
|
||||||
seriesById,
|
seriesById,
|
||||||
@@ -116,7 +166,7 @@ function RoundColumn({
|
|||||||
return (
|
return (
|
||||||
<section aria-label={round.label} className="space-y-2">
|
<section aria-label={round.label} className="space-y-2">
|
||||||
<h3 className="px-1 text-xs font-bold text-base-content/45">
|
<h3 className="px-1 text-xs font-bold text-base-content/45">
|
||||||
{stageLabel(round.stage, round.roundNumber)}
|
{bracketRoundLabel(round.stage, round.roundNumber)}
|
||||||
</h3>
|
</h3>
|
||||||
<div className="space-y-3">
|
<div className="space-y-3">
|
||||||
{round.seriesIds.map((seriesId) => {
|
{round.seriesIds.map((seriesId) => {
|
||||||
@@ -166,20 +216,3 @@ function OutcomeSummary({
|
|||||||
</p>
|
</p>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function stageLabel(stage: BracketRoundView["stage"], round?: number) {
|
|
||||||
switch (stage) {
|
|
||||||
case "pair":
|
|
||||||
return "대진";
|
|
||||||
case "round-robin":
|
|
||||||
return `${round ?? 1}라운드`;
|
|
||||||
case "upper":
|
|
||||||
return `승자조 ${round ?? 1}라운드`;
|
|
||||||
case "lower":
|
|
||||||
return `패자조 ${round ?? 1}라운드`;
|
|
||||||
case "grand-final":
|
|
||||||
return "그랜드 파이널";
|
|
||||||
case "reset-final":
|
|
||||||
return "리셋 파이널";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,433 @@
|
|||||||
|
import type {
|
||||||
|
CommunityId,
|
||||||
|
CompetitionTeamView,
|
||||||
|
MatchId,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { ChevronDown } from "lucide-react";
|
||||||
|
import { useState } from "react";
|
||||||
|
import { useLocation } from "react-router";
|
||||||
|
import {
|
||||||
|
formatCompetitionHistoryDate,
|
||||||
|
getSeriesHistoryRecordLabel,
|
||||||
|
getSeriesHistoryResultLabel,
|
||||||
|
getSeriesHistoryStatusLabel,
|
||||||
|
getSeriesHistoryTimePresentation,
|
||||||
|
isCompetitionHistoryCalendarDate,
|
||||||
|
shouldDisplaySeriesHistoryScore,
|
||||||
|
type CompetitionSeriesHistoryDay,
|
||||||
|
type CompetitionSeriesHistoryRow,
|
||||||
|
type CompetitionSeriesHistorySeries,
|
||||||
|
} from "./competition-series-history";
|
||||||
|
import { CompetitionGameHistory } from "./CompetitionGameHistory";
|
||||||
|
import { bracketRoundLabel } from "./double-elimination-bracket-layout";
|
||||||
|
import { isSeriesEntryWinner } from "./series-score-card-model";
|
||||||
|
|
||||||
|
export function CompetitionSeriesHistory({
|
||||||
|
communityId,
|
||||||
|
matchId,
|
||||||
|
history,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
communityId: CommunityId;
|
||||||
|
matchId: MatchId;
|
||||||
|
history: CompetitionSeriesHistoryDay[];
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
}) {
|
||||||
|
const location = useLocation();
|
||||||
|
const historyPath = `${location.pathname}${location.search}`;
|
||||||
|
if (history.length === 0) return null;
|
||||||
|
|
||||||
|
const rows = history.flatMap((day) => day.rows);
|
||||||
|
const anchorRow =
|
||||||
|
rows.find((row) => row.series.status === "in-progress") ??
|
||||||
|
rows.find((row) => isFutureSeries(row.series)) ??
|
||||||
|
rows.at(-1);
|
||||||
|
const jumpLabel =
|
||||||
|
anchorRow?.series.status === "in-progress"
|
||||||
|
? "진행 중 경기로"
|
||||||
|
: anchorRow && isFutureSeries(anchorRow.series)
|
||||||
|
? "다음 경기로"
|
||||||
|
: "최근 결과로";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className="competition-series-history border border-base-content/10 bg-base-100"
|
||||||
|
aria-labelledby="competition-series-history-heading"
|
||||||
|
>
|
||||||
|
<header className="flex flex-wrap items-start justify-between gap-4 border-b border-base-content/10 px-4 py-3">
|
||||||
|
<div>
|
||||||
|
<h3
|
||||||
|
id="competition-series-history-heading"
|
||||||
|
className="text-sm font-bold"
|
||||||
|
>
|
||||||
|
경기 일정·결과
|
||||||
|
</h3>
|
||||||
|
<p className="mt-0.5 text-xs text-content-muted">
|
||||||
|
예정 경기부터 최종 결과까지 날짜순으로 보여줍니다.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{rows.length > 1 && anchorRow && (
|
||||||
|
<a
|
||||||
|
href="#competition-series-history-current"
|
||||||
|
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"
|
||||||
|
/>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
{history.map((day) => {
|
||||||
|
const headingId = historyDayHeadingId(day.dateKey);
|
||||||
|
const dateLabel = formatCompetitionHistoryDate(day.dateKey);
|
||||||
|
return (
|
||||||
|
<section key={day.dateKey} aria-labelledby={headingId}>
|
||||||
|
<h4
|
||||||
|
id={headingId}
|
||||||
|
className="scroll-mt-24 flex items-center justify-between gap-3 border-b border-base-content/10 bg-base-200/60 px-4 py-3 text-sm font-bold"
|
||||||
|
>
|
||||||
|
{isCompetitionHistoryCalendarDate(day.dateKey) ? (
|
||||||
|
<time dateTime={day.dateKey}>{dateLabel}</time>
|
||||||
|
) : (
|
||||||
|
<span>{dateLabel}</span>
|
||||||
|
)}
|
||||||
|
<span className="shrink-0 text-xs font-semibold text-content-muted">
|
||||||
|
{day.rows.length}경기
|
||||||
|
</span>
|
||||||
|
</h4>
|
||||||
|
<ol className="divide-y divide-base-content/10">
|
||||||
|
{day.rows.map((row) => (
|
||||||
|
<li
|
||||||
|
key={row.series.seriesId}
|
||||||
|
id={
|
||||||
|
row.series.seriesId === anchorRow?.series.seriesId
|
||||||
|
? "competition-series-history-current"
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
className={
|
||||||
|
row.series.seriesId === anchorRow?.series.seriesId
|
||||||
|
? "scroll-mt-24"
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<SeriesHistoryRow
|
||||||
|
row={row}
|
||||||
|
teamById={teamById}
|
||||||
|
communityId={communityId}
|
||||||
|
matchId={matchId}
|
||||||
|
historyPath={historyPath}
|
||||||
|
currentHash={location.hash}
|
||||||
|
/>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SeriesHistoryRow({
|
||||||
|
row,
|
||||||
|
teamById,
|
||||||
|
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 (
|
||||||
|
<SeriesSummary
|
||||||
|
row={row}
|
||||||
|
teamById={teamById}
|
||||||
|
hasGameDetails={false}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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">
|
||||||
|
<SeriesSummary
|
||||||
|
row={row}
|
||||||
|
teamById={teamById}
|
||||||
|
hasGameDetails
|
||||||
|
/>
|
||||||
|
</summary>
|
||||||
|
<CompetitionGameHistory
|
||||||
|
games={row.games}
|
||||||
|
teamById={teamById}
|
||||||
|
communityId={communityId}
|
||||||
|
matchId={matchId}
|
||||||
|
historyBackTo={`${historyPath}${seriesHash}`}
|
||||||
|
/>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SeriesSummary({
|
||||||
|
row,
|
||||||
|
teamById,
|
||||||
|
hasGameDetails,
|
||||||
|
}: {
|
||||||
|
row: CompetitionSeriesHistoryRow;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
hasGameDetails: boolean;
|
||||||
|
}) {
|
||||||
|
const { series } = row;
|
||||||
|
const statusLabel = getSeriesHistoryStatusLabel(series);
|
||||||
|
const roundLabel = bracketRoundLabel(
|
||||||
|
series.stage.type,
|
||||||
|
series.stage.roundNumber,
|
||||||
|
);
|
||||||
|
const closedRecordLabel = getSeriesHistoryRecordLabel(
|
||||||
|
series,
|
||||||
|
row.games.length,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
const showRecordLabel = hasGameDetails || !isFutureSeries(series);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="block px-4 py-3 lg:grid lg:min-h-20 lg:grid-cols-[minmax(13rem,1fr)_minmax(20rem,2fr)_minmax(13rem,1fr)] lg:items-center lg:gap-4">
|
||||||
|
<span className="block min-w-0 lg:col-start-2 lg:row-start-1">
|
||||||
|
<SeriesMatchup row={row} teamById={teamById} />
|
||||||
|
</span>
|
||||||
|
|
||||||
|
<span className="mt-3 flex min-w-0 flex-wrap items-center gap-x-3 gap-y-2 lg:col-start-1 lg:row-start-1 lg:mt-0 lg:flex-col lg:items-start lg:gap-1.5">
|
||||||
|
<span className="flex min-w-0 flex-wrap items-center gap-2">
|
||||||
|
<HistoryTime row={row} />
|
||||||
|
<StatusLabel series={series} label={statusLabel} />
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0 break-words text-xs leading-4 text-content-muted">
|
||||||
|
{roundLabel}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
|
||||||
|
{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>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HistoryTime({ row }: { row: CompetitionSeriesHistoryRow }) {
|
||||||
|
const presentation = getSeriesHistoryTimePresentation(row);
|
||||||
|
const kindLabel =
|
||||||
|
row.timestampSource === "decision"
|
||||||
|
? "결정"
|
||||||
|
: row.timestampSource === "scheduled" ||
|
||||||
|
row.timestampSource === "unavailable"
|
||||||
|
? "예정"
|
||||||
|
: "시작";
|
||||||
|
|
||||||
|
if (presentation.dateTime) {
|
||||||
|
return (
|
||||||
|
<time
|
||||||
|
dateTime={presentation.dateTime}
|
||||||
|
aria-label={`${kindLabel} 시각 ${presentation.text}`}
|
||||||
|
className="shrink-0 text-sm font-bold tabular-nums text-base-content"
|
||||||
|
>
|
||||||
|
{row.timestampSource === "decision" && (
|
||||||
|
<span className="mr-1 text-xs text-content-muted">결정</span>
|
||||||
|
)}
|
||||||
|
<span className="font-mono">{presentation.text}</span>
|
||||||
|
</time>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="shrink-0 text-sm font-bold text-content-muted">
|
||||||
|
<span aria-hidden="true" className="font-mono tabular-nums">
|
||||||
|
{presentation.text}
|
||||||
|
</span>
|
||||||
|
{presentation.screenReaderText && (
|
||||||
|
<span className="sr-only">{presentation.screenReaderText}</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function StatusLabel({
|
||||||
|
series,
|
||||||
|
label,
|
||||||
|
}: {
|
||||||
|
series: CompetitionSeriesHistorySeries;
|
||||||
|
label: string;
|
||||||
|
}) {
|
||||||
|
const tone =
|
||||||
|
series.status === "in-progress"
|
||||||
|
? "bg-primary/10 text-base-content"
|
||||||
|
: series.status === "inactive"
|
||||||
|
? "bg-info/10 text-base-content"
|
||||||
|
: "bg-base-200 text-content-muted";
|
||||||
|
return (
|
||||||
|
<span className={`shrink-0 px-1.5 py-0.5 text-xs font-bold ${tone}`}>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SeriesMatchup({
|
||||||
|
row,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
row: CompetitionSeriesHistoryRow;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
}) {
|
||||||
|
const [entryA, entryB] = row.series.entries;
|
||||||
|
const teamAName = teamName(entryA.teamId, teamById);
|
||||||
|
const teamBName = teamName(entryB.teamId, teamById);
|
||||||
|
const teamAWon = isSeriesEntryWinner(row.series, entryA.teamId);
|
||||||
|
const teamBWon = isSeriesEntryWinner(row.series, entryB.teamId);
|
||||||
|
const showScore = shouldDisplaySeriesHistoryScore(row.series);
|
||||||
|
const resultLabel = getSeriesHistoryResultLabel(row.series);
|
||||||
|
const officialWinnerTeamId =
|
||||||
|
row.series.status === "completed" && row.series.outcome.type !== "draw"
|
||||||
|
? row.series.outcome.winnerTeamId
|
||||||
|
: null;
|
||||||
|
const matchupAnnouncement = showScore
|
||||||
|
? `${teamAName} ${entryA.gameWins} 대 ${entryB.gameWins} ${teamBName}`
|
||||||
|
: `${teamAName} 대 ${teamBName}`;
|
||||||
|
const accessibleResult = [
|
||||||
|
matchupAnnouncement,
|
||||||
|
resultLabel === "VS" ? null : resultLabel,
|
||||||
|
officialWinnerTeamId
|
||||||
|
? `${teamName(officialWinnerTeamId, teamById)} 승`
|
||||||
|
: null,
|
||||||
|
]
|
||||||
|
.filter((part): part is string => Boolean(part))
|
||||||
|
.join(", ");
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<span
|
||||||
|
className="grid w-full grid-cols-[minmax(0,1fr)_4.5rem_minmax(0,1fr)] items-center gap-2 sm:grid-cols-[minmax(0,1fr)_5rem_minmax(0,1fr)]"
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<TeamName name={teamAName} winner={teamAWon} align="right" />
|
||||||
|
<span className="flex min-h-10 flex-col items-center justify-center">
|
||||||
|
{showScore ? (
|
||||||
|
<span className="flex items-center justify-center gap-1 font-mono text-base font-bold tabular-nums">
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
teamAWon ? "text-base-content" : "text-content-muted"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{entryA.gameWins}
|
||||||
|
</span>
|
||||||
|
<span className="text-content-disabled">:</span>
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
teamBWon ? "text-base-content" : "text-content-muted"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{entryB.gameWins}
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
{resultLabel && (
|
||||||
|
<span
|
||||||
|
className={
|
||||||
|
showScore
|
||||||
|
? "mt-0.5 text-xs font-bold leading-4 text-content-muted"
|
||||||
|
: row.series.status === "completed"
|
||||||
|
? "text-sm font-bold leading-5 text-base-content"
|
||||||
|
: "text-sm font-bold leading-5 text-content-muted"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{resultLabel}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<TeamName name={teamBName} winner={teamBWon} align="left" />
|
||||||
|
</span>
|
||||||
|
<span className="sr-only">{accessibleResult}</span>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TeamName({
|
||||||
|
name,
|
||||||
|
winner,
|
||||||
|
align,
|
||||||
|
}: {
|
||||||
|
name: string;
|
||||||
|
winner: boolean;
|
||||||
|
align: "left" | "right";
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={`flex min-h-10 min-w-0 items-center gap-1 text-sm leading-5 ${
|
||||||
|
align === "right" ? "justify-end text-right" : "justify-start text-left"
|
||||||
|
} ${winner ? "font-bold text-base-content" : "text-content-subtle"}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
>
|
||||||
|
<span className="min-w-0 break-words">{name}</span>
|
||||||
|
{winner && (
|
||||||
|
<span className="shrink-0 text-xs font-bold text-base-content">승</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamName(
|
||||||
|
teamId: TeamId | null,
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>,
|
||||||
|
): string {
|
||||||
|
if (teamId === null) return "미정";
|
||||||
|
return teamById.get(teamId)?.name ?? "알 수 없는 팀";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isFutureSeries(series: CompetitionSeriesHistorySeries): boolean {
|
||||||
|
return (
|
||||||
|
series.status === "inactive" ||
|
||||||
|
series.status === "waiting" ||
|
||||||
|
series.status === "ready"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function historyDayHeadingId(dateKey: string): string {
|
||||||
|
return `competition-series-history-day-${dateKey}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function seriesHistoryDetailsId(seriesId: string): string {
|
||||||
|
return `competition-series-history-series-${seriesId}`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,395 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionTeamView,
|
||||||
|
DoubleEliminationCompetitionProjection,
|
||||||
|
SeriesId,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { useCallback, useEffect, useId, useRef, useState } from "react";
|
||||||
|
import type {
|
||||||
|
BracketConnectorKind,
|
||||||
|
DoubleEliminationBracketLayout,
|
||||||
|
} from "./double-elimination-bracket-layout";
|
||||||
|
import { DOUBLE_ELIMINATION_BRACKET_GEOMETRY } from "./double-elimination-bracket-layout";
|
||||||
|
import {
|
||||||
|
bracketConnectorKey,
|
||||||
|
getBracketConnectorColorClass,
|
||||||
|
getBracketFocusState,
|
||||||
|
getHorizontalOverflowCues,
|
||||||
|
type HorizontalOverflowCues,
|
||||||
|
} from "./double-elimination-bracket-interaction";
|
||||||
|
import { DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS } from "./competition-display-layout";
|
||||||
|
import { DoubleEliminationMobileBracket } from "./DoubleEliminationMobileBracket";
|
||||||
|
import { SeriesScoreCard } from "./SeriesScoreCard";
|
||||||
|
import { getSeriesScoreCardAccessibleLabel } from "./series-score-card-model";
|
||||||
|
|
||||||
|
export function DoubleEliminationBracket({
|
||||||
|
projection,
|
||||||
|
layout,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
projection: DoubleEliminationCompetitionProjection;
|
||||||
|
layout: DoubleEliminationBracketLayout;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<DesktopBracket
|
||||||
|
projection={projection}
|
||||||
|
layout={layout}
|
||||||
|
teamById={teamById}
|
||||||
|
/>
|
||||||
|
<DoubleEliminationMobileBracket
|
||||||
|
projection={projection}
|
||||||
|
layout={layout}
|
||||||
|
teamById={teamById}
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function DesktopBracket({
|
||||||
|
projection,
|
||||||
|
layout,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
projection: DoubleEliminationCompetitionProjection;
|
||||||
|
layout: DoubleEliminationBracketLayout;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
}) {
|
||||||
|
const seriesById = new Map(
|
||||||
|
projection.series.map((series) => [series.seriesId, series]),
|
||||||
|
);
|
||||||
|
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||||
|
const finalNodes = layout.nodes.filter(({ lane }) => lane === "final");
|
||||||
|
const hasResetRoute = layout.connectors.some(({ kind }) => kind === "reset");
|
||||||
|
const bracketInstructionsId = useId();
|
||||||
|
const scrollViewportRef = useRef<HTMLDivElement>(null);
|
||||||
|
const [hoveredSeriesId, setHoveredSeriesId] = useState<SeriesId | null>(null);
|
||||||
|
const [focusedSeriesId, setFocusedSeriesId] = useState<SeriesId | null>(null);
|
||||||
|
const [overflowCues, setOverflowCues] = useState<HorizontalOverflowCues>({
|
||||||
|
showStart: false,
|
||||||
|
showEnd: false,
|
||||||
|
});
|
||||||
|
const activeSeriesId = focusedSeriesId ?? hoveredSeriesId;
|
||||||
|
const focusState = getBracketFocusState(layout.connectors, activeSeriesId);
|
||||||
|
const roundGuideXs = Array.from(
|
||||||
|
new Set(layout.rounds.map((round) => round.x)),
|
||||||
|
);
|
||||||
|
const finalZoneLeft = Math.max(
|
||||||
|
0,
|
||||||
|
Math.min(...finalNodes.map(({ x }) => x), layout.width) - 16,
|
||||||
|
);
|
||||||
|
const updateOverflowCues = useCallback((viewport: HTMLDivElement) => {
|
||||||
|
const next = getHorizontalOverflowCues(viewport);
|
||||||
|
setOverflowCues((current) =>
|
||||||
|
current.showStart === next.showStart && current.showEnd === next.showEnd
|
||||||
|
? current
|
||||||
|
: next,
|
||||||
|
);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const viewport = scrollViewportRef.current;
|
||||||
|
if (!viewport) return;
|
||||||
|
const update = () => updateOverflowCues(viewport);
|
||||||
|
update();
|
||||||
|
window.addEventListener("resize", update);
|
||||||
|
return () => window.removeEventListener("resize", update);
|
||||||
|
}, [layout.width, updateOverflowCues]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`hidden xl:block ${DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS}`}
|
||||||
|
>
|
||||||
|
<div className="mb-2 flex flex-wrap items-center justify-between gap-3 text-xs text-content-muted">
|
||||||
|
<p id={bracketInstructionsId}>
|
||||||
|
승자조와 패자조는 같은 시간축을 공유하며 오른쪽 결승에서 합류합니다.
|
||||||
|
<span className="ml-2 text-content-subtle">
|
||||||
|
화면에 모두 보이지 않으면 가로로 스크롤하세요.
|
||||||
|
</span>
|
||||||
|
<span className="ml-2 text-content-subtle">
|
||||||
|
경기 카드에 마우스를 올리거나 Tab 키로 초점을 맞추면 연결 경로가
|
||||||
|
강조됩니다.
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
<ConnectorLegend showReset={hasResetRoute} />
|
||||||
|
</div>
|
||||||
|
<div className="relative">
|
||||||
|
<div
|
||||||
|
ref={scrollViewportRef}
|
||||||
|
className="overflow-x-auto border-y border-base-content/10 bg-base-100 pb-2 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary"
|
||||||
|
role="region"
|
||||||
|
aria-label="더블 엘리미네이션 대진표"
|
||||||
|
aria-describedby={bracketInstructionsId}
|
||||||
|
tabIndex={0}
|
||||||
|
onScroll={(event) => updateOverflowCues(event.currentTarget)}
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
className="relative"
|
||||||
|
style={{ width: layout.width, height: layout.height }}
|
||||||
|
>
|
||||||
|
<LaneBand
|
||||||
|
label="승자조"
|
||||||
|
description="패배 시 패자조 이동"
|
||||||
|
top={layout.upperLane.top}
|
||||||
|
height={layout.upperLane.height}
|
||||||
|
width={layout.width}
|
||||||
|
/>
|
||||||
|
<LaneBand
|
||||||
|
label="패자조"
|
||||||
|
description="패배 시 탈락"
|
||||||
|
top={layout.lowerLane.top}
|
||||||
|
height={layout.lowerLane.height}
|
||||||
|
width={layout.width}
|
||||||
|
/>
|
||||||
|
{finalNodes.length > 0 && (
|
||||||
|
<div
|
||||||
|
className="absolute border-l border-primary/20 bg-primary/[0.04]"
|
||||||
|
style={{
|
||||||
|
left: finalZoneLeft,
|
||||||
|
top: 0,
|
||||||
|
width: layout.width - finalZoneLeft,
|
||||||
|
height: layout.height,
|
||||||
|
}}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{roundGuideXs.map((x) => (
|
||||||
|
<div
|
||||||
|
key={x}
|
||||||
|
className="absolute top-0 border-l border-base-content/[0.045]"
|
||||||
|
style={{
|
||||||
|
left: Math.max(
|
||||||
|
0,
|
||||||
|
x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
|
||||||
|
),
|
||||||
|
height: layout.height,
|
||||||
|
}}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<svg
|
||||||
|
className="pointer-events-none absolute inset-0 z-[1]"
|
||||||
|
width={layout.width}
|
||||||
|
height={layout.height}
|
||||||
|
viewBox={`0 0 ${layout.width} ${layout.height}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
focusable="false"
|
||||||
|
>
|
||||||
|
{layout.connectors.map((connector) => {
|
||||||
|
const connectorKey = bracketConnectorKey(connector);
|
||||||
|
const isFocused = focusState.connectorKeys.has(connectorKey);
|
||||||
|
return (
|
||||||
|
<g
|
||||||
|
key={connectorKey}
|
||||||
|
className={getBracketConnectorColorClass(
|
||||||
|
connector.kind,
|
||||||
|
isFocused,
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
d={connector.path}
|
||||||
|
fill="none"
|
||||||
|
stroke="var(--color-base-100)"
|
||||||
|
strokeWidth={isFocused ? 5 : 4}
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
d={connector.path}
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={isFocused ? 2 : 1.5}
|
||||||
|
strokeDasharray={connectorDash(connector.kind)}
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
vectorEffect="non-scaling-stroke"
|
||||||
|
/>
|
||||||
|
<circle
|
||||||
|
cx={connector.targetX}
|
||||||
|
cy={connector.targetY}
|
||||||
|
r={isFocused ? 3 : 2.5}
|
||||||
|
fill="currentColor"
|
||||||
|
/>
|
||||||
|
</g>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</svg>
|
||||||
|
|
||||||
|
{layout.rounds.map((round) => (
|
||||||
|
<section
|
||||||
|
key={`${round.stage}:${round.roundNumber}`}
|
||||||
|
aria-labelledby={`${bracketInstructionsId}-round-${round.stage}-${round.roundNumber}`}
|
||||||
|
>
|
||||||
|
<h3
|
||||||
|
id={`${bracketInstructionsId}-round-${round.stage}-${round.roundNumber}`}
|
||||||
|
aria-label={round.accessibleLabel}
|
||||||
|
className={`absolute z-[2] truncate border-l-2 px-2 text-xs font-bold ${round.lane === "final" ? "border-primary/45 text-base-content" : "border-base-content/15 text-content-muted"}`}
|
||||||
|
style={{
|
||||||
|
left: round.x,
|
||||||
|
top: round.labelY,
|
||||||
|
width: DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnWidth,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{round.label}
|
||||||
|
</h3>
|
||||||
|
{round.seriesIds.map((seriesId, seriesIndex) => {
|
||||||
|
const node = nodeById.get(seriesId);
|
||||||
|
const series = seriesById.get(seriesId);
|
||||||
|
if (!node || !series) return null;
|
||||||
|
const relatedRoutes = layout.connectors.filter(
|
||||||
|
(connector) =>
|
||||||
|
connector.fromSeriesId === node.seriesId ||
|
||||||
|
connector.toSeriesId === node.seriesId,
|
||||||
|
);
|
||||||
|
const routeDescriptionId = `${bracketInstructionsId}-${round.stage}-${round.roundNumber}-${seriesIndex}`;
|
||||||
|
const isFocused = activeSeriesId === node.seriesId;
|
||||||
|
const isRelated = focusState.seriesIds.has(node.seriesId);
|
||||||
|
const accessibilityLabel = getSeriesScoreCardAccessibleLabel(
|
||||||
|
series,
|
||||||
|
node.accessibleLabel,
|
||||||
|
teamById,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={node.seriesId}
|
||||||
|
className={`absolute z-[3] focus-visible:z-[4] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${isFocused ? "z-[4] ring-2 ring-primary/55" : isRelated ? "z-[4] ring-1 ring-base-content/30" : node.lane === "final" ? "outline outline-1 outline-primary/25" : ""}`}
|
||||||
|
style={{
|
||||||
|
left: node.x,
|
||||||
|
top: node.y,
|
||||||
|
width: node.width,
|
||||||
|
minHeight: node.height,
|
||||||
|
}}
|
||||||
|
role="group"
|
||||||
|
aria-label={accessibilityLabel}
|
||||||
|
aria-describedby={
|
||||||
|
relatedRoutes.length > 0 ? routeDescriptionId : undefined
|
||||||
|
}
|
||||||
|
tabIndex={0}
|
||||||
|
onMouseEnter={() => setHoveredSeriesId(node.seriesId)}
|
||||||
|
onMouseLeave={() =>
|
||||||
|
setHoveredSeriesId((current) =>
|
||||||
|
current === node.seriesId ? null : current,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onFocus={() => setFocusedSeriesId(node.seriesId)}
|
||||||
|
onBlur={(event) => {
|
||||||
|
if (!event.currentTarget.contains(event.relatedTarget)) {
|
||||||
|
setFocusedSeriesId((current) =>
|
||||||
|
current === node.seriesId ? null : current,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<SeriesScoreCard
|
||||||
|
series={series}
|
||||||
|
displayLabel={node.label}
|
||||||
|
teamById={teamById}
|
||||||
|
variant="bracket"
|
||||||
|
accessibilityLabel={accessibilityLabel}
|
||||||
|
/>
|
||||||
|
{relatedRoutes.length > 0 && (
|
||||||
|
<span id={routeDescriptionId} className="sr-only">
|
||||||
|
{relatedRoutes
|
||||||
|
.map(({ accessibleLabel }) => accessibleLabel)
|
||||||
|
.join(". ")}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className={`pointer-events-none absolute inset-y-px left-0 z-[5] w-8 bg-linear-to-r from-base-100 to-transparent transition-opacity duration-150 motion-reduce:transition-none ${overflowCues.showStart ? "opacity-100" : "opacity-0"}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<div
|
||||||
|
className={`pointer-events-none absolute inset-y-px right-0 z-[5] w-8 bg-linear-to-l from-base-100 to-transparent transition-opacity duration-150 motion-reduce:transition-none ${overflowCues.showEnd ? "opacity-100" : "opacity-0"}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LaneBand({
|
||||||
|
label,
|
||||||
|
description,
|
||||||
|
top,
|
||||||
|
height,
|
||||||
|
width,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
description: string;
|
||||||
|
top: number;
|
||||||
|
height: number;
|
||||||
|
width: number;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<div
|
||||||
|
className="absolute border-y border-base-content/10 bg-base-content/[0.03]"
|
||||||
|
style={{ top: top - 6, width, height: height + 12 }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
<p
|
||||||
|
className="absolute z-[2] flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-content-muted"
|
||||||
|
style={{ left: 12, top: top - 57 }}
|
||||||
|
>
|
||||||
|
<span>{label}</span>
|
||||||
|
<span className="font-normal normal-case tracking-normal text-content-subtle">
|
||||||
|
{description}
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ConnectorLegend({ showReset }: { showReset: boolean }) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="flex flex-wrap items-center gap-4"
|
||||||
|
role="group"
|
||||||
|
aria-label="연결선 범례"
|
||||||
|
>
|
||||||
|
<LegendItem label="승자 진출" kind="winner" />
|
||||||
|
<LegendItem label="패자조 이동" kind="loser" />
|
||||||
|
{showReset && <LegendItem label="리셋 대진 유지" kind="reset" />}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LegendItem({
|
||||||
|
label,
|
||||||
|
kind,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
kind: BracketConnectorKind;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<span className="inline-flex items-center gap-1.5">
|
||||||
|
<svg width="24" height="6" aria-hidden="true">
|
||||||
|
<path
|
||||||
|
d="M 0 3 H 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="1.25"
|
||||||
|
strokeDasharray={connectorDash(kind)}
|
||||||
|
className={getBracketConnectorColorClass(kind)}
|
||||||
|
/>
|
||||||
|
</svg>
|
||||||
|
{label}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function connectorDash(kind: BracketConnectorKind): string | undefined {
|
||||||
|
if (kind === "loser") return "6 5";
|
||||||
|
if (kind === "reset") return "2 5";
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionTeamView,
|
||||||
|
DoubleEliminationCompetitionProjection,
|
||||||
|
SeriesId,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { useId } from "react";
|
||||||
|
import type { DoubleEliminationBracketLayout } from "./double-elimination-bracket-layout";
|
||||||
|
import { SeriesScoreCard } from "./SeriesScoreCard";
|
||||||
|
import { getSeriesScoreCardAccessibleLabel } from "./series-score-card-model";
|
||||||
|
|
||||||
|
export function DoubleEliminationMobileBracket({
|
||||||
|
projection,
|
||||||
|
layout,
|
||||||
|
teamById,
|
||||||
|
}: {
|
||||||
|
projection: DoubleEliminationCompetitionProjection;
|
||||||
|
layout: DoubleEliminationBracketLayout;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
}) {
|
||||||
|
const bracketId = useId();
|
||||||
|
const seriesById = new Map(
|
||||||
|
projection.series.map((series) => [series.seriesId, series]),
|
||||||
|
);
|
||||||
|
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||||
|
const sections = [
|
||||||
|
{
|
||||||
|
key: "upper",
|
||||||
|
title: "승자조",
|
||||||
|
description: "승리하면 승자조에 남고, 패배하면 패자조로 이동합니다.",
|
||||||
|
stages: new Set(["upper"]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "lower",
|
||||||
|
title: "패자조",
|
||||||
|
description: "승리하면 다음 라운드로 진출하고, 패배하면 탈락합니다.",
|
||||||
|
stages: new Set(["lower"]),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "final",
|
||||||
|
title: "결승",
|
||||||
|
description: "승자조 우승 팀과 패자조 우승 팀이 최종 우승을 결정합니다.",
|
||||||
|
stages: new Set(["grand-final", "reset-final"]),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="space-y-7 xl:hidden"
|
||||||
|
role="region"
|
||||||
|
aria-label="더블 엘리미네이션 대진표"
|
||||||
|
>
|
||||||
|
{sections.map((section) => {
|
||||||
|
const groups = layout.mobileGroups.filter((group) =>
|
||||||
|
section.stages.has(group.stage),
|
||||||
|
);
|
||||||
|
if (groups.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
key={section.key}
|
||||||
|
aria-labelledby={`${bracketId}-${section.key}`}
|
||||||
|
>
|
||||||
|
<div className="mb-3 border-b border-base-content/10 pb-2">
|
||||||
|
<h3
|
||||||
|
id={`${bracketId}-${section.key}`}
|
||||||
|
className="text-sm font-bold"
|
||||||
|
>
|
||||||
|
{section.title}
|
||||||
|
</h3>
|
||||||
|
<p className="mt-0.5 text-xs text-content-muted">
|
||||||
|
{section.description}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div className="space-y-5">
|
||||||
|
{groups.map((group) => (
|
||||||
|
<section
|
||||||
|
key={`${group.stage}:${group.roundNumber}`}
|
||||||
|
aria-labelledby={`${bracketId}-${group.stage}-${group.roundNumber}`}
|
||||||
|
>
|
||||||
|
<h4
|
||||||
|
id={`${bracketId}-${group.stage}-${group.roundNumber}`}
|
||||||
|
className="mb-2 text-xs font-bold text-content-muted"
|
||||||
|
aria-label={group.accessibleLabel}
|
||||||
|
>
|
||||||
|
{group.label}
|
||||||
|
</h4>
|
||||||
|
<div className="space-y-3">
|
||||||
|
{group.seriesIds.map((seriesId) => {
|
||||||
|
const series = seriesById.get(seriesId);
|
||||||
|
if (!series) return null;
|
||||||
|
const node = nodeById.get(seriesId);
|
||||||
|
const accessibilityLabel =
|
||||||
|
getSeriesScoreCardAccessibleLabel(
|
||||||
|
series,
|
||||||
|
node?.accessibleLabel,
|
||||||
|
teamById,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<div key={seriesId}>
|
||||||
|
<SeriesScoreCard
|
||||||
|
series={series}
|
||||||
|
displayLabel={node?.label}
|
||||||
|
teamById={teamById}
|
||||||
|
variant="bracket"
|
||||||
|
accessibilityLabel={accessibilityLabel}
|
||||||
|
/>
|
||||||
|
<MobileRoutes
|
||||||
|
layout={layout}
|
||||||
|
seriesId={seriesId}
|
||||||
|
seriesLabel={node?.accessibleLabel ?? "경기"}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MobileRoutes({
|
||||||
|
layout,
|
||||||
|
seriesId,
|
||||||
|
seriesLabel,
|
||||||
|
}: {
|
||||||
|
layout: DoubleEliminationBracketLayout;
|
||||||
|
seriesId: SeriesId;
|
||||||
|
seriesLabel: string;
|
||||||
|
}) {
|
||||||
|
const routes = layout.connectors.filter(
|
||||||
|
(connector) => connector.fromSeriesId === seriesId,
|
||||||
|
);
|
||||||
|
if (routes.length === 0) return null;
|
||||||
|
return (
|
||||||
|
<ul
|
||||||
|
className="mt-1.5 space-y-0.5 border-l border-base-content/10 pl-2 text-[11px] text-content-muted"
|
||||||
|
aria-label={`${seriesLabel} 연결 경로`}
|
||||||
|
>
|
||||||
|
{routes.map((route) => (
|
||||||
|
<li key={`${route.select}:${route.toSeriesId}:${route.toSlot}`}>
|
||||||
|
<span aria-hidden="true">{route.label}</span>
|
||||||
|
<span className="sr-only">{route.accessibleLabel}</span>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import {
|
||||||
|
moveMatchDetailTabFocus,
|
||||||
|
type MatchDetailTab,
|
||||||
|
type MatchDetailTabId,
|
||||||
|
type MatchDetailTabNavigationKey,
|
||||||
|
} from "./match-detail-tabs";
|
||||||
|
|
||||||
|
export function MatchDetailTabBar({
|
||||||
|
tabs,
|
||||||
|
activeTab,
|
||||||
|
onChange,
|
||||||
|
}: {
|
||||||
|
tabs: readonly MatchDetailTab[];
|
||||||
|
activeTab: MatchDetailTabId;
|
||||||
|
onChange: (tab: MatchDetailTabId) => void;
|
||||||
|
}) {
|
||||||
|
const tabRefs = useRef<
|
||||||
|
Partial<Record<MatchDetailTabId, HTMLButtonElement | null>>
|
||||||
|
>({});
|
||||||
|
const previousActiveTabRef = useRef(activeTab);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
tabRefs.current[activeTab]?.scrollIntoView({
|
||||||
|
block: "nearest",
|
||||||
|
inline: "nearest",
|
||||||
|
});
|
||||||
|
if (previousActiveTabRef.current === activeTab) return;
|
||||||
|
|
||||||
|
const activePanel = document.getElementById(
|
||||||
|
`match-detail-panel-${activeTab}`,
|
||||||
|
);
|
||||||
|
const panelTop = activePanel?.getBoundingClientRect().top;
|
||||||
|
if (
|
||||||
|
activePanel &&
|
||||||
|
panelTop !== undefined &&
|
||||||
|
(panelTop < 96 || panelTop >= window.innerHeight)
|
||||||
|
) {
|
||||||
|
activePanel.scrollIntoView({ block: "start" });
|
||||||
|
}
|
||||||
|
previousActiveTabRef.current = activeTab;
|
||||||
|
}, [activeTab]);
|
||||||
|
|
||||||
|
function handleKeyDown(
|
||||||
|
event: React.KeyboardEvent<HTMLButtonElement>,
|
||||||
|
currentTab: MatchDetailTabId,
|
||||||
|
) {
|
||||||
|
if (!isNavigationKey(event.key)) return;
|
||||||
|
const nextTab = moveMatchDetailTabFocus(tabs, currentTab, event.key);
|
||||||
|
if (!nextTab) return;
|
||||||
|
|
||||||
|
event.preventDefault();
|
||||||
|
onChange(nextTab);
|
||||||
|
window.requestAnimationFrame(() => tabRefs.current[nextTab]?.focus());
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="sticky top-12 z-40 -mx-4 border-y border-base-content/10 bg-base-100/95 px-4 backdrop-blur sm:-mx-6 sm:px-6">
|
||||||
|
<div
|
||||||
|
className="flex overflow-x-auto"
|
||||||
|
role="tablist"
|
||||||
|
aria-label="내전 상세"
|
||||||
|
>
|
||||||
|
{tabs.map((tab) => {
|
||||||
|
const selected = activeTab === tab.id;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={tab.id}
|
||||||
|
ref={(element) => {
|
||||||
|
tabRefs.current[tab.id] = element;
|
||||||
|
}}
|
||||||
|
id={`match-detail-tab-${tab.id}`}
|
||||||
|
type="button"
|
||||||
|
role="tab"
|
||||||
|
aria-selected={selected}
|
||||||
|
aria-controls={`match-detail-panel-${tab.id}`}
|
||||||
|
tabIndex={selected ? 0 : -1}
|
||||||
|
onClick={() => onChange(tab.id)}
|
||||||
|
onKeyDown={(event) => handleKeyDown(event, tab.id)}
|
||||||
|
className={`min-h-11 flex-none whitespace-nowrap border-b-2 px-4 text-xs font-bold transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary ${
|
||||||
|
selected
|
||||||
|
? "border-primary bg-primary/5 text-base-content"
|
||||||
|
: "border-transparent text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNavigationKey(
|
||||||
|
key: string,
|
||||||
|
): key is MatchDetailTabNavigationKey {
|
||||||
|
return (
|
||||||
|
key === "ArrowLeft" ||
|
||||||
|
key === "ArrowRight" ||
|
||||||
|
key === "Home" ||
|
||||||
|
key === "End"
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -3,73 +3,223 @@ import type {
|
|||||||
SeriesProjection,
|
SeriesProjection,
|
||||||
TeamId,
|
TeamId,
|
||||||
} from "@lolympus/contracts";
|
} from "@lolympus/contracts";
|
||||||
|
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry";
|
||||||
|
import {
|
||||||
|
formatSeriesScore,
|
||||||
|
getSeriesScoreCardAccessibleLabel,
|
||||||
|
getSeriesScoreCardIdentity,
|
||||||
|
getSeriesScoreCardPresentation,
|
||||||
|
isSeriesEntryWinner,
|
||||||
|
type SeriesScoreCardTone,
|
||||||
|
} from "./series-score-card-model";
|
||||||
|
|
||||||
const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
|
const CARD_TONE_CLASS: Record<SeriesScoreCardTone, string> = {
|
||||||
inactive: "비활성",
|
muted: "",
|
||||||
waiting: "대진 대기",
|
ready: "border-l-2 border-l-success/70",
|
||||||
ready: "경기 가능",
|
live: "border-l-2 border-l-primary/70",
|
||||||
"in-progress": "진행 중",
|
completed: "",
|
||||||
completed: "종료",
|
adjudicated: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const HEADER_TONE_CLASS: Record<SeriesScoreCardTone, string> = {
|
||||||
|
muted: "",
|
||||||
|
ready: "bg-success/[0.035]",
|
||||||
|
live: "bg-primary/[0.04]",
|
||||||
|
completed: "",
|
||||||
|
adjudicated: "",
|
||||||
|
};
|
||||||
|
|
||||||
|
const STATUS_TONE_CLASS: Record<SeriesScoreCardTone, string> = {
|
||||||
|
muted: "border-base-content/10 bg-base-200 text-content-muted",
|
||||||
|
ready: "border-success/30 bg-success/10 text-base-content",
|
||||||
|
live: "border-primary/30 bg-primary/10 text-base-content",
|
||||||
|
completed: "border-base-content/10 bg-base-200 text-content-muted",
|
||||||
|
adjudicated: "border-warning/35 bg-warning/10 text-base-content",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function SeriesScoreCard({
|
export function SeriesScoreCard({
|
||||||
series,
|
series,
|
||||||
|
displayLabel,
|
||||||
teamById,
|
teamById,
|
||||||
|
variant = "default",
|
||||||
|
accessibilityLabel,
|
||||||
}: {
|
}: {
|
||||||
series: SeriesProjection;
|
series: SeriesProjection;
|
||||||
|
displayLabel?: string;
|
||||||
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
variant?: "default" | "bracket";
|
||||||
|
accessibilityLabel?: string;
|
||||||
}) {
|
}) {
|
||||||
const winnerTeamId =
|
const isBracket = variant === "bracket";
|
||||||
series.status === "completed" && series.outcome.type !== "draw"
|
const identity = getSeriesScoreCardIdentity(series, displayLabel);
|
||||||
? series.outcome.winnerTeamId
|
const presentation = getSeriesScoreCardPresentation(series);
|
||||||
: null;
|
const cardAccessibilityLabel =
|
||||||
|
accessibilityLabel ??
|
||||||
|
getSeriesScoreCardAccessibleLabel(series, displayLabel, teamById);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<article
|
<article
|
||||||
className="border border-base-content/10 bg-base-100"
|
className={`border border-base-content/10 bg-base-100 ${CARD_TONE_CLASS[presentation.tone]}`}
|
||||||
aria-label={`${series.code ?? "경기"} ${STATUS_LABEL[series.status]}`}
|
aria-label={cardAccessibilityLabel}
|
||||||
|
style={
|
||||||
|
isBracket ? { height: SERIES_SCORE_CARD_GEOMETRY.height } : undefined
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<header className="flex items-center justify-between gap-3 border-b border-base-content/8 px-3 py-2">
|
<header
|
||||||
<span className="truncate text-xs font-bold text-base-content/65">
|
className={`flex items-center justify-between gap-2 border-b border-base-content/8 ${HEADER_TONE_CLASS[presentation.tone]} ${
|
||||||
{series.code ?? "Series"}
|
isBracket ? "px-2" : "px-3 py-2"
|
||||||
|
}`}
|
||||||
|
style={
|
||||||
|
isBracket
|
||||||
|
? { height: SERIES_SCORE_CARD_GEOMETRY.headerHeight }
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span
|
||||||
|
className="min-w-0"
|
||||||
|
title={
|
||||||
|
identity.code
|
||||||
|
? `${identity.label} (${identity.code})`
|
||||||
|
: identity.label
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<span className="block truncate text-[11px] font-bold leading-3 text-base-content/75">
|
||||||
|
{identity.label}
|
||||||
|
</span>
|
||||||
|
{identity.code && (
|
||||||
|
<span className="mt-0.5 block truncate font-mono text-[9px] leading-[10px] text-content-subtle">
|
||||||
|
{identity.code}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</span>
|
</span>
|
||||||
<span className="shrink-0 text-[11px] text-base-content/40">
|
<span
|
||||||
{STATUS_LABEL[series.status]}
|
className={`inline-flex shrink-0 items-center gap-1 border px-1 py-0.5 text-[10px] font-bold leading-3 ${STATUS_TONE_CLASS[presentation.tone]}`}
|
||||||
|
>
|
||||||
|
{(presentation.tone === "ready" || presentation.tone === "live") && (
|
||||||
|
<span
|
||||||
|
className={`size-1.5 ${presentation.tone === "ready" ? "bg-success" : "bg-primary"}`}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{presentation.label}
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
<div className="divide-y divide-base-content/8">
|
<div
|
||||||
|
className={
|
||||||
|
isBracket ? "relative" : "divide-y divide-base-content/8"
|
||||||
|
}
|
||||||
|
>
|
||||||
{series.entries.map((entry) => {
|
{series.entries.map((entry) => {
|
||||||
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
||||||
const isWinner = entry.teamId === winnerTeamId;
|
const isWinner = isSeriesEntryWinner(series, entry.teamId);
|
||||||
return (
|
const score = formatSeriesScore(series, entry.gameWins);
|
||||||
<div
|
const teamName =
|
||||||
|
team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중");
|
||||||
|
return isBracket ? (
|
||||||
|
<BracketEntryRow
|
||||||
key={entry.slot}
|
key={entry.slot}
|
||||||
className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5"
|
entry={entry}
|
||||||
>
|
isWinner={isWinner}
|
||||||
<span className="text-[10px] font-bold text-base-content/30">
|
score={score}
|
||||||
{entry.slot}
|
teamName={teamName}
|
||||||
</span>
|
/>
|
||||||
<span
|
) : (
|
||||||
className={`truncate text-sm ${
|
<DefaultEntryRow
|
||||||
isWinner
|
key={entry.slot}
|
||||||
? "font-bold text-base-content"
|
entry={entry}
|
||||||
: "text-base-content/60"
|
isWinner={isWinner}
|
||||||
}`}
|
score={score}
|
||||||
>
|
teamName={teamName}
|
||||||
{team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중")}
|
/>
|
||||||
{isWinner && (
|
|
||||||
<span className="ml-2 text-[10px] font-bold text-success">
|
|
||||||
승리
|
|
||||||
</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
|
|
||||||
{entry.gameWins}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
|
{isBracket && (
|
||||||
|
<span
|
||||||
|
className="pointer-events-none absolute inset-x-0 border-t border-base-content/8"
|
||||||
|
style={{ top: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function DefaultEntryRow({
|
||||||
|
entry,
|
||||||
|
isWinner,
|
||||||
|
score,
|
||||||
|
teamName,
|
||||||
|
}: {
|
||||||
|
entry: SeriesProjection["entries"][number];
|
||||||
|
isWinner: boolean;
|
||||||
|
score: string;
|
||||||
|
teamName: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5">
|
||||||
|
<span className="text-[10px] font-bold text-base-content/30">
|
||||||
|
{entry.slot}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`truncate text-sm ${
|
||||||
|
isWinner ? "font-bold text-base-content" : "text-content-subtle"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{teamName}
|
||||||
|
{isWinner && (
|
||||||
|
<span className="ml-2 text-[10px] font-bold text-base-content">
|
||||||
|
승리
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
<Score score={score} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function BracketEntryRow({
|
||||||
|
entry,
|
||||||
|
isWinner,
|
||||||
|
score,
|
||||||
|
teamName,
|
||||||
|
}: {
|
||||||
|
entry: SeriesProjection["entries"][number];
|
||||||
|
isWinner: boolean;
|
||||||
|
score: string;
|
||||||
|
teamName: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="grid grid-cols-[0.75rem_minmax(0,1fr)_1.5rem_1.25rem] items-center gap-1 px-2"
|
||||||
|
style={{ height: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
|
||||||
|
>
|
||||||
|
<span className="text-[9px] font-bold text-base-content/30">
|
||||||
|
{entry.slot}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`line-clamp-2 break-words text-[13px] leading-4 ${
|
||||||
|
isWinner ? "font-bold text-base-content" : "text-content-subtle"
|
||||||
|
}`}
|
||||||
|
title={teamName}
|
||||||
|
>
|
||||||
|
{teamName}
|
||||||
|
</span>
|
||||||
|
<span className="text-center text-[10px] font-bold text-base-content">
|
||||||
|
{isWinner ? "승리" : null}
|
||||||
|
</span>
|
||||||
|
<Score score={score} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function Score({ score }: { score: string }) {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className="text-right font-mono text-base font-bold tabular-nums text-base-content/75"
|
||||||
|
aria-label={score === "—" ? "점수 없음" : `${score}승`}
|
||||||
|
>
|
||||||
|
{score}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionTeamView,
|
||||||
|
SeriesProjection,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import {
|
||||||
|
getTeamSeriesPresentation,
|
||||||
|
type TeamSeriesTone,
|
||||||
|
} from "../../pages/match-team-progress-view";
|
||||||
|
import { isSeriesEntryWinner } from "./series-score-card-model";
|
||||||
|
|
||||||
|
const STATUS_TONE_CLASS: Record<TeamSeriesTone, string> = {
|
||||||
|
muted: "border-base-content/15 bg-base-200 text-base-content",
|
||||||
|
ready: "border-primary/50 bg-primary/10 text-base-content",
|
||||||
|
live: "border-info/60 bg-info/10 text-base-content",
|
||||||
|
completed: "border-base-content/20 bg-base-200 text-base-content",
|
||||||
|
adjudicated: "border-warning/60 bg-warning/15 text-base-content",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function TeamSeriesCard({
|
||||||
|
series,
|
||||||
|
displayLabel,
|
||||||
|
teamById,
|
||||||
|
highlightedTeamId,
|
||||||
|
emphasized = false,
|
||||||
|
children,
|
||||||
|
}: {
|
||||||
|
series: SeriesProjection;
|
||||||
|
displayLabel: string;
|
||||||
|
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||||
|
highlightedTeamId: TeamId;
|
||||||
|
emphasized?: boolean;
|
||||||
|
children?: ReactNode;
|
||||||
|
}) {
|
||||||
|
const presentation = getTeamSeriesPresentation(series);
|
||||||
|
const headingId = `team-series-${String(series.seriesId)}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<article
|
||||||
|
className={`overflow-hidden border bg-base-100 ${
|
||||||
|
emphasized ? "border-primary/30" : "border-base-content/10"
|
||||||
|
}`}
|
||||||
|
aria-labelledby={headingId}
|
||||||
|
>
|
||||||
|
<header
|
||||||
|
className={`flex flex-wrap items-start justify-between gap-3 border-b px-4 py-3 sm:px-5 ${
|
||||||
|
emphasized
|
||||||
|
? "border-primary/20 bg-primary/[0.035]"
|
||||||
|
: "border-base-content/10 bg-base-200/40"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<h3
|
||||||
|
id={headingId}
|
||||||
|
className="break-words text-base font-black text-base-content"
|
||||||
|
>
|
||||||
|
{displayLabel}
|
||||||
|
</h3>
|
||||||
|
<div className="mt-1 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-content-muted">
|
||||||
|
{series.code && (
|
||||||
|
<code className="break-all font-mono">{series.code}</code>
|
||||||
|
)}
|
||||||
|
<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]}`}
|
||||||
|
>
|
||||||
|
{presentation.label}
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<ul
|
||||||
|
className="divide-y divide-base-content/10"
|
||||||
|
aria-label={`${displayLabel} 대진`}
|
||||||
|
>
|
||||||
|
{series.entries.map((entry) => {
|
||||||
|
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
||||||
|
const teamName =
|
||||||
|
team?.name ?? (entry.teamId ? "알 수 없는 팀" : "상대 결정 대기");
|
||||||
|
const isHighlightedTeam = entry.teamId === highlightedTeamId;
|
||||||
|
const isWinner = isSeriesEntryWinner(series, entry.teamId);
|
||||||
|
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" : ""
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<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">
|
||||||
|
이 팀
|
||||||
|
</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>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content">
|
||||||
|
<span className="sr-only">
|
||||||
|
{presentation.showScore ? "게임 승수: " : "점수 없음"}
|
||||||
|
</span>
|
||||||
|
{presentation.showScore ? (
|
||||||
|
entry.gameWins
|
||||||
|
) : (
|
||||||
|
<span aria-hidden="true">—</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
|
||||||
|
{children}
|
||||||
|
</article>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function seriesRuleLabel(series: SeriesProjection): string {
|
||||||
|
if (series.rule.type === "fixed-games") {
|
||||||
|
return `${series.rule.gameCount}게임`;
|
||||||
|
}
|
||||||
|
return `${series.rule.maxGames}전 ${series.rule.winsRequired}선승`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
import type { TeamTournamentCodeView } from "@lolympus/contracts";
|
||||||
|
import { Check, Copy, LoaderCircle } from "lucide-react";
|
||||||
|
import { useEffect, useLayoutEffect, useRef, useState } from "react";
|
||||||
|
import {
|
||||||
|
copyTournamentCode,
|
||||||
|
getNextTournamentCodeExpiryDelay,
|
||||||
|
getTournamentCodeCopyLabel,
|
||||||
|
getTournamentCodeExpiryLabel,
|
||||||
|
getTournamentCodePresentation,
|
||||||
|
type TournamentCodeCopyFeedback,
|
||||||
|
type TournamentCodeTone,
|
||||||
|
} from "../../pages/match-team-progress-view";
|
||||||
|
|
||||||
|
const CODE_TONE_CLASS: Record<TournamentCodeTone, string> = {
|
||||||
|
pending: "border-base-content/15 bg-base-200 text-base-content",
|
||||||
|
available: "border-primary/50 bg-primary/10 text-base-content",
|
||||||
|
expired: "border-error/50 bg-error/10 text-base-content",
|
||||||
|
used: "border-base-content/20 bg-base-200 text-base-content",
|
||||||
|
};
|
||||||
|
|
||||||
|
type VisibleFeedback = TournamentCodeCopyFeedback & { gameSlotId: string };
|
||||||
|
|
||||||
|
export function TeamTournamentCodes({
|
||||||
|
assignments,
|
||||||
|
seriesLabel,
|
||||||
|
}: {
|
||||||
|
assignments: readonly TeamTournamentCodeView[];
|
||||||
|
seriesLabel: string;
|
||||||
|
}) {
|
||||||
|
const [copyingSlotId, setCopyingSlotId] = useState<string | null>(null);
|
||||||
|
const [feedback, setFeedback] = useState<VisibleFeedback | null>(null);
|
||||||
|
const [now, setNow] = useState(() => Date.now());
|
||||||
|
const clearFeedbackTimeoutRef = useRef<number | null>(null);
|
||||||
|
|
||||||
|
useEffect(
|
||||||
|
() => () => {
|
||||||
|
if (clearFeedbackTimeoutRef.current !== null) {
|
||||||
|
window.clearTimeout(clearFeedbackTimeoutRef.current);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const delay = getNextTournamentCodeExpiryDelay(assignments, now);
|
||||||
|
if (delay === null) return;
|
||||||
|
const timeoutId = window.setTimeout(
|
||||||
|
() => setNow(Date.now()),
|
||||||
|
Math.max(1, delay),
|
||||||
|
);
|
||||||
|
return () => window.clearTimeout(timeoutId);
|
||||||
|
}, [assignments, now]);
|
||||||
|
|
||||||
|
if (assignments.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="border-t border-base-content/10 px-4 py-5 sm:px-5">
|
||||||
|
<p role="status" className="text-sm text-content-muted">
|
||||||
|
이 경기에 배정된 토너먼트 코드가 없습니다.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleCopy(assignment: TeamTournamentCodeView) {
|
||||||
|
if (!assignment.code || copyingSlotId !== null) return;
|
||||||
|
if (clearFeedbackTimeoutRef.current !== null) {
|
||||||
|
window.clearTimeout(clearFeedbackTimeoutRef.current);
|
||||||
|
clearFeedbackTimeoutRef.current = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const slotId = String(assignment.gameSlotId);
|
||||||
|
const gameLabel = `${seriesLabel} ${assignment.ordinal}세트`;
|
||||||
|
const currentTime = readCurrentTime();
|
||||||
|
setNow(currentTime);
|
||||||
|
if (!getTournamentCodePresentation(assignment, currentTime).canCopy) {
|
||||||
|
setFeedback({
|
||||||
|
kind: "error",
|
||||||
|
gameSlotId: slotId,
|
||||||
|
message: `${gameLabel} 코드는 만료되었거나 사용할 수 없어 복사하지 않았습니다.`,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setCopyingSlotId(slotId);
|
||||||
|
setFeedback(null);
|
||||||
|
const clipboard = navigator.clipboard;
|
||||||
|
const result = await copyTournamentCode(
|
||||||
|
clipboard?.writeText ? clipboard.writeText.bind(clipboard) : undefined,
|
||||||
|
assignment.code,
|
||||||
|
gameLabel,
|
||||||
|
);
|
||||||
|
setCopyingSlotId(null);
|
||||||
|
setFeedback({ ...result, gameSlotId: slotId });
|
||||||
|
|
||||||
|
if (result.kind === "success") {
|
||||||
|
clearFeedbackTimeoutRef.current = window.setTimeout(() => {
|
||||||
|
setFeedback(null);
|
||||||
|
clearFeedbackTimeoutRef.current = null;
|
||||||
|
}, 2500);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
className="border-t border-base-content/10"
|
||||||
|
aria-label={`${seriesLabel} 토너먼트 코드`}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-baseline justify-between gap-2 bg-base-200/25 px-4 py-2.5 sm:px-5">
|
||||||
|
<h4 className="text-sm font-bold text-base-content">게임 코드</h4>
|
||||||
|
<p className="text-xs text-content-muted">
|
||||||
|
세트에 맞는 코드를 복사해 클라이언트에 입력하세요.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ol className="divide-y divide-base-content/10">
|
||||||
|
{assignments.map((assignment) => {
|
||||||
|
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">
|
||||||
|
전체 Game {assignment.displayNumber}
|
||||||
|
</p>
|
||||||
|
</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>
|
||||||
|
|
||||||
|
<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>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ol>
|
||||||
|
|
||||||
|
{feedback && (
|
||||||
|
<p
|
||||||
|
className={`border-t px-4 py-2.5 text-sm sm:px-5 ${
|
||||||
|
feedback.kind === "error"
|
||||||
|
? "border-error/30 bg-error/10 text-base-content"
|
||||||
|
: "border-success/30 bg-success/10 text-base-content"
|
||||||
|
}`}
|
||||||
|
role={feedback.kind === "error" ? "alert" : "status"}
|
||||||
|
aria-live={feedback.kind === "error" ? "assertive" : "polite"}
|
||||||
|
aria-atomic="true"
|
||||||
|
>
|
||||||
|
{feedback.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readCurrentTime(): number {
|
||||||
|
return Date.now();
|
||||||
|
}
|
||||||
|
|
||||||
|
function AutoSizingCodeField({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
}) {
|
||||||
|
const fieldRef = useRef<HTMLTextAreaElement>(null);
|
||||||
|
|
||||||
|
useLayoutEffect(() => {
|
||||||
|
const resizeToContent = () => {
|
||||||
|
const field = fieldRef.current;
|
||||||
|
if (!field) return;
|
||||||
|
field.style.height = "auto";
|
||||||
|
const borderHeight = field.offsetHeight - field.clientHeight;
|
||||||
|
field.style.height = `${field.scrollHeight + borderHeight}px`;
|
||||||
|
};
|
||||||
|
|
||||||
|
resizeToContent();
|
||||||
|
window.addEventListener("resize", resizeToContent);
|
||||||
|
return () => window.removeEventListener("resize", resizeToContent);
|
||||||
|
}, [value]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<textarea
|
||||||
|
ref={fieldRef}
|
||||||
|
aria-label={label}
|
||||||
|
className="block min-h-11 w-full resize-none overflow-hidden border border-base-content/15 bg-base-100 px-3 py-2 font-mono text-sm font-bold leading-5 text-base-content focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
|
onClick={(event) => event.currentTarget.select()}
|
||||||
|
onFocus={(event) => event.currentTarget.select()}
|
||||||
|
readOnly
|
||||||
|
rows={1}
|
||||||
|
spellCheck={false}
|
||||||
|
value={value}
|
||||||
|
wrap="soft"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import type { CompetitionDetailResponse } from "@lolympus/contracts";
|
||||||
|
import { createDoubleEliminationBracketLayout } from "./double-elimination-bracket-layout.ts";
|
||||||
|
|
||||||
|
export const MATCH_PAGE_MAX_WIDTH_CLASS = "max-w-5xl";
|
||||||
|
|
||||||
|
export const DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS =
|
||||||
|
"relative left-1/2 w-[calc(100vw-3rem)] max-w-[1600px] -translate-x-1/2";
|
||||||
|
|
||||||
|
export function createCompetitionBracketLayout(
|
||||||
|
competition: CompetitionDetailResponse,
|
||||||
|
) {
|
||||||
|
const { format, projection, teams } = competition;
|
||||||
|
if (
|
||||||
|
format.type !== "double-elimination" ||
|
||||||
|
projection.formatType !== "double-elimination" ||
|
||||||
|
format.teamCount !== teams.length
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const hasResetFinal = projection.series.some(
|
||||||
|
({ stage }) => stage.type === "reset-final",
|
||||||
|
);
|
||||||
|
if (format.resetFinalEnabled !== hasResetFinal) return null;
|
||||||
|
|
||||||
|
return createDoubleEliminationBracketLayout(projection, {
|
||||||
|
teamCount: format.teamCount,
|
||||||
|
resetFinalEnabled: format.resetFinalEnabled,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,479 @@
|
|||||||
|
import type {
|
||||||
|
CompetitionGameView,
|
||||||
|
CompetitionProjection,
|
||||||
|
IsoDateTime,
|
||||||
|
SeriesProjection,
|
||||||
|
SeriesSchedule,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { internalMatchGamePath } from "../../lib/internal-match-routes.ts";
|
||||||
|
|
||||||
|
export type CompetitionSeriesHistorySeries = SeriesProjection;
|
||||||
|
|
||||||
|
export type CompetitionSeriesHistoryTimestampSource =
|
||||||
|
| "game-start"
|
||||||
|
| "decision"
|
||||||
|
| "scheduled"
|
||||||
|
| "unavailable";
|
||||||
|
|
||||||
|
export interface CompetitionSeriesHistoryRow {
|
||||||
|
series: CompetitionSeriesHistorySeries;
|
||||||
|
games: CompetitionGameView[];
|
||||||
|
occurredAt: IsoDateTime | null;
|
||||||
|
timestampSource: CompetitionSeriesHistoryTimestampSource;
|
||||||
|
dateKey: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CompetitionSeriesHistoryDay {
|
||||||
|
dateKey: string;
|
||||||
|
rows: CompetitionSeriesHistoryRow[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SeriesHistoryTimePresentation {
|
||||||
|
text: string;
|
||||||
|
dateTime: string | null;
|
||||||
|
screenReaderText: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
type HistoryProjection = Pick<CompetitionProjection, "series" | "games">;
|
||||||
|
|
||||||
|
const KOREAN_WEEKDAYS = [
|
||||||
|
"일",
|
||||||
|
"월",
|
||||||
|
"화",
|
||||||
|
"수",
|
||||||
|
"목",
|
||||||
|
"금",
|
||||||
|
"토",
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const UNKNOWN_DATE_KEY = "unknown";
|
||||||
|
const UNKNOWN_RECORD_DATE_KEY = "record-unknown";
|
||||||
|
|
||||||
|
export function competitionHistoryGameDetailPath(
|
||||||
|
communityId: string,
|
||||||
|
matchId: string,
|
||||||
|
game: Pick<CompetitionGameView, "displayNumber">,
|
||||||
|
): string | null {
|
||||||
|
if (!Number.isSafeInteger(game.displayNumber) || game.displayNumber <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return internalMatchGamePath(communityId, matchId, game.displayNumber);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createCompetitionSeriesHistory(
|
||||||
|
projection: HistoryProjection,
|
||||||
|
timeZone = "Asia/Seoul",
|
||||||
|
): CompetitionSeriesHistoryDay[] {
|
||||||
|
const gamesBySeriesId = new Map<string, CompetitionGameView[]>();
|
||||||
|
for (const game of projection.games) {
|
||||||
|
const seriesGames = gamesBySeriesId.get(game.seriesId) ?? [];
|
||||||
|
seriesGames.push(game);
|
||||||
|
gamesBySeriesId.set(game.seriesId, seriesGames);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows: CompetitionSeriesHistoryRow[] = [];
|
||||||
|
for (const series of projection.series) {
|
||||||
|
const games = [...(gamesBySeriesId.get(series.seriesId) ?? [])].sort(
|
||||||
|
compareGames,
|
||||||
|
);
|
||||||
|
|
||||||
|
switch (series.status) {
|
||||||
|
case "completed": {
|
||||||
|
if (hasInvalidStartedAt(games)) {
|
||||||
|
rows.push(missingRecordedGameTimeRow(series, games));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const gameStartedAt = earliestStartedAt(games);
|
||||||
|
if (games.length > 0 && !gameStartedAt) {
|
||||||
|
rows.push(missingRecordedGameTimeRow(series, games));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const occurredAt = gameStartedAt ?? series.outcome.completedAt;
|
||||||
|
rows.push({
|
||||||
|
series,
|
||||||
|
games,
|
||||||
|
occurredAt,
|
||||||
|
timestampSource: gameStartedAt ? "game-start" : "decision",
|
||||||
|
dateKey:
|
||||||
|
dateKeyInTimeZone(occurredAt, timeZone) ??
|
||||||
|
UNKNOWN_RECORD_DATE_KEY,
|
||||||
|
});
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "in-progress": {
|
||||||
|
if (hasInvalidStartedAt(games)) {
|
||||||
|
rows.push(missingRecordedGameTimeRow(series, games));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
const gameStartedAt = earliestStartedAt(games);
|
||||||
|
if (gameStartedAt) {
|
||||||
|
rows.push({
|
||||||
|
series,
|
||||||
|
games,
|
||||||
|
occurredAt: gameStartedAt,
|
||||||
|
timestampSource: "game-start",
|
||||||
|
dateKey:
|
||||||
|
dateKeyInTimeZone(gameStartedAt, timeZone) ??
|
||||||
|
UNKNOWN_RECORD_DATE_KEY,
|
||||||
|
});
|
||||||
|
} else if (games.length > 0) {
|
||||||
|
rows.push(missingRecordedGameTimeRow(series, games));
|
||||||
|
} else if (series.schedule) {
|
||||||
|
rows.push(scheduledRow(series, games));
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "ready":
|
||||||
|
case "waiting":
|
||||||
|
rows.push(scheduledRow(series, games));
|
||||||
|
break;
|
||||||
|
case "inactive":
|
||||||
|
if (series.schedule) rows.push(scheduledRow(series, games));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rows.sort(compareRows);
|
||||||
|
|
||||||
|
const days: CompetitionSeriesHistoryDay[] = [];
|
||||||
|
for (const row of rows) {
|
||||||
|
const currentDay = days.at(-1);
|
||||||
|
if (currentDay?.dateKey === row.dateKey) {
|
||||||
|
currentDay.rows.push(row);
|
||||||
|
} else {
|
||||||
|
days.push({ dateKey: row.dateKey, rows: [row] });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return days;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesHistoryStatusLabel(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
): string {
|
||||||
|
switch (series.status) {
|
||||||
|
case "inactive":
|
||||||
|
return "필요 시";
|
||||||
|
case "waiting":
|
||||||
|
case "ready":
|
||||||
|
return "예정";
|
||||||
|
case "in-progress":
|
||||||
|
return "진행 중";
|
||||||
|
case "completed":
|
||||||
|
return "최종";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesHistoryResultLabel(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
): string | null {
|
||||||
|
if (
|
||||||
|
series.status === "inactive" ||
|
||||||
|
series.status === "waiting" ||
|
||||||
|
series.status === "ready"
|
||||||
|
) {
|
||||||
|
return "VS";
|
||||||
|
}
|
||||||
|
if (series.status === "in-progress") return null;
|
||||||
|
switch (series.outcome.type) {
|
||||||
|
case "played":
|
||||||
|
return null;
|
||||||
|
case "draw":
|
||||||
|
return series.outcome.basis.type === "played"
|
||||||
|
? "무승부"
|
||||||
|
: "판정 무승부";
|
||||||
|
case "walkover":
|
||||||
|
return "부전승";
|
||||||
|
case "forfeit":
|
||||||
|
return "기권승";
|
||||||
|
case "administrative":
|
||||||
|
return "판정승";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesHistoryRecordLabel(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
gameCount: number,
|
||||||
|
expanded: boolean,
|
||||||
|
): string {
|
||||||
|
if (gameCount > 0) {
|
||||||
|
return expanded ? "게임 상세 접기" : `게임 상세 (${gameCount})`;
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
series.status === "inactive" ||
|
||||||
|
series.status === "waiting" ||
|
||||||
|
series.status === "ready"
|
||||||
|
) {
|
||||||
|
return "게임 전";
|
||||||
|
}
|
||||||
|
if (isGameLessDecision(series)) return "경기 없이 결정";
|
||||||
|
return "게임 기록 미등록";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function shouldDisplaySeriesHistoryScore(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
): boolean {
|
||||||
|
if (series.status === "in-progress") return true;
|
||||||
|
if (series.status !== "completed") return false;
|
||||||
|
if (series.outcome.type === "played") return true;
|
||||||
|
return (
|
||||||
|
series.outcome.type === "draw" && series.outcome.basis.type === "played"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesHistoryTimePresentation(
|
||||||
|
row: CompetitionSeriesHistoryRow,
|
||||||
|
): SeriesHistoryTimePresentation {
|
||||||
|
if (row.timestampSource === "scheduled") {
|
||||||
|
const schedule = row.series.schedule;
|
||||||
|
if (
|
||||||
|
schedule?.time &&
|
||||||
|
isValidLocalDate(schedule.date) &&
|
||||||
|
isValidLocalTime(schedule.time)
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
text: schedule.time,
|
||||||
|
dateTime: localScheduleDateTime(schedule),
|
||||||
|
screenReaderText: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (row.timestampSource === "unavailable") {
|
||||||
|
return {
|
||||||
|
text: "--:--",
|
||||||
|
dateTime: null,
|
||||||
|
screenReaderText: "시작 시간 미정",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = row.occurredAt
|
||||||
|
? formatCompetitionHistoryTime(row.occurredAt)
|
||||||
|
: null;
|
||||||
|
if (text && row.occurredAt) {
|
||||||
|
return {
|
||||||
|
text,
|
||||||
|
dateTime: row.occurredAt,
|
||||||
|
screenReaderText: null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const kind = row.timestampSource === "decision" ? "결정" : "시작";
|
||||||
|
return {
|
||||||
|
text: "—",
|
||||||
|
dateTime: null,
|
||||||
|
screenReaderText: `${kind} 시각 기록 없음`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSeriesGameDuration(
|
||||||
|
durationSeconds: number,
|
||||||
|
): string | null {
|
||||||
|
if (!Number.isFinite(durationSeconds) || durationSeconds <= 0) return null;
|
||||||
|
const totalSeconds = Math.floor(durationSeconds);
|
||||||
|
const hours = Math.floor(totalSeconds / 3_600);
|
||||||
|
const minutes = Math.floor((totalSeconds % 3_600) / 60);
|
||||||
|
const seconds = totalSeconds % 60;
|
||||||
|
if (hours > 0) {
|
||||||
|
return `${hours}:${padNumber(minutes)}:${padNumber(seconds)}`;
|
||||||
|
}
|
||||||
|
return `${minutes}:${padNumber(seconds)}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompetitionHistoryDate(dateKey: string): string {
|
||||||
|
if (dateKey === UNKNOWN_RECORD_DATE_KEY) return "기록 일시 미상";
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateKey);
|
||||||
|
if (!match) return "일정 미정";
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
const date = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
if (
|
||||||
|
date.getUTCFullYear() !== year ||
|
||||||
|
date.getUTCMonth() !== month - 1 ||
|
||||||
|
date.getUTCDate() !== day
|
||||||
|
) {
|
||||||
|
return "일정 미정";
|
||||||
|
}
|
||||||
|
return `${month}월 ${padNumber(day)}일 (${KOREAN_WEEKDAYS[date.getUTCDay()]})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isCompetitionHistoryCalendarDate(dateKey: string): boolean {
|
||||||
|
return isValidLocalDate(dateKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatCompetitionHistoryTime(
|
||||||
|
value: IsoDateTime,
|
||||||
|
timeZone = "Asia/Seoul",
|
||||||
|
): string | null {
|
||||||
|
const date = new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return null;
|
||||||
|
const parts = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone,
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
hourCycle: "h23",
|
||||||
|
}).formatToParts(date);
|
||||||
|
const part = (type: Intl.DateTimeFormatPartTypes) =>
|
||||||
|
parts.find((entry) => entry.type === type)?.value;
|
||||||
|
const hour = part("hour");
|
||||||
|
const minute = part("minute");
|
||||||
|
return hour && minute ? `${hour}:${minute}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function scheduledRow(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
games: CompetitionGameView[],
|
||||||
|
): CompetitionSeriesHistoryRow {
|
||||||
|
const schedule = series.schedule;
|
||||||
|
const dateKey =
|
||||||
|
schedule && isValidLocalDate(schedule.date)
|
||||||
|
? schedule.date
|
||||||
|
: UNKNOWN_DATE_KEY;
|
||||||
|
const occurredAt =
|
||||||
|
schedule?.time &&
|
||||||
|
isValidLocalTime(schedule.time) &&
|
||||||
|
dateKey !== UNKNOWN_DATE_KEY
|
||||||
|
? localScheduleDateTime(schedule)
|
||||||
|
: null;
|
||||||
|
return {
|
||||||
|
series,
|
||||||
|
games,
|
||||||
|
occurredAt,
|
||||||
|
timestampSource: occurredAt ? "scheduled" : "unavailable",
|
||||||
|
dateKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function missingRecordedGameTimeRow(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
games: CompetitionGameView[],
|
||||||
|
): CompetitionSeriesHistoryRow {
|
||||||
|
return {
|
||||||
|
series,
|
||||||
|
games,
|
||||||
|
occurredAt: null,
|
||||||
|
timestampSource: "game-start",
|
||||||
|
dateKey: UNKNOWN_RECORD_DATE_KEY,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function localScheduleDateTime(schedule: SeriesSchedule): IsoDateTime {
|
||||||
|
return `${schedule.date}T${schedule.time}:00+09:00`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareGames(
|
||||||
|
left: CompetitionGameView,
|
||||||
|
right: CompetitionGameView,
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
left.ordinal - right.ordinal ||
|
||||||
|
timestampValue(left.startedAt) - timestampValue(right.startedAt) ||
|
||||||
|
left.id.localeCompare(right.id)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareRows(
|
||||||
|
left: CompetitionSeriesHistoryRow,
|
||||||
|
right: CompetitionSeriesHistoryRow,
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
compareDateKeys(left.dateKey, right.dateKey) ||
|
||||||
|
rowTimeValue(left) - rowTimeValue(right) ||
|
||||||
|
left.series.stage.displayOrder - right.series.stage.displayOrder ||
|
||||||
|
left.series.seriesId.localeCompare(right.series.seriesId)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareDateKeys(left: string, right: string): number {
|
||||||
|
if (left === right) return 0;
|
||||||
|
const leftRank = dateKeyRank(left);
|
||||||
|
const rightRank = dateKeyRank(right);
|
||||||
|
if (leftRank !== rightRank) return leftRank - rightRank;
|
||||||
|
return left.localeCompare(right);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dateKeyRank(dateKey: string): number {
|
||||||
|
if (dateKey === UNKNOWN_RECORD_DATE_KEY) return 1;
|
||||||
|
if (dateKey === UNKNOWN_DATE_KEY) return 2;
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
function rowTimeValue(row: CompetitionSeriesHistoryRow): number {
|
||||||
|
if (!row.occurredAt) return Number.POSITIVE_INFINITY;
|
||||||
|
return timestampValue(row.occurredAt);
|
||||||
|
}
|
||||||
|
|
||||||
|
function earliestStartedAt(games: CompetitionGameView[]): IsoDateTime | null {
|
||||||
|
let earliest: { value: number; startedAt: IsoDateTime } | null = null;
|
||||||
|
for (const game of games) {
|
||||||
|
const value = timestampValue(game.startedAt);
|
||||||
|
if (!Number.isFinite(value)) continue;
|
||||||
|
if (!earliest || value < earliest.value) {
|
||||||
|
earliest = { value, startedAt: game.startedAt };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return earliest?.startedAt ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasInvalidStartedAt(games: CompetitionGameView[]): boolean {
|
||||||
|
return games.some(
|
||||||
|
(game) => !Number.isFinite(timestampValue(game.startedAt)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function dateKeyInTimeZone(
|
||||||
|
value: IsoDateTime,
|
||||||
|
timeZone: string,
|
||||||
|
): string | null {
|
||||||
|
const date = new Date(value);
|
||||||
|
if (Number.isNaN(date.getTime())) return null;
|
||||||
|
const parts = new Intl.DateTimeFormat("en-US", {
|
||||||
|
timeZone,
|
||||||
|
year: "numeric",
|
||||||
|
month: "2-digit",
|
||||||
|
day: "2-digit",
|
||||||
|
}).formatToParts(date);
|
||||||
|
const part = (type: Intl.DateTimeFormatPartTypes) =>
|
||||||
|
parts.find((entry) => entry.type === type)?.value;
|
||||||
|
const year = part("year");
|
||||||
|
const month = part("month");
|
||||||
|
const day = part("day");
|
||||||
|
return year && month && day ? `${year}-${month}-${day}` : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function timestampValue(value: IsoDateTime): number {
|
||||||
|
const timestamp = Date.parse(value);
|
||||||
|
return Number.isNaN(timestamp) ? Number.POSITIVE_INFINITY : timestamp;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isGameLessDecision(
|
||||||
|
series: CompetitionSeriesHistorySeries,
|
||||||
|
): boolean {
|
||||||
|
if (series.status !== "completed") return false;
|
||||||
|
if (series.outcome.type === "draw") {
|
||||||
|
return series.outcome.basis.type !== "played";
|
||||||
|
}
|
||||||
|
return series.outcome.type !== "played";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidLocalDate(value: string): boolean {
|
||||||
|
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
||||||
|
if (!match) return false;
|
||||||
|
const year = Number(match[1]);
|
||||||
|
const month = Number(match[2]);
|
||||||
|
const day = Number(match[3]);
|
||||||
|
const date = new Date(Date.UTC(year, month - 1, day));
|
||||||
|
return (
|
||||||
|
date.getUTCFullYear() === year &&
|
||||||
|
date.getUTCMonth() === month - 1 &&
|
||||||
|
date.getUTCDate() === day
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isValidLocalTime(value: string): boolean {
|
||||||
|
return /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function padNumber(value: number): string {
|
||||||
|
return value.toString().padStart(2, "0");
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
import type {
|
||||||
|
SeriesConnectorView,
|
||||||
|
SeriesId,
|
||||||
|
SeriesSlot,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import type { BracketConnectorKind } from "./double-elimination-bracket-layout";
|
||||||
|
|
||||||
|
export interface BracketFocusConnector {
|
||||||
|
fromSeriesId: SeriesId;
|
||||||
|
select: SeriesConnectorView["from"]["select"];
|
||||||
|
toSeriesId: SeriesId;
|
||||||
|
toSlot: SeriesSlot;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BracketFocusState {
|
||||||
|
seriesIds: ReadonlySet<SeriesId>;
|
||||||
|
connectorKeys: ReadonlySet<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HorizontalScrollMetrics {
|
||||||
|
scrollLeft: number;
|
||||||
|
scrollWidth: number;
|
||||||
|
clientWidth: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HorizontalOverflowCues {
|
||||||
|
showStart: boolean;
|
||||||
|
showEnd: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function bracketConnectorKey(connector: BracketFocusConnector): string {
|
||||||
|
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBracketConnectorColorClass(
|
||||||
|
kind: BracketConnectorKind,
|
||||||
|
focused = false,
|
||||||
|
): string {
|
||||||
|
if (kind === "winner") return "text-bracket-winner";
|
||||||
|
return focused ? "text-base-content" : "text-base-content/55";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getBracketFocusState(
|
||||||
|
connectors: readonly BracketFocusConnector[],
|
||||||
|
activeSeriesId: SeriesId | null,
|
||||||
|
): BracketFocusState {
|
||||||
|
if (!activeSeriesId) {
|
||||||
|
return {
|
||||||
|
seriesIds: new Set(),
|
||||||
|
connectorKeys: new Set(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const seriesIds = new Set<SeriesId>([activeSeriesId]);
|
||||||
|
const connectorKeys = new Set<string>();
|
||||||
|
for (const connector of connectors) {
|
||||||
|
if (
|
||||||
|
connector.fromSeriesId !== activeSeriesId &&
|
||||||
|
connector.toSeriesId !== activeSeriesId
|
||||||
|
) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seriesIds.add(connector.fromSeriesId);
|
||||||
|
seriesIds.add(connector.toSeriesId);
|
||||||
|
connectorKeys.add(bracketConnectorKey(connector));
|
||||||
|
}
|
||||||
|
|
||||||
|
return { seriesIds, connectorKeys };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getHorizontalOverflowCues({
|
||||||
|
scrollLeft,
|
||||||
|
scrollWidth,
|
||||||
|
clientWidth,
|
||||||
|
}: HorizontalScrollMetrics): HorizontalOverflowCues {
|
||||||
|
const threshold = 1;
|
||||||
|
const maxScrollLeft = Math.max(0, scrollWidth - clientWidth);
|
||||||
|
if (maxScrollLeft <= threshold) {
|
||||||
|
return { showStart: false, showEnd: false };
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
showStart: scrollLeft > threshold,
|
||||||
|
showEnd: scrollLeft < maxScrollLeft - threshold,
|
||||||
|
};
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,83 @@
|
|||||||
|
export type MatchDetailTabStatus =
|
||||||
|
| "recruiting"
|
||||||
|
| "team-built"
|
||||||
|
| "in-progress"
|
||||||
|
| "finished";
|
||||||
|
|
||||||
|
export type MatchDetailTabId =
|
||||||
|
| "bracket"
|
||||||
|
| "games"
|
||||||
|
| "teams"
|
||||||
|
| "info"
|
||||||
|
| "ops";
|
||||||
|
|
||||||
|
export type MatchDetailTab = {
|
||||||
|
id: MatchDetailTabId;
|
||||||
|
label: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type MatchDetailTabNavigationKey =
|
||||||
|
| "ArrowLeft"
|
||||||
|
| "ArrowRight"
|
||||||
|
| "Home"
|
||||||
|
| "End";
|
||||||
|
|
||||||
|
export const MATCH_DETAIL_TAB_QUERY_KEY = "tab";
|
||||||
|
|
||||||
|
const PUBLIC_MATCH_DETAIL_TABS: MatchDetailTab[] = [
|
||||||
|
{ id: "bracket", label: "대진표·순위" },
|
||||||
|
{ id: "games", label: "경기 일정·결과" },
|
||||||
|
{ id: "teams", label: "팀" },
|
||||||
|
{ id: "info", label: "안내" },
|
||||||
|
];
|
||||||
|
|
||||||
|
const OPERATIONS_TAB: MatchDetailTab = { id: "ops", label: "운영" };
|
||||||
|
|
||||||
|
export function createMatchDetailTabs({
|
||||||
|
status,
|
||||||
|
canManage,
|
||||||
|
}: {
|
||||||
|
status: MatchDetailTabStatus;
|
||||||
|
canManage: boolean;
|
||||||
|
}): MatchDetailTab[] {
|
||||||
|
if (status !== "in-progress" && status !== "finished") return [];
|
||||||
|
return canManage
|
||||||
|
? [...PUBLIC_MATCH_DETAIL_TABS, OPERATIONS_TAB]
|
||||||
|
: [...PUBLIC_MATCH_DETAIL_TABS];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveMatchDetailTab(
|
||||||
|
requestedTab: string | null | undefined,
|
||||||
|
availableTabs: readonly MatchDetailTab[],
|
||||||
|
): MatchDetailTabId | null {
|
||||||
|
return (
|
||||||
|
availableTabs.find((tab) => tab.id === requestedTab)?.id ??
|
||||||
|
availableTabs[0]?.id ??
|
||||||
|
null
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createMatchDetailTabSearchParams(
|
||||||
|
current: URLSearchParams,
|
||||||
|
nextTab: MatchDetailTabId,
|
||||||
|
): URLSearchParams {
|
||||||
|
const next = new URLSearchParams(current);
|
||||||
|
next.set(MATCH_DETAIL_TAB_QUERY_KEY, nextTab);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function moveMatchDetailTabFocus(
|
||||||
|
tabs: readonly MatchDetailTab[],
|
||||||
|
currentTab: MatchDetailTabId,
|
||||||
|
key: MatchDetailTabNavigationKey,
|
||||||
|
): MatchDetailTabId | null {
|
||||||
|
if (tabs.length === 0) return null;
|
||||||
|
if (key === "Home") return tabs[0].id;
|
||||||
|
if (key === "End") return tabs[tabs.length - 1].id;
|
||||||
|
|
||||||
|
const currentIndex = tabs.findIndex((tab) => tab.id === currentTab);
|
||||||
|
const safeIndex = currentIndex === -1 ? 0 : currentIndex;
|
||||||
|
const direction = key === "ArrowRight" ? 1 : -1;
|
||||||
|
const nextIndex = (safeIndex + direction + tabs.length) % tabs.length;
|
||||||
|
return tabs[nextIndex].id;
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export const SERIES_SCORE_CARD_GEOMETRY = {
|
||||||
|
borderWidth: 1,
|
||||||
|
height: 116,
|
||||||
|
headerHeight: 32,
|
||||||
|
entryHeight: 41,
|
||||||
|
} as const;
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
import type { SeriesProjection, TeamId } from "@lolympus/contracts";
|
||||||
|
|
||||||
|
export type SeriesScoreCardTone =
|
||||||
|
| "muted"
|
||||||
|
| "ready"
|
||||||
|
| "live"
|
||||||
|
| "completed"
|
||||||
|
| "adjudicated";
|
||||||
|
|
||||||
|
export interface SeriesScoreCardPresentation {
|
||||||
|
label: string;
|
||||||
|
tone: SeriesScoreCardTone;
|
||||||
|
showScore: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesScoreCardIdentity(
|
||||||
|
series: SeriesProjection,
|
||||||
|
displayLabel?: string,
|
||||||
|
): { label: string; code: string | undefined } {
|
||||||
|
const label = displayLabel ?? series.code ?? "Series";
|
||||||
|
return {
|
||||||
|
label,
|
||||||
|
code: series.code && series.code !== label ? series.code : undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesScoreCardPresentation(
|
||||||
|
series: SeriesProjection,
|
||||||
|
): SeriesScoreCardPresentation {
|
||||||
|
switch (series.status) {
|
||||||
|
case "inactive":
|
||||||
|
return { label: "비활성", tone: "muted", showScore: false };
|
||||||
|
case "waiting":
|
||||||
|
return { label: "대진 대기", tone: "muted", showScore: false };
|
||||||
|
case "ready":
|
||||||
|
return { label: "경기 가능", tone: "ready", showScore: false };
|
||||||
|
case "in-progress":
|
||||||
|
return { label: "진행 중", tone: "live", showScore: true };
|
||||||
|
case "completed":
|
||||||
|
return completedSeriesPresentation(series);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function formatSeriesScore(
|
||||||
|
series: SeriesProjection,
|
||||||
|
gameWins: number,
|
||||||
|
): string {
|
||||||
|
return getSeriesScoreCardPresentation(series).showScore
|
||||||
|
? String(gameWins)
|
||||||
|
: "—";
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getSeriesScoreCardAccessibleLabel(
|
||||||
|
series: SeriesProjection,
|
||||||
|
displayLabel: string | undefined,
|
||||||
|
teamById: ReadonlyMap<TeamId, { readonly name: string }>,
|
||||||
|
): string {
|
||||||
|
const identity = getSeriesScoreCardIdentity(series, displayLabel);
|
||||||
|
const presentation = getSeriesScoreCardPresentation(series);
|
||||||
|
const identityLabel = identity.code
|
||||||
|
? `${identity.label}, 코드 ${identity.code}`
|
||||||
|
: identity.label;
|
||||||
|
const entries = series.entries.map((entry) => {
|
||||||
|
const teamName = entry.teamId
|
||||||
|
? (teamById.get(entry.teamId)?.name ?? "알 수 없는 팀")
|
||||||
|
: "대기 중";
|
||||||
|
const score = formatSeriesScore(series, entry.gameWins);
|
||||||
|
const scoreLabel = score === "—" ? "점수 없음" : `${score}승`;
|
||||||
|
const winnerLabel = isSeriesEntryWinner(series, entry.teamId)
|
||||||
|
? ", 승리"
|
||||||
|
: "";
|
||||||
|
return `${entry.slot} ${teamName}, ${scoreLabel}${winnerLabel}.`;
|
||||||
|
});
|
||||||
|
|
||||||
|
return `${identityLabel}, ${presentation.label}. ${entries.join(" ")}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSeriesEntryWinner(
|
||||||
|
series: SeriesProjection,
|
||||||
|
teamId: TeamId | null,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
teamId !== null &&
|
||||||
|
series.status === "completed" &&
|
||||||
|
series.outcome.type !== "draw" &&
|
||||||
|
series.outcome.winnerTeamId === teamId
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedSeriesPresentation(
|
||||||
|
series: Extract<SeriesProjection, { status: "completed" }>,
|
||||||
|
): SeriesScoreCardPresentation {
|
||||||
|
switch (series.outcome.type) {
|
||||||
|
case "played":
|
||||||
|
return { label: "종료", tone: "completed", showScore: true };
|
||||||
|
case "draw": {
|
||||||
|
const played = series.outcome.basis.type === "played";
|
||||||
|
return {
|
||||||
|
label: "무승부",
|
||||||
|
tone: played ? "completed" : "adjudicated",
|
||||||
|
showScore: played,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case "walkover":
|
||||||
|
return { label: "부전승", tone: "adjudicated", showScore: false };
|
||||||
|
case "forfeit":
|
||||||
|
return { label: "기권승", tone: "adjudicated", showScore: false };
|
||||||
|
case "administrative":
|
||||||
|
return { label: "판정", tone: "adjudicated", showScore: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
+21
-9
@@ -8,6 +8,15 @@
|
|||||||
dark;
|
dark;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ── 브랜드 원색 ──
|
||||||
|
실제 색상값은 이곳에서만 관리하고, 화면에서는 아래의 의미 토큰을 사용한다. */
|
||||||
|
@theme static {
|
||||||
|
--color-brand-coral: oklch(0.708008 0.234375 24);
|
||||||
|
--color-brand-violet: oklch(0.481934 0.285938 285);
|
||||||
|
--color-brand-gold: oklch(0.853027 0.2 90);
|
||||||
|
--color-brand-cyan: oklch(70% 0.14523 200);
|
||||||
|
}
|
||||||
|
|
||||||
html {
|
html {
|
||||||
scrollbar-gutter: stable;
|
scrollbar-gutter: stable;
|
||||||
}
|
}
|
||||||
@@ -68,6 +77,7 @@ body {
|
|||||||
--color-content-subtle: var(--lts-content-subtle);
|
--color-content-subtle: var(--lts-content-subtle);
|
||||||
--color-content-muted: var(--lts-content-muted);
|
--color-content-muted: var(--lts-content-muted);
|
||||||
--color-content-disabled: var(--lts-content-disabled);
|
--color-content-disabled: var(--lts-content-disabled);
|
||||||
|
--color-bracket-winner: var(--color-brand-coral);
|
||||||
}
|
}
|
||||||
|
|
||||||
@layer utilities {
|
@layer utilities {
|
||||||
@@ -89,28 +99,24 @@ body {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ════════════════════════════════════════════════════════════
|
/* ── 라이트 테마 의미 색상 ── */
|
||||||
🎛️ 튜닝 패널 (실험용) — 값만 바꾸면 dev에서 즉시 반영(HMR).
|
|
||||||
확정되면 element로 전환한 뒤 이 블록을 통째로 제거할 것.
|
|
||||||
색은 oklch(밝기% 채도 색상) 형식.
|
|
||||||
════════════════════════════════════════════════════════════ */
|
|
||||||
[data-theme="light"] {
|
[data-theme="light"] {
|
||||||
/* ── 포인트 4색 (primary 주 액션 / secondary 강조 / accent 하이라이트 / info 정보·보조) ── */
|
/* ── 포인트 4색 (primary 주 액션 / secondary 강조 / accent 하이라이트 / info 정보·보조) ── */
|
||||||
|
|
||||||
/* 코랄레드 — primary 117곳 즉시 반영 */
|
/* 코랄레드 — primary 117곳 즉시 반영 */
|
||||||
--color-primary: oklch(0.708008 0.234375 24);
|
--color-primary: var(--color-brand-coral);
|
||||||
--color-primary-content: oklch(98% 0 0); /* 흰 글자 */
|
--color-primary-content: oklch(98% 0 0); /* 흰 글자 */
|
||||||
|
|
||||||
/* 바이올렛 — 버튼·뱃지·보더용 */
|
/* 바이올렛 — 버튼·뱃지·보더용 */
|
||||||
--color-secondary: oklch(0.481934 0.285938 285);
|
--color-secondary: var(--color-brand-violet);
|
||||||
--color-secondary-content: oklch(98% 0 0); /* 흰 글자 */
|
--color-secondary-content: oklch(98% 0 0); /* 흰 글자 */
|
||||||
|
|
||||||
/* 골드 — 배경·보더·아이콘만. 텍스트색(text-accent)으론 쓰지 말 것 */
|
/* 골드 — 배경·보더·아이콘만. 텍스트색(text-accent)으론 쓰지 말 것 */
|
||||||
--color-accent: oklch(0.853027 0.2 90);
|
--color-accent: var(--color-brand-gold);
|
||||||
--color-accent-content: oklch(22% 0.03 80); /* 어두운 글자 */
|
--color-accent-content: oklch(22% 0.03 80); /* 어두운 글자 */
|
||||||
|
|
||||||
/* 시안 — 정보·링크·보조 강조. L70이라 흰배경 텍스트는 약함 → 배경/보더 위주 */
|
/* 시안 — 정보·링크·보조 강조. L70이라 흰배경 텍스트는 약함 → 배경/보더 위주 */
|
||||||
--color-info: oklch(70% 0.14523 200);
|
--color-info: var(--color-brand-cyan);
|
||||||
--color-info-content: oklch(24% 0.03 215); /* 어두운 글자 */
|
--color-info-content: oklch(24% 0.03 215); /* 어두운 글자 */
|
||||||
|
|
||||||
/* 텍스트 기본 진하기 (회색 알파의 기준색). 낮출수록 전체가 진해짐 */
|
/* 텍스트 기본 진하기 (회색 알파의 기준색). 낮출수록 전체가 진해짐 */
|
||||||
@@ -122,6 +128,12 @@ body {
|
|||||||
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
|
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 경기 결과 기록의 링크 강조는 양쪽 테마에서 같은 브랜드 코랄을 쓴다.
|
||||||
|
전역 dark primary는 유지해 다른 화면의 기존 색상 의미를 바꾸지 않는다. */
|
||||||
|
.competition-series-history {
|
||||||
|
--color-primary: var(--color-brand-coral);
|
||||||
|
}
|
||||||
|
|
||||||
/* ── 실시간 입찰 피드백 모션 ──
|
/* ── 실시간 입찰 피드백 모션 ──
|
||||||
입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */
|
입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */
|
||||||
@keyframes lts-bid-pop {
|
@keyframes lts-bid-pop {
|
||||||
|
|||||||
@@ -0,0 +1,127 @@
|
|||||||
|
export type LaneCheckpointKey = "at10" | "at15";
|
||||||
|
|
||||||
|
export const DEFAULT_LANE_CHECKPOINT: LaneCheckpointKey = "at15";
|
||||||
|
|
||||||
|
export type NormalizedLanePosition =
|
||||||
|
| "TOP"
|
||||||
|
| "JUNGLE"
|
||||||
|
| "MIDDLE"
|
||||||
|
| "BOTTOM"
|
||||||
|
| "UTILITY";
|
||||||
|
|
||||||
|
export interface LaneCheckpoint {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LaneParticipantLike {
|
||||||
|
teamPosition: string;
|
||||||
|
checkpoints?: Partial<Record<LaneCheckpointKey, LaneCheckpoint>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LanePair<TParticipant extends LaneParticipantLike> {
|
||||||
|
position: NormalizedLanePosition;
|
||||||
|
blue: TParticipant | null;
|
||||||
|
red: TParticipant | null;
|
||||||
|
ambiguousBlue: boolean;
|
||||||
|
ambiguousRed: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LaneCheckpointComparison {
|
||||||
|
blue: LaneCheckpoint;
|
||||||
|
red: LaneCheckpoint;
|
||||||
|
goldDiff: number;
|
||||||
|
csDiff: number;
|
||||||
|
xpDiff: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const LANE_ORDER: readonly NormalizedLanePosition[] = [
|
||||||
|
"TOP",
|
||||||
|
"JUNGLE",
|
||||||
|
"MIDDLE",
|
||||||
|
"BOTTOM",
|
||||||
|
"UTILITY",
|
||||||
|
];
|
||||||
|
|
||||||
|
const LANE_ALIASES: Readonly<Record<string, NormalizedLanePosition>> = {
|
||||||
|
TOP: "TOP",
|
||||||
|
JUNGLE: "JUNGLE",
|
||||||
|
JGL: "JUNGLE",
|
||||||
|
MIDDLE: "MIDDLE",
|
||||||
|
MID: "MIDDLE",
|
||||||
|
BOTTOM: "BOTTOM",
|
||||||
|
ADC: "BOTTOM",
|
||||||
|
UTILITY: "UTILITY",
|
||||||
|
SUPPORT: "UTILITY",
|
||||||
|
SUP: "UTILITY",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function normalizeLanePosition(
|
||||||
|
value: string | undefined,
|
||||||
|
): NormalizedLanePosition | null {
|
||||||
|
if (!value) return null;
|
||||||
|
return LANE_ALIASES[value.toUpperCase()] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function pairLaneParticipants<TParticipant extends LaneParticipantLike>(
|
||||||
|
blueParticipants: readonly TParticipant[],
|
||||||
|
redParticipants: readonly TParticipant[],
|
||||||
|
): Array<LanePair<TParticipant>> {
|
||||||
|
const blueByPosition = groupByPosition(blueParticipants);
|
||||||
|
const redByPosition = groupByPosition(redParticipants);
|
||||||
|
|
||||||
|
return LANE_ORDER.flatMap((position) => {
|
||||||
|
const blue = blueByPosition.get(position) ?? [];
|
||||||
|
const red = redByPosition.get(position) ?? [];
|
||||||
|
if (blue.length === 0 && red.length === 0) return [];
|
||||||
|
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
position,
|
||||||
|
blue: blue.length === 1 ? blue[0] : null,
|
||||||
|
red: red.length === 1 ? red[0] : null,
|
||||||
|
ambiguousBlue: blue.length > 1,
|
||||||
|
ambiguousRed: red.length > 1,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolveCheckpointComparison<
|
||||||
|
TParticipant extends LaneParticipantLike,
|
||||||
|
>(
|
||||||
|
blueParticipant: TParticipant | null,
|
||||||
|
redParticipant: TParticipant | null,
|
||||||
|
checkpointKey: LaneCheckpointKey,
|
||||||
|
): LaneCheckpointComparison | null {
|
||||||
|
const blue = blueParticipant?.checkpoints?.[checkpointKey];
|
||||||
|
const red = redParticipant?.checkpoints?.[checkpointKey];
|
||||||
|
if (!blue || !red) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
blue,
|
||||||
|
red,
|
||||||
|
goldDiff: blue.gold - red.gold,
|
||||||
|
csDiff: blue.cs - red.cs,
|
||||||
|
xpDiff: blue.xp - red.xp,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function groupByPosition<TParticipant extends LaneParticipantLike>(
|
||||||
|
participants: readonly TParticipant[],
|
||||||
|
) {
|
||||||
|
const grouped = new Map<NormalizedLanePosition, TParticipant[]>();
|
||||||
|
for (const participant of participants) {
|
||||||
|
const position = normalizeLanePosition(participant.teamPosition);
|
||||||
|
if (!position) continue;
|
||||||
|
const values = grouped.get(position) ?? [];
|
||||||
|
values.push(participant);
|
||||||
|
grouped.set(position, values);
|
||||||
|
}
|
||||||
|
return grouped;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
export function selectInternalMatchGame<T extends { gameNumber: number }>(
|
||||||
|
games: readonly T[],
|
||||||
|
requestedGameNumber: number,
|
||||||
|
): T | null {
|
||||||
|
if (
|
||||||
|
!Number.isSafeInteger(requestedGameNumber) ||
|
||||||
|
requestedGameNumber <= 0
|
||||||
|
) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
games.find((game) => game.gameNumber === requestedGameNumber) ?? null
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
export type InternalMatchTeamSide = "blue" | "red";
|
||||||
|
|
||||||
|
export type InternalMatchObjectiveType =
|
||||||
|
| "dragon"
|
||||||
|
| "elderDragon"
|
||||||
|
| "baron"
|
||||||
|
| "riftHerald"
|
||||||
|
| "voidGrub";
|
||||||
|
|
||||||
|
export type InternalMatchTimelineEventType =
|
||||||
|
| InternalMatchObjectiveType
|
||||||
|
| "championKill"
|
||||||
|
| "tower"
|
||||||
|
| "inhibitor";
|
||||||
|
|
||||||
|
export type TimelineEventCategory = "objective" | "kill" | "structure";
|
||||||
|
export type TimelineEventFilter = "all" | TimelineEventCategory;
|
||||||
|
|
||||||
|
export interface InternalMatchTimelineEvent {
|
||||||
|
timestamp: number;
|
||||||
|
side?: InternalMatchTeamSide;
|
||||||
|
type: InternalMatchTimelineEventType;
|
||||||
|
killerParticipantId?: number;
|
||||||
|
victimParticipantId?: number;
|
||||||
|
assistingParticipantIds?: number[];
|
||||||
|
monsterSubType?: string;
|
||||||
|
towerType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InternalMatchObjectiveEvent {
|
||||||
|
timestamp: number;
|
||||||
|
side: InternalMatchTeamSide;
|
||||||
|
type: InternalMatchObjectiveType;
|
||||||
|
monsterSubType?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NormalizedObjectiveEvent extends InternalMatchObjectiveEvent {
|
||||||
|
label: string;
|
||||||
|
markerLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface NormalizedTimelineEvent extends InternalMatchTimelineEvent {
|
||||||
|
category: TimelineEventCategory;
|
||||||
|
label: string;
|
||||||
|
markerLabel: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DRAGON_TYPE_LABELS: Readonly<Record<string, string>> = {
|
||||||
|
AIR_DRAGON: "바람",
|
||||||
|
EARTH_DRAGON: "대지",
|
||||||
|
WATER_DRAGON: "바다",
|
||||||
|
FIRE_DRAGON: "화염",
|
||||||
|
HEXTECH_DRAGON: "마법공학",
|
||||||
|
CHEMTECH_DRAGON: "화학공학",
|
||||||
|
ELDER_DRAGON: "장로",
|
||||||
|
};
|
||||||
|
|
||||||
|
const OBJECTIVE_LABELS: Readonly<
|
||||||
|
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
|
||||||
|
> = {
|
||||||
|
elderDragon: "장로 드래곤",
|
||||||
|
baron: "바론",
|
||||||
|
riftHerald: "협곡의 전령",
|
||||||
|
voidGrub: "공허 유충",
|
||||||
|
};
|
||||||
|
|
||||||
|
const OBJECTIVE_MARKER_LABELS: Readonly<
|
||||||
|
Record<Exclude<InternalMatchObjectiveType, "dragon">, string>
|
||||||
|
> = {
|
||||||
|
elderDragon: "장로",
|
||||||
|
baron: "바론",
|
||||||
|
riftHerald: "전령",
|
||||||
|
voidGrub: "유충",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function dragonTypeLabel(
|
||||||
|
monsterSubType: string | undefined,
|
||||||
|
): string | null {
|
||||||
|
if (!monsterSubType) return null;
|
||||||
|
return DRAGON_TYPE_LABELS[monsterSubType] ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeObjectiveEvents(
|
||||||
|
events: readonly InternalMatchObjectiveEvent[],
|
||||||
|
): NormalizedObjectiveEvent[] {
|
||||||
|
return events
|
||||||
|
.map((event) => {
|
||||||
|
if (event.type === "dragon") {
|
||||||
|
const dragonLabel = dragonTypeLabel(event.monsterSubType);
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
|
||||||
|
markerLabel: dragonLabel ?? "용",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
label: OBJECTIVE_LABELS[event.type],
|
||||||
|
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.timestamp - right.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function normalizeTimelineEvents(
|
||||||
|
events: readonly InternalMatchTimelineEvent[],
|
||||||
|
): NormalizedTimelineEvent[] {
|
||||||
|
return events
|
||||||
|
.map((event): NormalizedTimelineEvent => {
|
||||||
|
if (event.type === "championKill") {
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
category: "kill",
|
||||||
|
label: "챔피언 처치",
|
||||||
|
markerLabel: "킬",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (event.type === "tower") {
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
category: "structure",
|
||||||
|
label: "포탑 파괴",
|
||||||
|
markerLabel: "포탑",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (event.type === "inhibitor") {
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
category: "structure",
|
||||||
|
label: "억제기 파괴",
|
||||||
|
markerLabel: "억제기",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (event.type === "dragon") {
|
||||||
|
const dragonLabel = dragonTypeLabel(event.monsterSubType);
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
category: "objective",
|
||||||
|
label: dragonLabel ? `${dragonLabel} 드래곤` : "드래곤",
|
||||||
|
markerLabel: dragonLabel ?? "용",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...event,
|
||||||
|
category: "objective",
|
||||||
|
label: OBJECTIVE_LABELS[event.type],
|
||||||
|
markerLabel: OBJECTIVE_MARKER_LABELS[event.type],
|
||||||
|
};
|
||||||
|
})
|
||||||
|
.sort((left, right) => left.timestamp - right.timestamp);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function selectTimelineEventSource<
|
||||||
|
TTimeline extends InternalMatchTimelineEvent,
|
||||||
|
TObjective extends InternalMatchObjectiveEvent,
|
||||||
|
>(
|
||||||
|
timelineEvents: readonly TTimeline[] | undefined,
|
||||||
|
objectiveEvents: readonly TObjective[],
|
||||||
|
): readonly (TTimeline | TObjective)[] {
|
||||||
|
return timelineEvents && timelineEvents.length > 0
|
||||||
|
? timelineEvents
|
||||||
|
: objectiveEvents;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function filterTimelineEvents<TEvent extends NormalizedTimelineEvent>(
|
||||||
|
events: readonly TEvent[],
|
||||||
|
filter: TimelineEventFilter,
|
||||||
|
): TEvent[] {
|
||||||
|
return filter === "all"
|
||||||
|
? [...events]
|
||||||
|
: events.filter((event) => event.category === filter);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function summarizeDragonTypes(
|
||||||
|
events: readonly NormalizedObjectiveEvent[],
|
||||||
|
side: InternalMatchTeamSide,
|
||||||
|
): Array<{ label: string; count: number }> {
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
|
||||||
|
for (const event of events) {
|
||||||
|
if (event.side !== side || event.type !== "dragon") continue;
|
||||||
|
const label = dragonTypeLabel(event.monsterSubType);
|
||||||
|
if (!label) continue;
|
||||||
|
counts.set(label, (counts.get(label) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...counts.entries()].map(([label, count]) => ({ label, count }));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectObjectiveMarkers<
|
||||||
|
TEvent extends NormalizedObjectiveEvent,
|
||||||
|
>(
|
||||||
|
events: readonly TEvent[],
|
||||||
|
points: readonly { timestamp: number; value: number }[],
|
||||||
|
): Array<TEvent & { value: number }> {
|
||||||
|
return projectTimelineEventMarkers(events, points);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function projectTimelineEventMarkers<TEvent extends { timestamp: number }>(
|
||||||
|
events: readonly TEvent[],
|
||||||
|
points: readonly { timestamp: number; value: number }[],
|
||||||
|
): Array<TEvent & { value: number }> {
|
||||||
|
if (points.length === 0) return [];
|
||||||
|
|
||||||
|
const orderedPoints = [...points].sort(
|
||||||
|
(left, right) => left.timestamp - right.timestamp,
|
||||||
|
);
|
||||||
|
|
||||||
|
return events.map((event) => {
|
||||||
|
let selected = orderedPoints[0];
|
||||||
|
for (const point of orderedPoints) {
|
||||||
|
if (point.timestamp > event.timestamp) break;
|
||||||
|
selected = point;
|
||||||
|
}
|
||||||
|
return { ...event, value: selected.value };
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -5,7 +5,13 @@ import type {
|
|||||||
MatchParticipantView,
|
MatchParticipantView,
|
||||||
} from "@lolympus/contracts";
|
} from "@lolympus/contracts";
|
||||||
import { ChevronLeft, Search, X } from "lucide-react";
|
import { ChevronLeft, Search, X } from "lucide-react";
|
||||||
import { Link, useLocation, useNavigate, useParams } from "react-router";
|
import {
|
||||||
|
Link,
|
||||||
|
useLocation,
|
||||||
|
useNavigate,
|
||||||
|
useParams,
|
||||||
|
useSearchParams,
|
||||||
|
} from "react-router";
|
||||||
import {
|
import {
|
||||||
useAuction,
|
useAuction,
|
||||||
useCollectTournamentResultByRiotMatch,
|
useCollectTournamentResultByRiotMatch,
|
||||||
@@ -28,6 +34,14 @@ import {
|
|||||||
import { RankBadge } from "../components/RankBadge";
|
import { RankBadge } from "../components/RankBadge";
|
||||||
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
|
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
|
||||||
import { CompetitionResults } from "../components/competition/CompetitionResults";
|
import { CompetitionResults } from "../components/competition/CompetitionResults";
|
||||||
|
import { MatchDetailTabBar } from "../components/competition/MatchDetailTabBar";
|
||||||
|
import { MATCH_PAGE_MAX_WIDTH_CLASS } from "../components/competition/competition-display-layout";
|
||||||
|
import {
|
||||||
|
createMatchDetailTabSearchParams,
|
||||||
|
createMatchDetailTabs,
|
||||||
|
resolveMatchDetailTab,
|
||||||
|
type MatchDetailTabId,
|
||||||
|
} from "../components/competition/match-detail-tabs";
|
||||||
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
|
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
|
||||||
import { apiFetch, ApiError } from "../lib/api";
|
import { apiFetch, ApiError } from "../lib/api";
|
||||||
import { profileIconUrl } from "../lib/ddragon";
|
import { profileIconUrl } from "../lib/ddragon";
|
||||||
@@ -1382,6 +1396,7 @@ function formatManualCollectSummary(
|
|||||||
export default function MatchDetailPage() {
|
export default function MatchDetailPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
const navigate = useNavigate();
|
const navigate = useNavigate();
|
||||||
|
const [searchParams, setSearchParams] = useSearchParams();
|
||||||
const queryClient = useQueryClient();
|
const queryClient = useQueryClient();
|
||||||
const authUserId = useAuthUserId();
|
const authUserId = useAuthUserId();
|
||||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||||
@@ -1400,6 +1415,10 @@ export default function MatchDetailPage() {
|
|||||||
meQuery.data?.memberships.find(
|
meQuery.data?.memberships.find(
|
||||||
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
||||||
)?.user ?? null;
|
)?.user ?? null;
|
||||||
|
const canManageAuction =
|
||||||
|
currentUser?.role === "owner" || currentUser?.role === "admin";
|
||||||
|
const isCheckingPermissions =
|
||||||
|
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
|
||||||
const canUseMemberActions = Boolean(currentUser || authUserId);
|
const canUseMemberActions = Boolean(currentUser || authUserId);
|
||||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||||
const [captainSelections, setCaptainSelections] = useState<
|
const [captainSelections, setCaptainSelections] = useState<
|
||||||
@@ -1701,6 +1720,33 @@ export default function MatchDetailPage() {
|
|||||||
return () => window.clearTimeout(timer);
|
return () => window.clearTimeout(timer);
|
||||||
}, [matchQuery.data?.participants]);
|
}, [matchQuery.data?.participants]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const status = matchQuery.data?.status;
|
||||||
|
const requestedTab = searchParams.get("tab");
|
||||||
|
if (
|
||||||
|
isCheckingPermissions ||
|
||||||
|
!requestedTab ||
|
||||||
|
(status !== "in-progress" && status !== "finished")
|
||||||
|
) return;
|
||||||
|
|
||||||
|
const resolvedTab = resolveMatchDetailTab(
|
||||||
|
requestedTab,
|
||||||
|
createMatchDetailTabs({ status, canManage: canManageAuction }),
|
||||||
|
);
|
||||||
|
if (!resolvedTab || resolvedTab === requestedTab) return;
|
||||||
|
|
||||||
|
setSearchParams(
|
||||||
|
createMatchDetailTabSearchParams(searchParams, resolvedTab),
|
||||||
|
{ replace: true, preventScrollReset: true },
|
||||||
|
);
|
||||||
|
}, [
|
||||||
|
canManageAuction,
|
||||||
|
isCheckingPermissions,
|
||||||
|
matchQuery.data?.status,
|
||||||
|
searchParams,
|
||||||
|
setSearchParams,
|
||||||
|
]);
|
||||||
|
|
||||||
if (!DEFAULT_COMMUNITY_ID) {
|
if (!DEFAULT_COMMUNITY_ID) {
|
||||||
return (
|
return (
|
||||||
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||||
@@ -1734,10 +1780,6 @@ export default function MatchDetailPage() {
|
|||||||
|
|
||||||
const match = mapApiMatchToMatchDetail(matchQuery.data);
|
const match = mapApiMatchToMatchDetail(matchQuery.data);
|
||||||
const si = statusBadge(match.status);
|
const si = statusBadge(match.status);
|
||||||
const canManageAuction =
|
|
||||||
currentUser?.role === "owner" || currentUser?.role === "admin";
|
|
||||||
const isCheckingPermissions =
|
|
||||||
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
|
|
||||||
const auctionNotStarted =
|
const auctionNotStarted =
|
||||||
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
|
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
|
||||||
const activeAuction = auctionNotStarted ? null : auctionQuery.data;
|
const activeAuction = auctionNotStarted ? null : auctionQuery.data;
|
||||||
@@ -1791,8 +1833,66 @@ export default function MatchDetailPage() {
|
|||||||
hasValidCaptainInitialPoints &&
|
hasValidCaptainInitialPoints &&
|
||||||
hasValidAuctionTimerSettings;
|
hasValidAuctionTimerSettings;
|
||||||
|
|
||||||
|
const matchTabs = createMatchDetailTabs({
|
||||||
|
status: match.status,
|
||||||
|
canManage: canManageAuction,
|
||||||
|
});
|
||||||
|
const activeMatchTab = resolveMatchDetailTab(
|
||||||
|
searchParams.get("tab"),
|
||||||
|
matchTabs,
|
||||||
|
);
|
||||||
|
const usesTabbedLayout = activeMatchTab !== null;
|
||||||
|
const showCompetitionState =
|
||||||
|
!usesTabbedLayout ||
|
||||||
|
activeMatchTab === "bracket" ||
|
||||||
|
activeMatchTab === "games" ||
|
||||||
|
activeMatchTab === "ops";
|
||||||
|
const showCompetitionResults =
|
||||||
|
!usesTabbedLayout ||
|
||||||
|
activeMatchTab === "bracket" ||
|
||||||
|
activeMatchTab === "games";
|
||||||
|
const showOperationsPanel =
|
||||||
|
!usesTabbedLayout || activeMatchTab === "ops";
|
||||||
|
const showTeamsPanel = !usesTabbedLayout || activeMatchTab === "teams";
|
||||||
|
const showInfoPanel = !usesTabbedLayout || activeMatchTab === "info";
|
||||||
|
const hasMatchInfo =
|
||||||
|
match.schedule.length > 0 ||
|
||||||
|
match.prizes.length > 0 ||
|
||||||
|
match.notices.length > 0;
|
||||||
|
const showSupportingLayout =
|
||||||
|
!usesTabbedLayout ||
|
||||||
|
showTeamsPanel ||
|
||||||
|
showInfoPanel ||
|
||||||
|
(showOperationsPanel && match.status === "in-progress");
|
||||||
|
const showEmptyOperationsState =
|
||||||
|
usesTabbedLayout &&
|
||||||
|
activeMatchTab === "ops" &&
|
||||||
|
match.status === "finished" &&
|
||||||
|
!competitionQuery.isLoading &&
|
||||||
|
!competitionQuery.error &&
|
||||||
|
(!competitionEnabled ||
|
||||||
|
competitionQuery.data?.projection.series.length === 0);
|
||||||
|
const supportingAsideClassName = usesTabbedLayout
|
||||||
|
? showInfoPanel
|
||||||
|
? "grid w-full gap-4 lg:grid-cols-2"
|
||||||
|
: showOperationsPanel
|
||||||
|
? "w-full space-y-4 lg:max-w-sm"
|
||||||
|
: "hidden"
|
||||||
|
: "w-full lg:w-64 shrink-0 space-y-4";
|
||||||
|
|
||||||
|
function handleMatchDetailTabChange(nextTab: MatchDetailTabId) {
|
||||||
|
setSearchParams(
|
||||||
|
createMatchDetailTabSearchParams(searchParams, nextTab),
|
||||||
|
{ preventScrollReset: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
|
<main
|
||||||
|
className={`mx-auto px-4 py-6 sm:px-6 ${
|
||||||
|
MATCH_PAGE_MAX_WIDTH_CLASS
|
||||||
|
}`}
|
||||||
|
>
|
||||||
<Link
|
<Link
|
||||||
to="/"
|
to="/"
|
||||||
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
|
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
|
||||||
@@ -1872,7 +1972,59 @@ export default function MatchDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{competitionQuery.isLoading && competitionEnabled && (
|
{usesTabbedLayout && activeMatchTab && (
|
||||||
|
<MatchDetailTabBar
|
||||||
|
tabs={matchTabs}
|
||||||
|
activeTab={activeMatchTab}
|
||||||
|
onChange={handleMatchDetailTabChange}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{usesTabbedLayout &&
|
||||||
|
activeMatchTab &&
|
||||||
|
matchTabs
|
||||||
|
.filter((tab) => tab.id !== activeMatchTab)
|
||||||
|
.map((tab) => (
|
||||||
|
<div
|
||||||
|
key={tab.id}
|
||||||
|
id={`match-detail-panel-${tab.id}`}
|
||||||
|
role="tabpanel"
|
||||||
|
aria-labelledby={`match-detail-tab-${tab.id}`}
|
||||||
|
hidden
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
|
||||||
|
<div
|
||||||
|
id={
|
||||||
|
usesTabbedLayout && activeMatchTab
|
||||||
|
? `match-detail-panel-${activeMatchTab}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
role={usesTabbedLayout ? "tabpanel" : undefined}
|
||||||
|
aria-labelledby={
|
||||||
|
usesTabbedLayout && activeMatchTab
|
||||||
|
? `match-detail-tab-${activeMatchTab}`
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
tabIndex={usesTabbedLayout ? 0 : undefined}
|
||||||
|
className={
|
||||||
|
usesTabbedLayout
|
||||||
|
? "scroll-mt-24 pt-5 focus-visible:outline-none"
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{usesTabbedLayout &&
|
||||||
|
showCompetitionResults &&
|
||||||
|
!competitionEnabled && (
|
||||||
|
<div
|
||||||
|
className="mb-6 border border-dashed border-base-content/15 bg-base-content/[0.02] px-4 py-5 text-sm text-base-content/45"
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
공식 경기 결과가 아직 준비되지 않았습니다.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showCompetitionState && competitionQuery.isLoading && competitionEnabled && (
|
||||||
<div
|
<div
|
||||||
className="mb-6 space-y-3 border border-base-content/10 p-4"
|
className="mb-6 space-y-3 border border-base-content/10 p-4"
|
||||||
aria-busy="true"
|
aria-busy="true"
|
||||||
@@ -1883,7 +2035,8 @@ export default function MatchDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{competitionQuery.error &&
|
{showCompetitionState &&
|
||||||
|
competitionQuery.error &&
|
||||||
!(
|
!(
|
||||||
competitionQuery.error instanceof ApiError &&
|
competitionQuery.error instanceof ApiError &&
|
||||||
competitionQuery.error.status === 404
|
competitionQuery.error.status === 404
|
||||||
@@ -1893,18 +2046,32 @@ export default function MatchDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{competitionEnabled && competitionQuery.data && (
|
{showCompetitionState && competitionEnabled && competitionQuery.data && (
|
||||||
<>
|
<>
|
||||||
<CompetitionResults competition={competitionQuery.data} />
|
{showCompetitionResults && (
|
||||||
<CompetitionAdminControls
|
<CompetitionResults
|
||||||
competition={competitionQuery.data}
|
competition={competitionQuery.data}
|
||||||
communityId={DEFAULT_COMMUNITY_ID}
|
view={
|
||||||
canManage={canManageAuction}
|
usesTabbedLayout
|
||||||
/>
|
? activeMatchTab === "games"
|
||||||
|
? "games"
|
||||||
|
: "bracket"
|
||||||
|
: "all"
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{showOperationsPanel && (
|
||||||
|
<CompetitionAdminControls
|
||||||
|
competition={competitionQuery.data}
|
||||||
|
communityId={DEFAULT_COMMUNITY_ID}
|
||||||
|
canManage={canManageAuction}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{competitionEnabled &&
|
{showCompetitionState &&
|
||||||
|
competitionEnabled &&
|
||||||
competitionQuery.error instanceof ApiError &&
|
competitionQuery.error instanceof ApiError &&
|
||||||
competitionQuery.error.status === 404 && (
|
competitionQuery.error.status === 404 && (
|
||||||
<div
|
<div
|
||||||
@@ -1915,8 +2082,23 @@ export default function MatchDetailPage() {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="flex flex-col lg:flex-row gap-5">
|
{showEmptyOperationsState && (
|
||||||
<div className="flex-1 min-w-0 space-y-4">
|
<div
|
||||||
|
className="mb-6 border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
운영할 공식 경기 데이터가 없습니다.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showSupportingLayout && (
|
||||||
|
<div
|
||||||
|
className={
|
||||||
|
usesTabbedLayout ? "block" : "flex flex-col lg:flex-row gap-5"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{showTeamsPanel && (
|
||||||
|
<div className="flex-1 min-w-0 space-y-4">
|
||||||
{match.status === "recruiting" ? (
|
{match.status === "recruiting" ? (
|
||||||
<>
|
<>
|
||||||
<ParticipantTable
|
<ParticipantTable
|
||||||
@@ -2293,6 +2475,16 @@ export default function MatchDetailPage() {
|
|||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
{usesTabbedLayout &&
|
||||||
|
showTeamsPanel &&
|
||||||
|
match.teams.length === 0 && (
|
||||||
|
<div
|
||||||
|
className="border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
등록된 팀이 없습니다.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
{match.teams.map((team) => (
|
{match.teams.map((team) => (
|
||||||
<TeamCard key={team.teamIndex} team={team} />
|
<TeamCard key={team.teamIndex} team={team} />
|
||||||
))}
|
))}
|
||||||
@@ -2308,10 +2500,20 @@ export default function MatchDetailPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="w-full lg:w-64 shrink-0 space-y-4">
|
<div className={supportingAsideClassName}>
|
||||||
{match.schedule.length > 0 && (
|
{usesTabbedLayout && showInfoPanel && !hasMatchInfo && (
|
||||||
|
<div
|
||||||
|
className="lg:col-span-2 border border-dashed border-base-content/15 px-4 py-8 text-center text-sm text-base-content/40"
|
||||||
|
role="status"
|
||||||
|
>
|
||||||
|
등록된 일정이나 안내가 없습니다.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showInfoPanel && match.schedule.length > 0 && (
|
||||||
<SideCard title="일정">
|
<SideCard title="일정">
|
||||||
<ul className="space-y-2">
|
<ul className="space-y-2">
|
||||||
{match.schedule.map((item, index) => (
|
{match.schedule.map((item, index) => (
|
||||||
@@ -2326,7 +2528,8 @@ export default function MatchDetailPage() {
|
|||||||
</SideCard>
|
</SideCard>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{canManageAuction &&
|
{showOperationsPanel &&
|
||||||
|
canManageAuction &&
|
||||||
(match.status === "team-built" ||
|
(match.status === "team-built" ||
|
||||||
match.status === "in-progress") && (
|
match.status === "in-progress") && (
|
||||||
<SideCard title="결과 수집">
|
<SideCard title="결과 수집">
|
||||||
@@ -2444,7 +2647,7 @@ export default function MatchDetailPage() {
|
|||||||
</SideCard>
|
</SideCard>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{match.prizes.length > 0 && (
|
{showInfoPanel && match.prizes.length > 0 && (
|
||||||
<SideCard title="상품">
|
<SideCard title="상품">
|
||||||
<ul className="space-y-1.5">
|
<ul className="space-y-1.5">
|
||||||
{match.prizes.map((prize, index) => (
|
{match.prizes.map((prize, index) => (
|
||||||
@@ -2460,7 +2663,7 @@ export default function MatchDetailPage() {
|
|||||||
</SideCard>
|
</SideCard>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{match.notices.length > 0 && (
|
{showInfoPanel && match.notices.length > 0 && (
|
||||||
<SideCard title="안내사항">
|
<SideCard title="안내사항">
|
||||||
<ul className="space-y-1.5">
|
<ul className="space-y-1.5">
|
||||||
{match.notices.map((notice, index) => (
|
{match.notices.map((notice, index) => (
|
||||||
@@ -2477,6 +2680,8 @@ export default function MatchDetailPage() {
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -5,6 +5,7 @@ import {
|
|||||||
AreaChart,
|
AreaChart,
|
||||||
CartesianGrid,
|
CartesianGrid,
|
||||||
Line,
|
Line,
|
||||||
|
ReferenceDot,
|
||||||
ReferenceLine,
|
ReferenceLine,
|
||||||
ResponsiveContainer,
|
ResponsiveContainer,
|
||||||
Tooltip,
|
Tooltip,
|
||||||
@@ -27,7 +28,18 @@ import {
|
|||||||
internalMatchDetailPath,
|
internalMatchDetailPath,
|
||||||
internalMatchGamePath,
|
internalMatchGamePath,
|
||||||
} from "../lib/internal-match-routes";
|
} from "../lib/internal-match-routes";
|
||||||
|
import { selectInternalMatchGame } from "../lib/internal-match-game-selection";
|
||||||
import { LANE_LABELS } from "../lib/riot-history";
|
import { LANE_LABELS } from "../lib/riot-history";
|
||||||
|
import {
|
||||||
|
filterTimelineEvents,
|
||||||
|
normalizeObjectiveEvents,
|
||||||
|
normalizeTimelineEvents,
|
||||||
|
projectTimelineEventMarkers,
|
||||||
|
selectTimelineEventSource,
|
||||||
|
summarizeDragonTypes,
|
||||||
|
type NormalizedTimelineEvent,
|
||||||
|
type TimelineEventFilter,
|
||||||
|
} from "../lib/internal-match-timeline";
|
||||||
import {
|
import {
|
||||||
InternalGameAnalysisPanel,
|
InternalGameAnalysisPanel,
|
||||||
InternalGameDetailTabBar,
|
InternalGameDetailTabBar,
|
||||||
@@ -58,6 +70,16 @@ const TIMELINE_METRICS: Array<{ id: TimelineMetric; label: string }> = [
|
|||||||
{ id: "xp", label: "경험치" },
|
{ id: "xp", label: "경험치" },
|
||||||
];
|
];
|
||||||
|
|
||||||
|
const TIMELINE_EVENT_FILTERS: Array<{
|
||||||
|
id: TimelineEventFilter;
|
||||||
|
label: string;
|
||||||
|
}> = [
|
||||||
|
{ id: "all", label: "전체" },
|
||||||
|
{ id: "objective", label: "오브젝트" },
|
||||||
|
{ id: "kill", label: "킬" },
|
||||||
|
{ id: "structure", label: "구조물" },
|
||||||
|
];
|
||||||
|
|
||||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
return typeof value === "object" && value !== null;
|
return typeof value === "object" && value !== null;
|
||||||
}
|
}
|
||||||
@@ -75,15 +97,15 @@ function resolveBackTarget(
|
|||||||
return {
|
return {
|
||||||
to: state.backTo,
|
to: state.backTo,
|
||||||
label:
|
label:
|
||||||
typeof state.backLabel === "string"
|
typeof state.backLabel === "string" && state.backLabel.trim().length > 0
|
||||||
? state.backLabel
|
? state.backLabel.trim()
|
||||||
: "돌아가기",
|
: "돌아가기",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
to: fallbackTo,
|
to: fallbackTo,
|
||||||
label: "경기 결과로 돌아가기",
|
label: "경기 기록으로 돌아가기",
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -142,6 +164,16 @@ function formatPercent(value: number) {
|
|||||||
return `${value}%`;
|
return `${value}%`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function formatDragonTypeSummary(
|
||||||
|
values: Array<{ label: string; count: number }>,
|
||||||
|
total: number,
|
||||||
|
) {
|
||||||
|
if (values.length === 0) return total > 0 ? "유형 정보 없음" : "-";
|
||||||
|
return values
|
||||||
|
.map(({ label, count }) => (count > 1 ? `${label}×${count}` : label))
|
||||||
|
.join(" · ");
|
||||||
|
}
|
||||||
|
|
||||||
function barWidth(value: number, max: number) {
|
function barWidth(value: number, max: number) {
|
||||||
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
|
return `${Math.max(0, Math.min(100, max > 0 ? (value / max) * 100 : 0))}%`;
|
||||||
}
|
}
|
||||||
@@ -411,13 +443,13 @@ function PlayerRow({
|
|||||||
{participant.assists}
|
{participant.assists}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-xs font-bold tabular-nums text-base-content/40">
|
<div className="text-xs font-bold tabular-nums text-base-content/40">
|
||||||
{formatKda(
|
KDA {formatKda(
|
||||||
participant.kills,
|
participant.kills,
|
||||||
participant.deaths,
|
participant.deaths,
|
||||||
participant.assists,
|
participant.assists,
|
||||||
)}
|
)}
|
||||||
<span className="ml-1 text-base-content/35">
|
<span className="ml-1 text-base-content/35">
|
||||||
({participant.killParticipation}%)
|
· KP {participant.killParticipation}%
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</td>
|
</td>
|
||||||
@@ -451,6 +483,12 @@ function PlayerRow({
|
|||||||
<span className="block text-base-content/35">
|
<span className="block text-base-content/35">
|
||||||
{participant.csPerMin}/m
|
{participant.csPerMin}/m
|
||||||
</span>
|
</span>
|
||||||
|
<span className="mt-1 block font-bold text-base-content/55">
|
||||||
|
{formatCompactNumber(participant.gold)}
|
||||||
|
<span className="ml-1 font-normal text-base-content/30">
|
||||||
|
{formatNumber(participant.gpm)} GPM
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="px-3 py-2.5">
|
<td className="px-3 py-2.5">
|
||||||
<ItemStrip participant={participant} manifest={manifest} />
|
<ItemStrip participant={participant} manifest={manifest} />
|
||||||
@@ -486,13 +524,13 @@ function PlayerCard({
|
|||||||
{participant.assists}
|
{participant.assists}
|
||||||
</div>
|
</div>
|
||||||
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
|
<div className="text-[11px] font-bold tabular-nums text-base-content/40">
|
||||||
{formatKda(
|
KDA {formatKda(
|
||||||
participant.kills,
|
participant.kills,
|
||||||
participant.deaths,
|
participant.deaths,
|
||||||
participant.assists,
|
participant.assists,
|
||||||
)}
|
)}
|
||||||
<span className="ml-1 text-base-content/35">
|
<span className="ml-1 text-base-content/35">
|
||||||
({participant.killParticipation}%)
|
· KP {participant.killParticipation}%
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -527,13 +565,19 @@ function PlayerCard({
|
|||||||
</div>
|
</div>
|
||||||
<div className="border border-base-content/8 px-2 py-1.5">
|
<div className="border border-base-content/8 px-2 py-1.5">
|
||||||
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
<div className="text-[10px] font-bold uppercase tracking-wider text-base-content/30">
|
||||||
CS
|
CS · 경제
|
||||||
</div>
|
</div>
|
||||||
<div className="mt-0.5 font-black text-base-content/70">
|
<div className="mt-0.5 font-black text-base-content/70">
|
||||||
{participant.cs}
|
{participant.cs}
|
||||||
<span className="ml-1 font-bold text-base-content/35">
|
<span className="ml-1 font-bold text-base-content/35">
|
||||||
{participant.csPerMin}/m
|
{participant.csPerMin}/m
|
||||||
</span>
|
</span>
|
||||||
|
<span className="mt-1 block text-base-content/60">
|
||||||
|
{formatCompactNumber(participant.gold)}
|
||||||
|
<span className="ml-1 font-bold text-base-content/35">
|
||||||
|
{formatNumber(participant.gpm)} GPM
|
||||||
|
</span>
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="border border-base-content/8 px-2 py-1.5">
|
<div className="border border-base-content/8 px-2 py-1.5">
|
||||||
@@ -701,11 +745,125 @@ function PostgameBreakdown({
|
|||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
<ObjectiveComparisonStrip selectedGame={selectedGame} />
|
||||||
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
|
<GoldComparisonStrip selectedGame={selectedGame} detail={detail} />
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function ObjectiveComparisonStrip({
|
||||||
|
selectedGame,
|
||||||
|
}: {
|
||||||
|
selectedGame: MatchGameDetail;
|
||||||
|
}) {
|
||||||
|
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||||
|
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||||
|
if (!blueTeam || !redTeam) return null;
|
||||||
|
|
||||||
|
const events = normalizeObjectiveEvents(selectedGame.objectiveEvents ?? []);
|
||||||
|
const blueDragonTypes = formatDragonTypeSummary(
|
||||||
|
summarizeDragonTypes(events, "blue"),
|
||||||
|
blueTeam.objectives.dragon,
|
||||||
|
);
|
||||||
|
const redDragonTypes = formatDragonTypeSummary(
|
||||||
|
summarizeDragonTypes(events, "red"),
|
||||||
|
redTeam.objectives.dragon,
|
||||||
|
);
|
||||||
|
const objectives = [
|
||||||
|
{
|
||||||
|
key: "tower",
|
||||||
|
label: "포탑",
|
||||||
|
blue: blueTeam.objectives.tower,
|
||||||
|
red: redTeam.objectives.tower,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "dragon",
|
||||||
|
label: "드래곤",
|
||||||
|
blue: blueTeam.objectives.dragon,
|
||||||
|
red: redTeam.objectives.dragon,
|
||||||
|
blueDetail: blueDragonTypes,
|
||||||
|
redDetail: redDragonTypes,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "inhibitor",
|
||||||
|
label: "억제기",
|
||||||
|
blue: blueTeam.objectives.inhibitor,
|
||||||
|
red: redTeam.objectives.inhibitor,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "baron",
|
||||||
|
label: "바론",
|
||||||
|
blue: blueTeam.objectives.baron,
|
||||||
|
red: redTeam.objectives.baron,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "riftHerald",
|
||||||
|
label: "전령",
|
||||||
|
blue: blueTeam.objectives.riftHerald,
|
||||||
|
red: redTeam.objectives.riftHerald,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "voidGrub",
|
||||||
|
label: "공허 유충",
|
||||||
|
blue: blueTeam.objectives.voidGrub,
|
||||||
|
red: redTeam.objectives.voidGrub,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "elderDragon",
|
||||||
|
label: "장로",
|
||||||
|
blue: blueTeam.objectives.elderDragon,
|
||||||
|
red: redTeam.objectives.elderDragon,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="border-t border-base-content/8 bg-base-content/[0.01]">
|
||||||
|
<h3 className="sr-only">오브젝트 비교</h3>
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-7">
|
||||||
|
{objectives.map((objective) => (
|
||||||
|
<div
|
||||||
|
key={objective.key}
|
||||||
|
className="border-b border-r border-base-content/8 px-3 py-2.5 last:border-r-0 lg:border-b-0"
|
||||||
|
aria-label={`${objective.label}: 블루 ${objective.blue}, 레드 ${objective.red}`}
|
||||||
|
>
|
||||||
|
<div className="grid grid-cols-[1fr_auto_1fr] items-center gap-2 text-xs tabular-nums">
|
||||||
|
<span
|
||||||
|
className={`text-right font-black ${
|
||||||
|
objective.blue > objective.red
|
||||||
|
? "text-blue-400"
|
||||||
|
: "text-base-content/50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{objective.blue}
|
||||||
|
</span>
|
||||||
|
<span className="text-[10px] font-bold text-base-content/35">
|
||||||
|
{objective.label}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`font-black ${
|
||||||
|
objective.red > objective.blue
|
||||||
|
? "text-red-400"
|
||||||
|
: "text-base-content/50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{objective.red}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{objective.key === "dragon" ? (
|
||||||
|
<div className="mt-1 grid grid-cols-2 gap-2 text-[9px] font-bold leading-tight">
|
||||||
|
<span className="text-right text-blue-400/70">
|
||||||
|
{objective.blueDetail}
|
||||||
|
</span>
|
||||||
|
<span className="text-red-400/70">{objective.redDetail}</span>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
function GoldComparisonStrip({
|
function GoldComparisonStrip({
|
||||||
selectedGame,
|
selectedGame,
|
||||||
detail,
|
detail,
|
||||||
@@ -848,14 +1006,74 @@ function TimelineTooltip({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function timelineEventKey(event: NormalizedTimelineEvent, index: number) {
|
||||||
|
return [
|
||||||
|
event.timestamp,
|
||||||
|
event.side ?? "unknown",
|
||||||
|
event.type,
|
||||||
|
event.killerParticipantId ?? "none",
|
||||||
|
event.victimParticipantId ?? "none",
|
||||||
|
index,
|
||||||
|
].join(":");
|
||||||
|
}
|
||||||
|
|
||||||
|
function timelineParticipantLabel(
|
||||||
|
participant: MatchGameParticipant | undefined,
|
||||||
|
manifest: ReturnType<typeof useDdragonManifest>["data"],
|
||||||
|
) {
|
||||||
|
if (!participant) return null;
|
||||||
|
const championName =
|
||||||
|
championDisplayName(manifest, participant.championId) ??
|
||||||
|
String(participant.championId);
|
||||||
|
return `${participant.summonerName} (${championName})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function timelineEventActors(
|
||||||
|
event: NormalizedTimelineEvent,
|
||||||
|
participantById: ReadonlyMap<number, MatchGameParticipant>,
|
||||||
|
manifest: ReturnType<typeof useDdragonManifest>["data"],
|
||||||
|
) {
|
||||||
|
const killer = timelineParticipantLabel(
|
||||||
|
event.killerParticipantId === undefined
|
||||||
|
? undefined
|
||||||
|
: participantById.get(event.killerParticipantId),
|
||||||
|
manifest,
|
||||||
|
);
|
||||||
|
const victim = timelineParticipantLabel(
|
||||||
|
event.victimParticipantId === undefined
|
||||||
|
? undefined
|
||||||
|
: participantById.get(event.victimParticipantId),
|
||||||
|
manifest,
|
||||||
|
);
|
||||||
|
const assistants = (event.assistingParticipantIds ?? [])
|
||||||
|
.map((participantId) =>
|
||||||
|
timelineParticipantLabel(participantById.get(participantId), manifest),
|
||||||
|
)
|
||||||
|
.filter((label): label is string => Boolean(label));
|
||||||
|
const assistLabel =
|
||||||
|
assistants.length > 0 ? ` · 도움 ${assistants.join(", ")}` : "";
|
||||||
|
|
||||||
|
if (event.type === "championKill") {
|
||||||
|
if (killer && victim) return `${killer} → ${victim}${assistLabel}`;
|
||||||
|
if (killer) return `${killer} 처치${assistLabel}`;
|
||||||
|
if (victim) return `${victim} 사망`;
|
||||||
|
}
|
||||||
|
if (killer) return `${killer} 기여${assistLabel}`;
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
function TimelineGraph({
|
function TimelineGraph({
|
||||||
selectedGame,
|
selectedGame,
|
||||||
detail,
|
detail,
|
||||||
|
manifest,
|
||||||
}: {
|
}: {
|
||||||
selectedGame: MatchGameDetail;
|
selectedGame: MatchGameDetail;
|
||||||
detail: ApiInternalMatchDetailResponse;
|
detail: ApiInternalMatchDetailResponse;
|
||||||
|
manifest: ReturnType<typeof useDdragonManifest>["data"];
|
||||||
}) {
|
}) {
|
||||||
const [metric, setMetric] = useState<TimelineMetric>("gold");
|
const [metric, setMetric] = useState<TimelineMetric>("gold");
|
||||||
|
const [eventFilter, setEventFilter] = useState<TimelineEventFilter>("all");
|
||||||
|
const [selectedEventKey, setSelectedEventKey] = useState<string | null>(null);
|
||||||
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
const blueTeam = selectedGame.teams.find((team) => team.side === "blue");
|
||||||
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
const redTeam = selectedGame.teams.find((team) => team.side === "red");
|
||||||
const blueTeamName = blueTeam
|
const blueTeamName = blueTeam
|
||||||
@@ -883,6 +1101,41 @@ function TimelineGraph({
|
|||||||
...chartData.map((point) => Math.abs(point.value)),
|
...chartData.map((point) => Math.abs(point.value)),
|
||||||
);
|
);
|
||||||
const finalPoint = chartData[chartData.length - 1];
|
const finalPoint = chartData[chartData.length - 1];
|
||||||
|
const timelineEvents = normalizeTimelineEvents(
|
||||||
|
selectTimelineEventSource(
|
||||||
|
selectedGame.timelineEvents,
|
||||||
|
selectedGame.objectiveEvents ?? [],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
const visibleEvents = filterTimelineEvents(timelineEvents, eventFilter);
|
||||||
|
const visibleEventEntries = visibleEvents.map((event) => {
|
||||||
|
const index = timelineEvents.indexOf(event);
|
||||||
|
return {
|
||||||
|
event,
|
||||||
|
key: timelineEventKey(event, index),
|
||||||
|
};
|
||||||
|
});
|
||||||
|
const selectedEvent = visibleEventEntries.find(
|
||||||
|
(entry) => entry.key === selectedEventKey,
|
||||||
|
);
|
||||||
|
const selectedTimestamp = selectedEvent?.event.timestamp ?? null;
|
||||||
|
const timelineMarkers = projectTimelineEventMarkers(
|
||||||
|
visibleEventEntries.map(({ event, key }) => ({ ...event, eventKey: key })),
|
||||||
|
chartData,
|
||||||
|
);
|
||||||
|
const participantById = new Map<number, MatchGameParticipant>();
|
||||||
|
for (const team of selectedGame.teams) {
|
||||||
|
for (const participant of team.participants) {
|
||||||
|
if (participant.participantId !== undefined) {
|
||||||
|
participantById.set(participant.participantId, participant);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const chartMaxTimestamp = Math.max(
|
||||||
|
selectedGame.gameDuration,
|
||||||
|
finalPoint?.timestamp ?? 0,
|
||||||
|
timelineEvents[timelineEvents.length - 1]?.timestamp ?? 0,
|
||||||
|
);
|
||||||
const finalLeader =
|
const finalLeader =
|
||||||
finalPoint?.leaderSide === "blue"
|
finalPoint?.leaderSide === "blue"
|
||||||
? blueTeamName
|
? blueTeamName
|
||||||
@@ -901,11 +1154,16 @@ function TimelineGraph({
|
|||||||
: "타임라인 대기"}
|
: "타임라인 대기"}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto">
|
<div
|
||||||
|
className="flex w-full border border-base-content/10 bg-base-content/[0.02] sm:w-auto"
|
||||||
|
role="group"
|
||||||
|
aria-label="경기 흐름 지표"
|
||||||
|
>
|
||||||
{TIMELINE_METRICS.map((item) => (
|
{TIMELINE_METRICS.map((item) => (
|
||||||
<button
|
<button
|
||||||
key={item.id}
|
key={item.id}
|
||||||
type="button"
|
type="button"
|
||||||
|
aria-pressed={metric === item.id}
|
||||||
onClick={() => setMetric(item.id)}
|
onClick={() => setMetric(item.id)}
|
||||||
className={`min-w-24 flex-1 border-r border-base-content/8 px-4 py-2 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
|
className={`min-w-24 flex-1 border-r border-base-content/8 px-4 py-2 text-xs font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
|
||||||
metric === item.id
|
metric === item.id
|
||||||
@@ -921,7 +1179,11 @@ function TimelineGraph({
|
|||||||
{chartData.length > 0 ? (
|
{chartData.length > 0 ? (
|
||||||
<div className="px-2 py-4 sm:px-4">
|
<div className="px-2 py-4 sm:px-4">
|
||||||
<div className="h-[260px] min-w-0 w-full">
|
<div className="h-[260px] min-w-0 w-full">
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
<ResponsiveContainer
|
||||||
|
width="100%"
|
||||||
|
height="100%"
|
||||||
|
initialDimension={{ width: 800, height: 260 }}
|
||||||
|
>
|
||||||
<AreaChart
|
<AreaChart
|
||||||
data={chartData}
|
data={chartData}
|
||||||
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
|
margin={{ top: 12, right: 12, bottom: 0, left: 0 }}
|
||||||
@@ -933,6 +1195,8 @@ function TimelineGraph({
|
|||||||
/>
|
/>
|
||||||
<XAxis
|
<XAxis
|
||||||
dataKey="timestamp"
|
dataKey="timestamp"
|
||||||
|
type="number"
|
||||||
|
domain={[0, chartMaxTimestamp]}
|
||||||
minTickGap={28}
|
minTickGap={28}
|
||||||
tickFormatter={(value) =>
|
tickFormatter={(value) =>
|
||||||
`${Math.round(Number(value) / 60)}분`
|
`${Math.round(Number(value) / 60)}분`
|
||||||
@@ -965,6 +1229,14 @@ function TimelineGraph({
|
|||||||
stroke="currentColor"
|
stroke="currentColor"
|
||||||
strokeOpacity={0.25}
|
strokeOpacity={0.25}
|
||||||
/>
|
/>
|
||||||
|
{selectedTimestamp !== null ? (
|
||||||
|
<ReferenceLine
|
||||||
|
x={selectedTimestamp}
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeDasharray="3 3"
|
||||||
|
strokeOpacity={0.35}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
<Area
|
<Area
|
||||||
type="monotone"
|
type="monotone"
|
||||||
dataKey="positive"
|
dataKey="positive"
|
||||||
@@ -994,6 +1266,44 @@ function TimelineGraph({
|
|||||||
}}
|
}}
|
||||||
isAnimationActive={false}
|
isAnimationActive={false}
|
||||||
/>
|
/>
|
||||||
|
{timelineMarkers.map((event) => {
|
||||||
|
const selected = event.eventKey === selectedEventKey;
|
||||||
|
const markerRadius =
|
||||||
|
event.category === "objective"
|
||||||
|
? 4
|
||||||
|
: event.category === "structure"
|
||||||
|
? 3.5
|
||||||
|
: 2.5;
|
||||||
|
return (
|
||||||
|
<ReferenceDot
|
||||||
|
key={event.eventKey}
|
||||||
|
x={event.timestamp}
|
||||||
|
y={event.value}
|
||||||
|
r={selected ? 5.5 : markerRadius}
|
||||||
|
fill={
|
||||||
|
event.side === "blue"
|
||||||
|
? "#3b82f6"
|
||||||
|
: event.side === "red"
|
||||||
|
? "#ef4444"
|
||||||
|
: "currentColor"
|
||||||
|
}
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth={selected ? 2 : 1}
|
||||||
|
ifOverflow="extendDomain"
|
||||||
|
label={
|
||||||
|
selected
|
||||||
|
? {
|
||||||
|
value: event.markerLabel,
|
||||||
|
position: "top",
|
||||||
|
fontSize: 10,
|
||||||
|
fontWeight: 800,
|
||||||
|
fill: "currentColor",
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</AreaChart>
|
</AreaChart>
|
||||||
</ResponsiveContainer>
|
</ResponsiveContainer>
|
||||||
</div>
|
</div>
|
||||||
@@ -1008,6 +1318,106 @@ function TimelineGraph({
|
|||||||
타임라인 데이터가 아직 없습니다
|
타임라인 데이터가 아직 없습니다
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{timelineEvents.length > 0 ? (
|
||||||
|
<div className="border-t border-base-content/8 px-4 py-3">
|
||||||
|
<div className="flex flex-wrap items-baseline justify-between gap-2">
|
||||||
|
<h3 className="text-xs font-black text-base-content">주요 사건</h3>
|
||||||
|
<p className="text-[11px] font-bold text-base-content/30">
|
||||||
|
항목을 선택하면 그래프의 해당 시점을 강조합니다
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="mt-3 flex w-full overflow-x-auto border border-base-content/10 bg-base-content/[0.02] sm:w-fit"
|
||||||
|
role="group"
|
||||||
|
aria-label="사건 유형 필터"
|
||||||
|
>
|
||||||
|
{TIMELINE_EVENT_FILTERS.map((filter) => (
|
||||||
|
<button
|
||||||
|
key={filter.id}
|
||||||
|
type="button"
|
||||||
|
aria-pressed={eventFilter === filter.id}
|
||||||
|
onClick={() => setEventFilter(filter.id)}
|
||||||
|
className={`min-w-20 flex-1 border-r border-base-content/8 px-3 py-2 text-[11px] font-black transition-colors last:border-r-0 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary sm:flex-none ${
|
||||||
|
eventFilter === filter.id
|
||||||
|
? "bg-primary text-primary-content"
|
||||||
|
: "text-base-content/45 hover:bg-base-content/[0.03] hover:text-base-content"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{filter.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<ul
|
||||||
|
className="m-0 mt-3 grid max-h-64 list-none gap-1.5 overflow-y-auto p-0 sm:grid-cols-2 lg:grid-cols-3"
|
||||||
|
aria-label="시간순 주요 사건"
|
||||||
|
>
|
||||||
|
{visibleEventEntries.map(({ event, key }) => {
|
||||||
|
const selected = key === selectedEventKey;
|
||||||
|
const teamName =
|
||||||
|
event.side === "blue"
|
||||||
|
? blueTeamName
|
||||||
|
: event.side === "red"
|
||||||
|
? redTeamName
|
||||||
|
: null;
|
||||||
|
const actorLabel = timelineEventActors(
|
||||||
|
event,
|
||||||
|
participantById,
|
||||||
|
manifest,
|
||||||
|
);
|
||||||
|
return (
|
||||||
|
<li key={key} className="min-w-0">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-pressed={selected}
|
||||||
|
onClick={() => setSelectedEventKey(selected ? null : key)}
|
||||||
|
className={`grid h-full w-full grid-cols-[3.25rem_3.25rem_minmax(0,1fr)] items-start gap-2 border px-2.5 py-2 text-left text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary ${
|
||||||
|
selected
|
||||||
|
? "border-primary bg-primary/8"
|
||||||
|
: "border-base-content/8 hover:bg-base-content/[0.03]"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<span className="font-mono font-black tabular-nums text-base-content/55">
|
||||||
|
{formatDuration(event.timestamp)}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
className={`text-[10px] font-black uppercase tracking-wider ${
|
||||||
|
event.side === "blue"
|
||||||
|
? "text-blue-400"
|
||||||
|
: event.side === "red"
|
||||||
|
? "text-red-400"
|
||||||
|
: "text-base-content/35"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{event.side ? sideLabel(event.side) : "-"}
|
||||||
|
</span>
|
||||||
|
<span className="min-w-0">
|
||||||
|
<span className="block truncate font-bold text-base-content/75">
|
||||||
|
{teamName ? (
|
||||||
|
<span className="sr-only">{teamName} </span>
|
||||||
|
) : null}
|
||||||
|
{event.label}
|
||||||
|
</span>
|
||||||
|
{actorLabel ? (
|
||||||
|
<span
|
||||||
|
className="mt-0.5 block truncate text-[10px] font-bold text-base-content/35"
|
||||||
|
title={actorLabel}
|
||||||
|
>
|
||||||
|
{actorLabel}
|
||||||
|
</span>
|
||||||
|
) : null}
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
{visibleEventEntries.length === 0 ? (
|
||||||
|
<p className="py-6 text-center text-xs font-bold text-base-content/35">
|
||||||
|
이 유형의 사건이 없습니다
|
||||||
|
</p>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1045,7 +1455,7 @@ function TeamTable({
|
|||||||
<th className="w-[120px] px-3 py-2.5 text-center">가한 피해량</th>
|
<th className="w-[120px] px-3 py-2.5 text-center">가한 피해량</th>
|
||||||
<th className="w-[120px] px-3 py-2.5 text-center">받은 피해량</th>
|
<th className="w-[120px] px-3 py-2.5 text-center">받은 피해량</th>
|
||||||
<th className="w-[80px] px-3 py-2.5 text-center">시야</th>
|
<th className="w-[80px] px-3 py-2.5 text-center">시야</th>
|
||||||
<th className="w-[76px] px-3 py-2.5 text-center">CS</th>
|
<th className="w-[96px] px-3 py-2.5 text-center">CS · 경제</th>
|
||||||
<th className="w-[260px] px-3 py-2.5">아이템</th>
|
<th className="w-[260px] px-3 py-2.5">아이템</th>
|
||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</thead>
|
||||||
@@ -1272,14 +1682,29 @@ export default function MatchGameDetailPage() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
const selectedGame =
|
const selectedGame = selectInternalMatchGame(
|
||||||
detail.games.find((game) => game.gameNumber === requestedGameNumber) ??
|
detail.games,
|
||||||
detail.games[0];
|
requestedGameNumber,
|
||||||
|
);
|
||||||
|
|
||||||
if (!selectedGame) {
|
if (!selectedGame) {
|
||||||
|
const hasRecordedGames = detail.games.length > 0;
|
||||||
|
const requestedGameLabel =
|
||||||
|
Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0
|
||||||
|
? `${requestedGameNumber}경기`
|
||||||
|
: "요청한 경기";
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto max-w-6xl px-4 py-20 text-center">
|
<main className="mx-auto max-w-6xl px-4 py-20 text-center">
|
||||||
<h1 className="text-lg font-bold">수집된 세트 기록이 없습니다</h1>
|
<h1 className="text-lg font-bold">
|
||||||
|
{hasRecordedGames
|
||||||
|
? "해당 경기 기록을 찾을 수 없습니다"
|
||||||
|
: "수집된 세트 기록이 없습니다"}
|
||||||
|
</h1>
|
||||||
|
{hasRecordedGames && (
|
||||||
|
<p className="mt-2 text-sm text-content-muted">
|
||||||
|
{requestedGameLabel}가 현재 상세 기록에 없습니다.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
<Link
|
<Link
|
||||||
to={backTarget.to}
|
to={backTarget.to}
|
||||||
className="btn btn-ghost btn-sm mt-4"
|
className="btn btn-ghost btn-sm mt-4"
|
||||||
@@ -1306,6 +1731,13 @@ export default function MatchGameDetailPage() {
|
|||||||
manifest={ddragon}
|
manifest={ddragon}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<TimelineGraph
|
||||||
|
key={selectedGame.riotMatchId}
|
||||||
|
selectedGame={selectedGame}
|
||||||
|
detail={detail}
|
||||||
|
manifest={ddragon}
|
||||||
|
/>
|
||||||
|
|
||||||
<div className="mt-5 space-y-4">
|
<div className="mt-5 space-y-4">
|
||||||
<InternalGameDetailTabBar
|
<InternalGameDetailTabBar
|
||||||
activeTab={activeTab}
|
activeTab={activeTab}
|
||||||
@@ -1325,8 +1757,6 @@ export default function MatchGameDetailPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<TimelineGraph selectedGame={selectedGame} detail={detail} />
|
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -1,24 +1,46 @@
|
|||||||
import { useEffect, useRef, useState } from "react";
|
import type {
|
||||||
import { Link, useParams } from "react-router";
|
CompetitionDetailResponse,
|
||||||
|
SeriesProjection,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { ArrowLeft, ChevronDown, UsersRound } from "lucide-react";
|
||||||
|
import { useEffect, useRef } from "react";
|
||||||
|
import { Link, useParams, useSearchParams } from "react-router";
|
||||||
import { useCompetition, useTeamCompetition } from "../api/hooks";
|
import { useCompetition, useTeamCompetition } from "../api/hooks";
|
||||||
import { SeriesScoreCard } from "../components/competition/SeriesScoreCard";
|
import { TeamSeriesCard } from "../components/competition/TeamSeriesCard";
|
||||||
|
import { TeamTournamentCodes } from "../components/competition/TeamTournamentCodes";
|
||||||
import { DEFAULT_COMMUNITY_ID } from "../config";
|
import { DEFAULT_COMMUNITY_ID } from "../config";
|
||||||
|
import { positionLabel } from "../lib/league";
|
||||||
import {
|
import {
|
||||||
getTeamProgressErrorContent,
|
getTeamProgressErrorContent,
|
||||||
isConsistentTeamProgressSnapshot,
|
isConsistentTeamProgressSnapshot,
|
||||||
|
shouldOfferTeamSelection,
|
||||||
type TeamProgressErrorContent,
|
type TeamProgressErrorContent,
|
||||||
} from "./match-team-progress-state";
|
} from "./match-team-progress-state";
|
||||||
|
import {
|
||||||
|
createTeamSeriesGroups,
|
||||||
|
getTeamSeriesDisplayLabel,
|
||||||
|
sortCompletedTeamSeries,
|
||||||
|
sortTeamMembersForRoster,
|
||||||
|
} from "./match-team-progress-view";
|
||||||
|
|
||||||
export default function MatchTeamProgressPage() {
|
export default function MatchTeamProgressPage() {
|
||||||
const { id } = useParams();
|
const { id } = useParams();
|
||||||
|
const [searchParams] = useSearchParams();
|
||||||
|
const selectedTeamId = searchParams.get("teamId") ?? undefined;
|
||||||
|
const isSelectingTeam = !selectedTeamId && searchParams.get("select") === "1";
|
||||||
const competitionQuery = useCompetition(id, DEFAULT_COMMUNITY_ID);
|
const competitionQuery = useCompetition(id, DEFAULT_COMMUNITY_ID);
|
||||||
const teamQuery = useTeamCompetition(id, DEFAULT_COMMUNITY_ID);
|
const teamQuery = useTeamCompetition(
|
||||||
|
id,
|
||||||
|
DEFAULT_COMMUNITY_ID,
|
||||||
|
selectedTeamId,
|
||||||
|
);
|
||||||
const refetchCompetition = competitionQuery.refetch;
|
const refetchCompetition = competitionQuery.refetch;
|
||||||
const refetchTeam = teamQuery.refetch;
|
const refetchTeam = teamQuery.refetch;
|
||||||
const [copiedSlotId, setCopiedSlotId] = useState<string | null>(null);
|
|
||||||
const lastAutoRefetchedMismatchRef = useRef<string | null>(null);
|
const lastAutoRefetchedMismatchRef = useRef<string | null>(null);
|
||||||
|
const contentHeadingRef = useRef<HTMLHeadingElement>(null);
|
||||||
const competition = competitionQuery.data;
|
const competition = competitionQuery.data;
|
||||||
const teamView = teamQuery.data;
|
const teamView = teamQuery.data;
|
||||||
|
const teamViewId = teamView?.teamId;
|
||||||
const hasQueryError = Boolean(
|
const hasQueryError = Boolean(
|
||||||
competitionQuery.error || teamQuery.error,
|
competitionQuery.error || teamQuery.error,
|
||||||
);
|
);
|
||||||
@@ -57,17 +79,35 @@ export default function MatchTeamProgressPage() {
|
|||||||
revisionMismatchKey,
|
revisionMismatchKey,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (isSelectingTeam || !teamViewId || !revisionsMatch) return;
|
||||||
|
contentHeadingRef.current?.focus({ preventScroll: true });
|
||||||
|
}, [isSelectingTeam, revisionsMatch, teamViewId]);
|
||||||
|
|
||||||
function retryBoth() {
|
function retryBoth() {
|
||||||
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
|
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
|
||||||
() => undefined,
|
() => undefined,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (isSelectingTeam && competition) {
|
||||||
|
return <TeamSelectionState competition={competition} matchId={id} />;
|
||||||
|
}
|
||||||
|
|
||||||
if (competitionQuery.isLoading || teamQuery.isLoading) {
|
if (competitionQuery.isLoading || teamQuery.isLoading) {
|
||||||
return <TeamProgressLoadingState />;
|
return <TeamProgressLoadingState />;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasQueryError) {
|
if (hasQueryError) {
|
||||||
|
// The caller could not be resolved to a team from their identity — let them
|
||||||
|
// name the team instead, so the page stays usable without signing in.
|
||||||
|
if (
|
||||||
|
competition &&
|
||||||
|
!competitionQuery.error &&
|
||||||
|
shouldOfferTeamSelection([teamQuery.error], selectedTeamId)
|
||||||
|
) {
|
||||||
|
return <TeamSelectionState competition={competition} matchId={id} />;
|
||||||
|
}
|
||||||
return (
|
return (
|
||||||
<TeamProgressProblemState
|
<TeamProgressProblemState
|
||||||
content={getTeamProgressErrorContent(
|
content={getTeamProgressErrorContent(
|
||||||
@@ -114,167 +154,245 @@ export default function MatchTeamProgressPage() {
|
|||||||
competition.teams.map((team) => [team.teamId, team]),
|
competition.teams.map((team) => [team.teamId, team]),
|
||||||
);
|
);
|
||||||
const team = teamById.get(teamView.teamId);
|
const team = teamById.get(teamView.teamId);
|
||||||
const completedSeries = competition.projection.series.filter(
|
const activeSeriesGroups = createTeamSeriesGroups(
|
||||||
(series) =>
|
teamView.activeSeries,
|
||||||
series.status === "completed" &&
|
teamView.tournamentCodes,
|
||||||
series.entries.some((entry) => entry.teamId === teamView.teamId),
|
|
||||||
);
|
);
|
||||||
|
const completedSeries = sortCompletedTeamSeries(
|
||||||
async function copyCode(gameSlotId: string, code: string | null) {
|
competition.projection.series.filter(
|
||||||
if (!code) return;
|
(
|
||||||
try {
|
series,
|
||||||
await navigator.clipboard.writeText(code);
|
): series is Extract<SeriesProjection, { status: "completed" }> =>
|
||||||
setCopiedSlotId(gameSlotId);
|
series.status === "completed" &&
|
||||||
window.setTimeout(() => setCopiedSlotId(null), 1500);
|
series.entries.some((entry) => entry.teamId === teamView.teamId),
|
||||||
} catch {
|
),
|
||||||
setCopiedSlotId(null);
|
);
|
||||||
}
|
const recentSeries = completedSeries.slice(0, 2);
|
||||||
}
|
const olderSeries = completedSeries.slice(2);
|
||||||
|
const rounds = competition.projection.rounds;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
|
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
|
||||||
<Link
|
<Link
|
||||||
to={`/match/${id}`}
|
to={`/match/${id}`}
|
||||||
className="mb-5 inline-flex text-xs text-base-content/40 hover:text-base-content"
|
className="mb-5 inline-flex min-h-11 items-center gap-1.5 text-sm font-bold text-content-muted hover:text-base-content focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
>
|
>
|
||||||
← 내전 상세로
|
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
|
||||||
|
내전 상세로
|
||||||
</Link>
|
</Link>
|
||||||
|
|
||||||
<header className="mb-6 border-b border-base-content/10 pb-5">
|
<header className="mb-8 flex flex-col gap-4 border-b border-base-content/10 pb-6 sm:flex-row sm:items-end sm:justify-between">
|
||||||
<p className="text-[11px] font-bold uppercase tracking-wider text-base-content/35">
|
<div className="min-w-0">
|
||||||
My Competition
|
<p className="text-xs font-bold text-content-muted">팀 경기 현황</p>
|
||||||
</p>
|
<h1
|
||||||
<h1 className="mt-1 text-2xl font-black">{team?.name ?? "내 팀"}</h1>
|
ref={contentHeadingRef}
|
||||||
<p className="mt-1 text-sm text-base-content/45">
|
className="mt-1 min-w-0 break-words text-2xl font-black sm:text-3xl"
|
||||||
우리 팀의 공식 대진과 토너먼트 코드는 이 페이지에서만 표시됩니다.
|
tabIndex={-1}
|
||||||
</p>
|
>
|
||||||
|
{team?.name ?? (selectedTeamId ? "팀" : "내 팀")}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 max-w-2xl text-sm text-content-muted">
|
||||||
|
다음 상대와 세트별 토너먼트 코드를 한곳에서 확인할 수 있습니다.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Link
|
||||||
|
to={`/match/${id}/team?select=1`}
|
||||||
|
className="inline-flex min-h-11 shrink-0 items-center justify-center gap-2 border border-base-content/20 bg-base-100 px-3 text-sm font-bold text-base-content hover:border-primary/40 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
|
>
|
||||||
|
<UsersRound className="h-4 w-4" aria-hidden="true" />
|
||||||
|
팀 변경
|
||||||
|
</Link>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<section className="mb-6" aria-labelledby="active-series-heading">
|
<section className="mb-8" aria-labelledby="active-series-heading">
|
||||||
<h2
|
<SectionHeading
|
||||||
id="active-series-heading"
|
id="active-series-heading"
|
||||||
className="mb-3 text-xs font-bold uppercase tracking-wider text-base-content/40"
|
title="다음 경기"
|
||||||
>
|
description="현재 팀이 준비하거나 진행해야 하는 공식 대진입니다."
|
||||||
진행할 Series
|
/>
|
||||||
</h2>
|
{activeSeriesGroups.length > 0 ? (
|
||||||
{teamView.activeSeries.length > 0 ? (
|
<div className="space-y-4">
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
{activeSeriesGroups.map(({ series, codes }) => {
|
||||||
{teamView.activeSeries.map((series) => (
|
const displayLabel = getTeamSeriesDisplayLabel(series, rounds);
|
||||||
<SeriesScoreCard
|
return (
|
||||||
key={series.seriesId}
|
<TeamSeriesCard
|
||||||
series={series}
|
key={series.seriesId}
|
||||||
teamById={teamById}
|
series={series}
|
||||||
/>
|
displayLabel={displayLabel}
|
||||||
))}
|
teamById={teamById}
|
||||||
|
highlightedTeamId={teamView.teamId}
|
||||||
|
emphasized
|
||||||
|
>
|
||||||
|
<TeamTournamentCodes
|
||||||
|
assignments={codes}
|
||||||
|
seriesLabel={displayLabel}
|
||||||
|
/>
|
||||||
|
</TeamSeriesCard>
|
||||||
|
);
|
||||||
|
})}
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<EmptyState message="현재 진행할 대진이 없습니다." />
|
<EmptyState message="현재 준비하거나 진행할 대진이 없습니다." />
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="mb-6" aria-labelledby="codes-heading">
|
|
||||||
<h2
|
|
||||||
id="codes-heading"
|
|
||||||
className="mb-3 text-xs font-bold uppercase tracking-wider text-base-content/40"
|
|
||||||
>
|
|
||||||
토너먼트 코드
|
|
||||||
</h2>
|
|
||||||
{teamView.tournamentCodes.length > 0 ? (
|
|
||||||
<ul className="grid gap-3 sm:grid-cols-2">
|
|
||||||
{teamView.tournamentCodes.map((assignment) => (
|
|
||||||
<li
|
|
||||||
key={assignment.gameSlotId}
|
|
||||||
className="border border-base-content/10 bg-base-100 p-4"
|
|
||||||
>
|
|
||||||
<div className="flex items-center justify-between gap-3">
|
|
||||||
<span className="text-xs font-bold text-base-content/45">
|
|
||||||
Game {assignment.displayNumber}
|
|
||||||
</span>
|
|
||||||
<span className="text-[11px] text-base-content/35">
|
|
||||||
{assignment.state === "used"
|
|
||||||
? "사용됨"
|
|
||||||
: assignment.state === "reserved"
|
|
||||||
? "사용 가능"
|
|
||||||
: "발급 대기"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="mt-3 flex items-center gap-2">
|
|
||||||
<code className="min-w-0 flex-1 truncate font-mono text-sm font-bold text-primary">
|
|
||||||
{assignment.code ?? "발급 대기"}
|
|
||||||
</code>
|
|
||||||
{assignment.code && assignment.state !== "used" && (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
className="border border-base-content/10 px-2 py-1 text-xs font-bold hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
|
|
||||||
onClick={() =>
|
|
||||||
void copyCode(assignment.gameSlotId, assignment.code)
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{copiedSlotId === assignment.gameSlotId
|
|
||||||
? "복사됨"
|
|
||||||
: "복사"}
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
) : (
|
|
||||||
<EmptyState message="배정된 토너먼트 코드가 없습니다." />
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="mb-6" aria-labelledby="completed-heading">
|
|
||||||
<h2
|
|
||||||
id="completed-heading"
|
|
||||||
className="mb-3 text-xs font-bold uppercase tracking-wider text-base-content/40"
|
|
||||||
>
|
|
||||||
종료된 Series
|
|
||||||
</h2>
|
|
||||||
{completedSeries.length > 0 ? (
|
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
|
||||||
{completedSeries.map((series) => (
|
|
||||||
<SeriesScoreCard
|
|
||||||
key={series.seriesId}
|
|
||||||
series={series}
|
|
||||||
teamById={teamById}
|
|
||||||
/>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<EmptyState message="아직 종료된 대진이 없습니다." />
|
|
||||||
)}
|
)}
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
{team && (
|
{team && (
|
||||||
<section className="border border-base-content/10 bg-base-100">
|
<section className="mb-8" aria-labelledby="roster-heading">
|
||||||
<h2 className="border-b border-base-content/10 bg-base-200/40 px-4 py-2 text-xs font-bold uppercase tracking-wider text-base-content/40">
|
<SectionHeading
|
||||||
팀 구성
|
id="roster-heading"
|
||||||
</h2>
|
title="팀 구성"
|
||||||
<ul className="divide-y divide-base-content/8">
|
description={`${team.members.length}명의 라인업을 포지션 순서로 보여줍니다.`}
|
||||||
{team.members.map((member) => (
|
/>
|
||||||
|
<ul className="divide-y divide-base-content/10 border border-base-content/10 bg-base-100">
|
||||||
|
{sortTeamMembersForRoster(team.members).map((member) => (
|
||||||
<li
|
<li
|
||||||
key={member.userId}
|
key={member.userId}
|
||||||
className="flex items-center gap-3 px-4 py-3"
|
className="grid min-h-12 grid-cols-[4.5rem_minmax(0,1fr)] items-center gap-3 px-4 py-2 sm:px-5"
|
||||||
>
|
>
|
||||||
<div className="min-w-0 flex-1">
|
<span className="text-xs font-bold text-content-muted">
|
||||||
<p className="truncate text-sm font-bold">
|
{member.assignedPosition
|
||||||
|
? positionLabel[member.assignedPosition]
|
||||||
|
: "미정"}
|
||||||
|
</span>
|
||||||
|
<div className="flex min-w-0 flex-wrap items-center gap-2">
|
||||||
|
<span className="min-w-0 break-words text-sm font-bold text-base-content">
|
||||||
{member.displayName}
|
{member.displayName}
|
||||||
</p>
|
</span>
|
||||||
{member.assignedPosition && (
|
{member.userId === team.captainUserId && (
|
||||||
<p className="mt-0.5 text-xs text-base-content/35">
|
<span className="border-l-2 border-warning bg-warning/15 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||||
{member.assignedPosition}
|
팀장
|
||||||
</p>
|
</span>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
{member.userId === team.captainUserId && (
|
|
||||||
<span className="text-xs font-bold text-warning">팀장</span>
|
|
||||||
)}
|
|
||||||
</li>
|
</li>
|
||||||
))}
|
))}
|
||||||
</ul>
|
</ul>
|
||||||
</section>
|
</section>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<section className="mb-6" aria-labelledby="completed-heading">
|
||||||
|
<SectionHeading
|
||||||
|
id="completed-heading"
|
||||||
|
title="지난 경기"
|
||||||
|
description="최근 결과를 먼저 보여주며, 오래된 결과는 펼쳐서 확인할 수 있습니다."
|
||||||
|
/>
|
||||||
|
{completedSeries.length > 0 ? (
|
||||||
|
<>
|
||||||
|
<div className="grid gap-3 md:grid-cols-2">
|
||||||
|
{recentSeries.map((series) => (
|
||||||
|
<TeamSeriesCard
|
||||||
|
key={series.seriesId}
|
||||||
|
series={series}
|
||||||
|
displayLabel={getTeamSeriesDisplayLabel(series, rounds)}
|
||||||
|
teamById={teamById}
|
||||||
|
highlightedTeamId={teamView.teamId}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{olderSeries.length > 0 && (
|
||||||
|
<details className="group mt-3 border border-base-content/10 bg-base-100">
|
||||||
|
<summary className="flex min-h-11 cursor-pointer list-none items-center justify-between gap-3 px-4 text-sm font-bold text-base-content hover:bg-base-200/50 focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary [&::-webkit-details-marker]:hidden">
|
||||||
|
<span>이전 경기 {olderSeries.length}개 더 보기</span>
|
||||||
|
<ChevronDown
|
||||||
|
className="h-4 w-4 transition-transform group-open:rotate-180 motion-reduce:transition-none"
|
||||||
|
aria-hidden="true"
|
||||||
|
/>
|
||||||
|
</summary>
|
||||||
|
<div className="grid gap-3 border-t border-base-content/10 p-3 md:grid-cols-2">
|
||||||
|
{olderSeries.map((series) => (
|
||||||
|
<TeamSeriesCard
|
||||||
|
key={series.seriesId}
|
||||||
|
series={series}
|
||||||
|
displayLabel={getTeamSeriesDisplayLabel(series, rounds)}
|
||||||
|
teamById={teamById}
|
||||||
|
highlightedTeamId={teamView.teamId}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<EmptyState message="아직 종료된 대진이 없습니다." />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SectionHeading({
|
||||||
|
id,
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
description: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className="mb-3 border-b border-base-content/10 pb-2">
|
||||||
|
<h2 id={id} className="text-base font-black text-base-content">
|
||||||
|
{title}
|
||||||
|
</h2>
|
||||||
|
<p className="mt-0.5 text-xs text-content-muted">{description}</p>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TeamSelectionState({
|
||||||
|
competition,
|
||||||
|
matchId,
|
||||||
|
}: {
|
||||||
|
competition: CompetitionDetailResponse;
|
||||||
|
matchId: string | undefined;
|
||||||
|
}) {
|
||||||
|
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
headingRef.current?.focus({ preventScroll: true });
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
|
||||||
|
<Link
|
||||||
|
to={`/match/${matchId}`}
|
||||||
|
className="mb-5 inline-flex min-h-11 items-center gap-1.5 text-sm font-bold text-content-muted hover:text-base-content focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" aria-hidden="true" />
|
||||||
|
내전 상세로
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<header className="mb-6 border-b border-base-content/10 pb-5">
|
||||||
|
<p className="text-xs font-bold text-content-muted">팀 경기 현황</p>
|
||||||
|
<h1 ref={headingRef} className="mt-1 text-2xl font-black" tabIndex={-1}>
|
||||||
|
팀 선택
|
||||||
|
</h1>
|
||||||
|
<p className="mt-1 text-sm text-content-muted">
|
||||||
|
진행 상황과 토너먼트 코드를 확인할 팀을 선택해 주세요.
|
||||||
|
</p>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
{competition.teams.length > 0 ? (
|
||||||
|
<ul className="grid gap-3 sm:grid-cols-2">
|
||||||
|
{competition.teams.map((team) => (
|
||||||
|
<li key={team.teamId}>
|
||||||
|
<Link
|
||||||
|
to={`/match/${matchId}/team?teamId=${team.teamId}`}
|
||||||
|
className="flex min-h-12 items-center justify-between gap-3 border border-base-content/10 bg-base-100 px-4 py-3 text-base-content hover:border-primary/40 hover:bg-primary/5 focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
|
>
|
||||||
|
<span className="min-w-0 break-words text-sm font-bold">
|
||||||
|
{team.name}
|
||||||
|
</span>
|
||||||
|
<span className="shrink-0 text-xs text-content-muted">
|
||||||
|
{team.members.length}명
|
||||||
|
</span>
|
||||||
|
</Link>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
) : (
|
||||||
|
<EmptyState message="구성된 팀이 없습니다." />
|
||||||
|
)}
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -285,9 +403,11 @@ function TeamProgressLoadingState() {
|
|||||||
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
|
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
|
||||||
aria-busy="true"
|
aria-busy="true"
|
||||||
aria-label="팀 진행 정보를 불러오는 중"
|
aria-label="팀 진행 정보를 불러오는 중"
|
||||||
|
role="status"
|
||||||
>
|
>
|
||||||
<div className="h-7 w-48 animate-pulse bg-base-200" />
|
<span className="sr-only">팀 진행 정보를 불러오는 중입니다.</span>
|
||||||
<div className="h-32 animate-pulse bg-base-200/70" />
|
<div className="h-7 w-48 animate-pulse bg-base-200 motion-reduce:animate-none" />
|
||||||
|
<div className="h-32 animate-pulse bg-base-200/70 motion-reduce:animate-none" />
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -303,6 +423,12 @@ function TeamProgressProblemState({
|
|||||||
matchId: string | undefined;
|
matchId: string | undefined;
|
||||||
onRetry: () => void;
|
onRetry: () => void;
|
||||||
}) {
|
}) {
|
||||||
|
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
headingRef.current?.focus({ preventScroll: true });
|
||||||
|
}, []);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto max-w-5xl px-4 py-20 sm:px-6">
|
<main className="mx-auto max-w-5xl px-4 py-20 sm:px-6">
|
||||||
<section
|
<section
|
||||||
@@ -310,20 +436,25 @@ function TeamProgressProblemState({
|
|||||||
aria-busy={isRetrying}
|
aria-busy={isRetrying}
|
||||||
className="border border-base-content/10 bg-base-100 px-5 py-8 text-center"
|
className="border border-base-content/10 bg-base-100 px-5 py-8 text-center"
|
||||||
>
|
>
|
||||||
<h1 className="text-lg font-bold">{content.title}</h1>
|
<h1 ref={headingRef} className="text-lg font-bold" tabIndex={-1}>
|
||||||
<p className="mt-2 text-sm text-base-content/45">
|
{content.title}
|
||||||
|
</h1>
|
||||||
|
<p className="mt-2 text-sm text-content-muted">
|
||||||
{content.description}
|
{content.description}
|
||||||
</p>
|
</p>
|
||||||
<div className="mt-5 flex flex-wrap justify-center gap-2">
|
<div className="mt-5 flex flex-wrap justify-center gap-2">
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="btn btn-primary btn-sm"
|
className="inline-flex min-h-11 items-center justify-center border border-primary/50 bg-primary/10 px-4 text-sm font-bold text-base-content hover:bg-primary/15 focus-visible:ring-2 focus-visible:ring-primary disabled:cursor-wait disabled:opacity-70"
|
||||||
disabled={isRetrying}
|
disabled={isRetrying}
|
||||||
onClick={onRetry}
|
onClick={onRetry}
|
||||||
>
|
>
|
||||||
{isRetrying ? "다시 불러오는 중..." : "다시 시도"}
|
{isRetrying ? "다시 불러오는 중..." : "다시 시도"}
|
||||||
</button>
|
</button>
|
||||||
<Link to={`/match/${matchId}`} className="btn btn-ghost btn-sm">
|
<Link
|
||||||
|
to={`/match/${matchId}`}
|
||||||
|
className="inline-flex min-h-11 items-center justify-center border border-base-content/20 bg-base-100 px-4 text-sm font-bold text-base-content hover:bg-base-200 focus-visible:ring-2 focus-visible:ring-primary"
|
||||||
|
>
|
||||||
내전 상세로
|
내전 상세로
|
||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
@@ -336,7 +467,7 @@ function EmptyState({ message }: { message: string }) {
|
|||||||
return (
|
return (
|
||||||
<p
|
<p
|
||||||
role="status"
|
role="status"
|
||||||
className="border border-dashed border-base-content/10 px-4 py-8 text-center text-sm text-base-content/40"
|
className="border border-dashed border-base-content/10 px-4 py-8 text-center text-sm text-content-muted"
|
||||||
>
|
>
|
||||||
{message}
|
{message}
|
||||||
</p>
|
</p>
|
||||||
|
|||||||
@@ -26,15 +26,24 @@ export function isConsistentTeamProgressSnapshot(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A visitor who is not signed in (401) — or is signed in but belongs to no team
|
||||||
|
* in this Competition (403) — can still read a team view by naming the team.
|
||||||
|
* Offer the team picker instead of an error until they have named one.
|
||||||
|
*/
|
||||||
|
export function shouldOfferTeamSelection(
|
||||||
|
errors: readonly unknown[],
|
||||||
|
selectedTeamId: string | undefined,
|
||||||
|
): boolean {
|
||||||
|
if (selectedTeamId) return false;
|
||||||
|
const statuses = errorStatuses(errors);
|
||||||
|
return statuses.includes(401) || statuses.includes(403);
|
||||||
|
}
|
||||||
|
|
||||||
export function getTeamProgressErrorContent(
|
export function getTeamProgressErrorContent(
|
||||||
errors: readonly unknown[],
|
errors: readonly unknown[],
|
||||||
): TeamProgressErrorContent {
|
): TeamProgressErrorContent {
|
||||||
const statuses = errors.flatMap((error) => {
|
const statuses = errorStatuses(errors);
|
||||||
if (typeof error !== "object" || error === null || !("status" in error)) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
return typeof error.status === "number" ? [error.status] : [];
|
|
||||||
});
|
|
||||||
|
|
||||||
if (statuses.includes(401)) {
|
if (statuses.includes(401)) {
|
||||||
return {
|
return {
|
||||||
@@ -86,6 +95,15 @@ export function getTeamProgressErrorContent(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function errorStatuses(errors: readonly unknown[]): number[] {
|
||||||
|
return errors.flatMap((error) => {
|
||||||
|
if (typeof error !== "object" || error === null || !("status" in error)) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
return typeof error.status === "number" ? [error.status] : [];
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function isNetworkError(error: unknown): boolean {
|
function isNetworkError(error: unknown): boolean {
|
||||||
return (
|
return (
|
||||||
error instanceof TypeError ||
|
error instanceof TypeError ||
|
||||||
|
|||||||
@@ -0,0 +1,274 @@
|
|||||||
|
import type {
|
||||||
|
BracketRoundView,
|
||||||
|
CompetitionTeamMemberView,
|
||||||
|
SeriesProjection,
|
||||||
|
TeamTournamentCodeView,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import { bracketRoundLabel } from "../components/competition/double-elimination-bracket-layout.ts";
|
||||||
|
|
||||||
|
export interface TeamSeriesGroup {
|
||||||
|
series: SeriesProjection;
|
||||||
|
codes: TeamTournamentCodeView[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TeamSeriesTone =
|
||||||
|
| "muted"
|
||||||
|
| "ready"
|
||||||
|
| "live"
|
||||||
|
| "completed"
|
||||||
|
| "adjudicated";
|
||||||
|
|
||||||
|
export interface TeamSeriesPresentation {
|
||||||
|
label: string;
|
||||||
|
tone: TeamSeriesTone;
|
||||||
|
showScore: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TournamentCodeTone =
|
||||||
|
| "pending"
|
||||||
|
| "available"
|
||||||
|
| "expired"
|
||||||
|
| "used";
|
||||||
|
|
||||||
|
export interface TournamentCodePresentation {
|
||||||
|
label: string;
|
||||||
|
tone: TournamentCodeTone;
|
||||||
|
canCopy: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type TournamentCodeCopyFeedback =
|
||||||
|
| { kind: "success"; message: string }
|
||||||
|
| { kind: "error"; message: string };
|
||||||
|
|
||||||
|
type ClipboardWriter = ((value: string) => Promise<void>) | undefined;
|
||||||
|
|
||||||
|
const POSITION_RANK = new Map(
|
||||||
|
(["TOP", "JGL", "MID", "ADC", "SUP"] as const).map(
|
||||||
|
(position, index) => [position, index],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
export function createTeamSeriesGroups(
|
||||||
|
activeSeries: readonly SeriesProjection[],
|
||||||
|
tournamentCodes: readonly TeamTournamentCodeView[],
|
||||||
|
): TeamSeriesGroup[] {
|
||||||
|
const codesBySeriesId = new Map<string, TeamTournamentCodeView[]>();
|
||||||
|
for (const assignment of tournamentCodes) {
|
||||||
|
const seriesId = String(assignment.seriesId);
|
||||||
|
const existing = codesBySeriesId.get(seriesId) ?? [];
|
||||||
|
existing.push(assignment);
|
||||||
|
codesBySeriesId.set(seriesId, existing);
|
||||||
|
}
|
||||||
|
|
||||||
|
return [...activeSeries]
|
||||||
|
.sort(compareSeriesDisplayOrder)
|
||||||
|
.map((series) => ({
|
||||||
|
series,
|
||||||
|
codes: [...(codesBySeriesId.get(String(series.seriesId)) ?? [])].sort(
|
||||||
|
compareTournamentCodes,
|
||||||
|
),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTeamSeriesDisplayLabel(
|
||||||
|
series: SeriesProjection,
|
||||||
|
rounds: readonly BracketRoundView[],
|
||||||
|
): string {
|
||||||
|
const round = rounds.find(({ seriesIds }) =>
|
||||||
|
seriesIds.some((seriesId) => seriesId === series.seriesId),
|
||||||
|
);
|
||||||
|
const stage = round?.stage ?? series.stage.type;
|
||||||
|
const roundNumber = round?.roundNumber ?? series.stage.roundNumber ?? 1;
|
||||||
|
const baseLabel = bracketRoundLabel(stage, roundNumber);
|
||||||
|
|
||||||
|
if (!round || round.seriesIds.length <= 1) return baseLabel;
|
||||||
|
const matchIndex = round.seriesIds.findIndex(
|
||||||
|
(seriesId) => seriesId === series.seriesId,
|
||||||
|
);
|
||||||
|
return matchIndex >= 0
|
||||||
|
? `${baseLabel} · ${matchIndex + 1}경기`
|
||||||
|
: baseLabel;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTeamSeriesPresentation(
|
||||||
|
series: SeriesProjection,
|
||||||
|
): TeamSeriesPresentation {
|
||||||
|
switch (series.status) {
|
||||||
|
case "inactive":
|
||||||
|
return { label: "비활성", tone: "muted", showScore: false };
|
||||||
|
case "waiting":
|
||||||
|
return { label: "대진 대기", tone: "muted", showScore: false };
|
||||||
|
case "ready":
|
||||||
|
return { label: "경기 가능", tone: "ready", showScore: false };
|
||||||
|
case "in-progress":
|
||||||
|
return { label: "진행 중", tone: "live", showScore: true };
|
||||||
|
case "completed":
|
||||||
|
switch (series.outcome.type) {
|
||||||
|
case "played":
|
||||||
|
return { label: "종료", tone: "completed", showScore: true };
|
||||||
|
case "draw":
|
||||||
|
return {
|
||||||
|
label: "무승부",
|
||||||
|
tone:
|
||||||
|
series.outcome.basis.type === "played"
|
||||||
|
? "completed"
|
||||||
|
: "adjudicated",
|
||||||
|
showScore: series.outcome.basis.type === "played",
|
||||||
|
};
|
||||||
|
case "walkover":
|
||||||
|
return { label: "부전승", tone: "adjudicated", showScore: false };
|
||||||
|
case "forfeit":
|
||||||
|
return { label: "기권승", tone: "adjudicated", showScore: false };
|
||||||
|
case "administrative":
|
||||||
|
return { label: "판정승", tone: "adjudicated", showScore: false };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTournamentCodePresentation(
|
||||||
|
assignment: TeamTournamentCodeView,
|
||||||
|
now = Date.now(),
|
||||||
|
): TournamentCodePresentation {
|
||||||
|
if (assignment.state === "used") {
|
||||||
|
return { label: "사용 완료", tone: "used", canCopy: false };
|
||||||
|
}
|
||||||
|
if (assignment.state === "pending" || !assignment.code) {
|
||||||
|
return { label: "발급 대기", tone: "pending", canCopy: false };
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
assignment.expiresAt &&
|
||||||
|
!Number.isFinite(Date.parse(assignment.expiresAt))
|
||||||
|
) {
|
||||||
|
return { label: "만료 정보 오류", tone: "expired", canCopy: false };
|
||||||
|
}
|
||||||
|
if (isExpired(assignment.expiresAt, now)) {
|
||||||
|
return { label: "만료", tone: "expired", canCopy: false };
|
||||||
|
}
|
||||||
|
return { label: "사용 가능", tone: "available", canCopy: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTournamentCodeExpiryLabel(
|
||||||
|
expiresAt: string,
|
||||||
|
now: number,
|
||||||
|
): string {
|
||||||
|
const date = new Date(expiresAt);
|
||||||
|
if (Number.isNaN(date.getTime())) return "만료 시각 정보 없음";
|
||||||
|
|
||||||
|
const formatted = new Intl.DateTimeFormat("ko-KR", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "Asia/Seoul",
|
||||||
|
timeZoneName: "short",
|
||||||
|
}).format(date);
|
||||||
|
return date.getTime() <= now
|
||||||
|
? `${formatted}에 만료됨`
|
||||||
|
: `${formatted}까지 사용 가능`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getNextTournamentCodeExpiryDelay(
|
||||||
|
assignments: readonly TeamTournamentCodeView[],
|
||||||
|
now: number,
|
||||||
|
): number | null {
|
||||||
|
let nearestExpiry = Number.POSITIVE_INFINITY;
|
||||||
|
for (const assignment of assignments) {
|
||||||
|
if (assignment.state !== "reserved" || !assignment.code) continue;
|
||||||
|
const expiry = assignment.expiresAt
|
||||||
|
? Date.parse(assignment.expiresAt)
|
||||||
|
: Number.NaN;
|
||||||
|
if (Number.isFinite(expiry) && expiry > now) {
|
||||||
|
nearestExpiry = Math.min(nearestExpiry, expiry);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Number.isFinite(nearestExpiry)) return null;
|
||||||
|
return Math.min(nearestExpiry - now, 2_147_483_647);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getTournamentCodeCopyLabel(
|
||||||
|
assignment: TeamTournamentCodeView,
|
||||||
|
seriesLabel: string,
|
||||||
|
): string {
|
||||||
|
return `${seriesLabel} ${assignment.ordinal}세트 토너먼트 코드 복사 (전체 ${assignment.displayNumber}번 게임)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function copyTournamentCode(
|
||||||
|
writeText: ClipboardWriter,
|
||||||
|
code: string,
|
||||||
|
gameLabel: string,
|
||||||
|
): Promise<TournamentCodeCopyFeedback> {
|
||||||
|
try {
|
||||||
|
if (!writeText) throw new Error("Clipboard API unavailable");
|
||||||
|
await writeText(code);
|
||||||
|
return {
|
||||||
|
kind: "success",
|
||||||
|
message: `${gameLabel} 코드를 복사했습니다.`,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return {
|
||||||
|
kind: "error",
|
||||||
|
message: `${gameLabel} 코드를 복사하지 못했습니다. 코드를 직접 선택해 복사해 주세요.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortCompletedTeamSeries(
|
||||||
|
series: readonly Extract<SeriesProjection, { status: "completed" }>[],
|
||||||
|
): Array<Extract<SeriesProjection, { status: "completed" }>> {
|
||||||
|
return [...series].sort(
|
||||||
|
(left, right) =>
|
||||||
|
timestampValue(right.outcome.completedAt) -
|
||||||
|
timestampValue(left.outcome.completedAt) ||
|
||||||
|
right.stage.displayOrder - left.stage.displayOrder ||
|
||||||
|
String(left.seriesId).localeCompare(String(right.seriesId)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sortTeamMembersForRoster(
|
||||||
|
members: readonly CompetitionTeamMemberView[],
|
||||||
|
): CompetitionTeamMemberView[] {
|
||||||
|
return [...members].sort(
|
||||||
|
(left, right) =>
|
||||||
|
(left.assignedPosition
|
||||||
|
? (POSITION_RANK.get(left.assignedPosition) ?? POSITION_RANK.size)
|
||||||
|
: POSITION_RANK.size) -
|
||||||
|
(right.assignedPosition
|
||||||
|
? (POSITION_RANK.get(right.assignedPosition) ?? POSITION_RANK.size)
|
||||||
|
: POSITION_RANK.size) ||
|
||||||
|
left.displayName.localeCompare(right.displayName, "ko"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareSeriesDisplayOrder(
|
||||||
|
left: SeriesProjection,
|
||||||
|
right: SeriesProjection,
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
left.stage.displayOrder - right.stage.displayOrder ||
|
||||||
|
String(left.seriesId).localeCompare(String(right.seriesId))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function compareTournamentCodes(
|
||||||
|
left: TeamTournamentCodeView,
|
||||||
|
right: TeamTournamentCodeView,
|
||||||
|
): number {
|
||||||
|
return (
|
||||||
|
left.ordinal - right.ordinal ||
|
||||||
|
left.displayNumber - right.displayNumber ||
|
||||||
|
String(left.gameSlotId).localeCompare(String(right.gameSlotId))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isExpired(expiresAt: string | null, now: number): boolean {
|
||||||
|
if (!expiresAt) return false;
|
||||||
|
const timestamp = Date.parse(expiresAt);
|
||||||
|
return Number.isFinite(timestamp) && timestamp <= now;
|
||||||
|
}
|
||||||
|
|
||||||
|
function timestampValue(value: string): number {
|
||||||
|
const timestamp = Date.parse(value);
|
||||||
|
return Number.isFinite(timestamp) ? timestamp : Number.NEGATIVE_INFINITY;
|
||||||
|
}
|
||||||
@@ -0,0 +1,928 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import type {
|
||||||
|
CompetitionGameView,
|
||||||
|
GameId,
|
||||||
|
GameSlotId,
|
||||||
|
SeriesId,
|
||||||
|
SeriesProjection,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import {
|
||||||
|
competitionHistoryGameDetailPath,
|
||||||
|
createCompetitionSeriesHistory,
|
||||||
|
formatCompetitionHistoryDate,
|
||||||
|
formatCompetitionHistoryTime,
|
||||||
|
formatSeriesGameDuration,
|
||||||
|
getSeriesHistoryRecordLabel,
|
||||||
|
getSeriesHistoryResultLabel,
|
||||||
|
getSeriesHistoryStatusLabel,
|
||||||
|
getSeriesHistoryTimePresentation,
|
||||||
|
isCompetitionHistoryCalendarDate,
|
||||||
|
shouldDisplaySeriesHistoryScore,
|
||||||
|
} from "../src/components/competition/competition-series-history.ts";
|
||||||
|
import { isSeriesEntryWinner } from "../src/components/competition/series-score-card-model.ts";
|
||||||
|
|
||||||
|
test("aggregates Games under their Series and preserves Series slot scores", () => {
|
||||||
|
const teamA = teamId("team-a");
|
||||||
|
const teamB = teamId("team-b");
|
||||||
|
const series = completedSeries({
|
||||||
|
id: "series-score",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 1,
|
||||||
|
completedAt: "2026-07-12T13:00:00.000Z",
|
||||||
|
});
|
||||||
|
const laterGame = game({
|
||||||
|
id: "game-later",
|
||||||
|
seriesId: series.seriesId,
|
||||||
|
ordinal: 2,
|
||||||
|
displayNumber: 4,
|
||||||
|
blueTeamId: teamB,
|
||||||
|
redTeamId: teamA,
|
||||||
|
winnerTeamId: teamB,
|
||||||
|
startedAt: "2026-07-12T12:30:00.000Z",
|
||||||
|
});
|
||||||
|
const earlierGame = game({
|
||||||
|
id: "game-earlier",
|
||||||
|
seriesId: series.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 19,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-12T12:00:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const history = createCompetitionSeriesHistory({
|
||||||
|
series: [series],
|
||||||
|
games: [laterGame, earlierGame],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(history.length, 1);
|
||||||
|
assert.equal(history[0].dateKey, "2026-07-12");
|
||||||
|
assert.equal(history[0].rows.length, 1);
|
||||||
|
assert.deepEqual(
|
||||||
|
history[0].rows[0].series.entries.map((entry) => entry.gameWins),
|
||||||
|
[2, 1],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
history[0].rows[0].games.map(({ ordinal }) => ordinal),
|
||||||
|
[1, 2],
|
||||||
|
);
|
||||||
|
assert.equal(history[0].rows[0].occurredAt, earlierGame.startedAt);
|
||||||
|
assert.equal(history[0].rows[0].timestampSource, "game-start");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("builds Game detail routes from global display numbers, not Series ordinals", () => {
|
||||||
|
const recordedGame = game({
|
||||||
|
id: "globally-numbered-game",
|
||||||
|
seriesId: seriesId("second-series"),
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 17,
|
||||||
|
blueTeamId: teamId("team-a"),
|
||||||
|
redTeamId: teamId("team-b"),
|
||||||
|
winnerTeamId: teamId("team-a"),
|
||||||
|
startedAt: "2026-07-13T09:00:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
competitionHistoryGameDetailPath(
|
||||||
|
"community-1",
|
||||||
|
"match-1",
|
||||||
|
recordedGame,
|
||||||
|
),
|
||||||
|
"/communities/community-1/internal-stats/match/match-1/game/17",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
competitionHistoryGameDetailPath("community-1", "match-1", {
|
||||||
|
displayNumber: 0,
|
||||||
|
}),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
competitionHistoryGameDetailPath("community-1", "match-1", {
|
||||||
|
displayNumber: 1.5,
|
||||||
|
}),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("groups and orders Series by the Asia/Seoul calendar day", () => {
|
||||||
|
const firstDay = playedSeriesWithGame({
|
||||||
|
id: "first-day",
|
||||||
|
displayOrder: 3,
|
||||||
|
startedAt: "2026-07-12T14:55:00.000Z",
|
||||||
|
});
|
||||||
|
const secondDayLater = playedSeriesWithGame({
|
||||||
|
id: "second-day-later",
|
||||||
|
displayOrder: 2,
|
||||||
|
startedAt: "2026-07-12T16:05:00.000Z",
|
||||||
|
});
|
||||||
|
const secondDayEarlier = playedSeriesWithGame({
|
||||||
|
id: "second-day-earlier",
|
||||||
|
displayOrder: 1,
|
||||||
|
startedAt: "2026-07-12T15:05:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const history = createCompetitionSeriesHistory({
|
||||||
|
series: [secondDayLater.series, firstDay.series, secondDayEarlier.series],
|
||||||
|
games: [secondDayLater.game, secondDayEarlier.game, firstDay.game],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
history.map(({ dateKey }) => dateKey),
|
||||||
|
["2026-07-12", "2026-07-13"],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
history[1].rows.map(({ series }) => series.seriesId),
|
||||||
|
[secondDayEarlier.series.seriesId, secondDayLater.series.seriesId],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("includes recorded in-progress Series and game-less completed decisions", () => {
|
||||||
|
const teamA = teamId("team-a");
|
||||||
|
const teamB = teamId("team-b");
|
||||||
|
const running = inProgressSeries("running-recorded", teamA, teamB, 1, 0);
|
||||||
|
const runningGame = game({
|
||||||
|
id: "running-game",
|
||||||
|
seriesId: running.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 1,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-13T09:00:00.000Z",
|
||||||
|
});
|
||||||
|
const administrative = completedSeries({
|
||||||
|
id: "administrative",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
completedAt: "2026-07-13T10:00:00.000Z",
|
||||||
|
outcome: "administrative",
|
||||||
|
});
|
||||||
|
const unrecordedRunning = inProgressSeries(
|
||||||
|
"running-unrecorded",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
);
|
||||||
|
|
||||||
|
const history = createCompetitionSeriesHistory({
|
||||||
|
series: [
|
||||||
|
unrecordedRunning,
|
||||||
|
administrative,
|
||||||
|
running,
|
||||||
|
],
|
||||||
|
games: [runningGame],
|
||||||
|
});
|
||||||
|
const rows = history.flatMap(({ rows }) => rows);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
rows.map(({ series }) => series.seriesId),
|
||||||
|
[running.seriesId, administrative.seriesId],
|
||||||
|
);
|
||||||
|
assert.equal(rows[0].timestampSource, "game-start");
|
||||||
|
assert.equal(rows[1].timestampSource, "decision");
|
||||||
|
assert.equal(rows[1].occurredAt, administrative.outcome.completedAt);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("includes ready and waiting Series in dated and final unscheduled groups", () => {
|
||||||
|
const teamA = teamId("future-team-a");
|
||||||
|
const teamB = teamId("future-team-b");
|
||||||
|
const scheduledReady = withSchedule(
|
||||||
|
readySeries("scheduled-ready", teamA, teamB),
|
||||||
|
{ date: "2026-07-15", time: "21:30", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const scheduledWaiting = withSchedule(waitingSeries("scheduled-waiting"), {
|
||||||
|
date: "2026-07-15",
|
||||||
|
time: null,
|
||||||
|
timeZone: "Asia/Seoul",
|
||||||
|
});
|
||||||
|
const unscheduledReady = {
|
||||||
|
...readySeries("unscheduled-ready", teamA, teamB),
|
||||||
|
stage: { type: "upper" as const, roundNumber: 1, displayOrder: 3 },
|
||||||
|
};
|
||||||
|
const unscheduledWaiting = {
|
||||||
|
...waitingSeries("unscheduled-waiting"),
|
||||||
|
stage: { type: "upper" as const, roundNumber: 1, displayOrder: 4 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const history = createCompetitionSeriesHistory({
|
||||||
|
series: [
|
||||||
|
unscheduledWaiting,
|
||||||
|
scheduledWaiting,
|
||||||
|
unscheduledReady,
|
||||||
|
scheduledReady,
|
||||||
|
],
|
||||||
|
games: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
history.map(({ dateKey }) => dateKey),
|
||||||
|
["2026-07-15", "unknown"],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
history[0].rows.map(({ series }) => series.seriesId),
|
||||||
|
[scheduledReady.seriesId, scheduledWaiting.seriesId],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
history[1].rows.map(({ series }) => series.seriesId),
|
||||||
|
[unscheduledReady.seriesId, unscheduledWaiting.seriesId],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps missing historical timestamps separate from unscheduled future Series", () => {
|
||||||
|
const teamA = teamId("missing-record-time-a");
|
||||||
|
const teamB = teamId("missing-record-time-b");
|
||||||
|
const historical = completedSeries({
|
||||||
|
id: "missing-record-time",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
completedAt: "not-an-iso-date",
|
||||||
|
outcome: "administrative",
|
||||||
|
});
|
||||||
|
const future = readySeries("missing-schedule-date", teamA, teamB);
|
||||||
|
|
||||||
|
const history = createCompetitionSeriesHistory({
|
||||||
|
series: [future, historical],
|
||||||
|
games: [],
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
history.map(({ dateKey }) => dateKey),
|
||||||
|
["record-unknown", "unknown"],
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
formatCompetitionHistoryDate(history[0].dateKey),
|
||||||
|
"기록 일시 미상",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
formatCompetitionHistoryDate(history[1].dateKey),
|
||||||
|
"일정 미정",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prefers recorded start and decision times over an attached schedule", () => {
|
||||||
|
const teamA = teamId("record-precedence-a");
|
||||||
|
const teamB = teamId("record-precedence-b");
|
||||||
|
const played = withSchedule(
|
||||||
|
completedSeries({
|
||||||
|
id: "recorded-start-precedence",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 0,
|
||||||
|
completedAt: "2026-07-12T12:00:00.000Z",
|
||||||
|
}),
|
||||||
|
{ date: "2026-08-01", time: "20:00", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const recordedGame = game({
|
||||||
|
id: "recorded-start-precedence-game",
|
||||||
|
seriesId: played.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 20,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-12T11:00:00.000Z",
|
||||||
|
});
|
||||||
|
const decided = withSchedule(
|
||||||
|
completedSeries({
|
||||||
|
id: "decision-precedence",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
completedAt: "2026-07-13T11:00:00.000Z",
|
||||||
|
outcome: "administrative",
|
||||||
|
}),
|
||||||
|
{ date: "2026-08-02", time: "21:00", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const running = withSchedule(
|
||||||
|
inProgressSeries("running-start-precedence", teamA, teamB, 1, 0),
|
||||||
|
{ date: "2026-08-03", time: "22:00", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const runningGame = game({
|
||||||
|
id: "running-start-precedence-game",
|
||||||
|
seriesId: running.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 21,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-14T11:00:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = createCompetitionSeriesHistory({
|
||||||
|
series: [running, decided, played],
|
||||||
|
games: [runningGame, recordedGame],
|
||||||
|
}).flatMap(({ rows }) => rows);
|
||||||
|
|
||||||
|
assert.equal(rows[0].timestampSource, "game-start");
|
||||||
|
assert.equal(rows[0].occurredAt, recordedGame.startedAt);
|
||||||
|
assert.equal(rows[1].timestampSource, "decision");
|
||||||
|
assert.equal(rows[1].occurredAt, decided.outcome.completedAt);
|
||||||
|
assert.equal(rows[2].timestampSource, "game-start");
|
||||||
|
assert.equal(rows[2].occurredAt, runningGame.startedAt);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps Series with invalid recorded Game starts in the missing-record group", () => {
|
||||||
|
const teamA = teamId("invalid-game-start-a");
|
||||||
|
const teamB = teamId("invalid-game-start-b");
|
||||||
|
const scheduledRunning = withSchedule(
|
||||||
|
inProgressSeries("invalid-running-scheduled", teamA, teamB, 0, 0),
|
||||||
|
{ date: "2026-08-03", time: "22:00", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const unscheduledRunning = {
|
||||||
|
...inProgressSeries("invalid-running-unscheduled", teamA, teamB, 0, 0),
|
||||||
|
stage: { type: "upper" as const, roundNumber: 1, displayOrder: 2 },
|
||||||
|
};
|
||||||
|
const completed = completedSeries({
|
||||||
|
id: "invalid-completed-game-start",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 0,
|
||||||
|
displayOrder: 3,
|
||||||
|
completedAt: "2026-07-15T11:00:00.000Z",
|
||||||
|
});
|
||||||
|
const invalidGames = [scheduledRunning, unscheduledRunning, completed].map(
|
||||||
|
(series, index) =>
|
||||||
|
game({
|
||||||
|
id: `invalid-start-game-${index}`,
|
||||||
|
seriesId: series.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 30 + index,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "not-an-iso-date",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
invalidGames.push(
|
||||||
|
game({
|
||||||
|
id: "mixed-valid-start-game",
|
||||||
|
seriesId: scheduledRunning.seriesId,
|
||||||
|
ordinal: 2,
|
||||||
|
displayNumber: 33,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-14T11:00:00.000Z",
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows = createCompetitionSeriesHistory({
|
||||||
|
series: [completed, unscheduledRunning, scheduledRunning],
|
||||||
|
games: invalidGames,
|
||||||
|
}).flatMap(({ rows }) => rows);
|
||||||
|
|
||||||
|
assert.equal(rows.length, 3);
|
||||||
|
for (const row of rows) {
|
||||||
|
assert.equal(row.dateKey, "record-unknown");
|
||||||
|
assert.equal(row.timestampSource, "game-start");
|
||||||
|
assert.equal(row.occurredAt, null);
|
||||||
|
assert.deepEqual(getSeriesHistoryTimePresentation(row), {
|
||||||
|
text: "—",
|
||||||
|
dateTime: null,
|
||||||
|
screenReaderText: "시작 시각 기록 없음",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hides unscheduled inactive Series but includes a scheduled conditional Series", () => {
|
||||||
|
const unscheduledInactive = inactiveSeries("inactive-unscheduled");
|
||||||
|
const scheduledInactive = withSchedule(
|
||||||
|
inactiveSeries("inactive-scheduled"),
|
||||||
|
{ date: "2026-07-16", time: null, timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
|
||||||
|
const rows = createCompetitionSeriesHistory({
|
||||||
|
series: [unscheduledInactive, scheduledInactive],
|
||||||
|
games: [],
|
||||||
|
}).flatMap(({ rows }) => rows);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
rows.map(({ series }) => series.seriesId),
|
||||||
|
[scheduledInactive.seriesId],
|
||||||
|
);
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(scheduledInactive), "필요 시");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sorts tied timestamps deterministically and ignores orphan Games", () => {
|
||||||
|
const teamA = teamId("team-a");
|
||||||
|
const teamB = teamId("team-b");
|
||||||
|
const earlierDisplayOrder = completedSeries({
|
||||||
|
id: "series-z",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 0,
|
||||||
|
displayOrder: 1,
|
||||||
|
completedAt: "2026-07-13T12:00:00.000Z",
|
||||||
|
});
|
||||||
|
const laterDisplayOrder = completedSeries({
|
||||||
|
id: "series-a",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 1,
|
||||||
|
displayOrder: 2,
|
||||||
|
completedAt: "2026-07-13T12:00:00.000Z",
|
||||||
|
});
|
||||||
|
const orphanGame = game({
|
||||||
|
id: "orphan-game",
|
||||||
|
seriesId: seriesId("missing-series"),
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: 99,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt: "2026-07-13T08:00:00.000Z",
|
||||||
|
});
|
||||||
|
|
||||||
|
const rows = createCompetitionSeriesHistory({
|
||||||
|
series: [laterDisplayOrder, earlierDisplayOrder],
|
||||||
|
games: [orphanGame],
|
||||||
|
}).flatMap(({ rows }) => rows);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
rows.map(({ series }) => series.seriesId),
|
||||||
|
[earlierDisplayOrder.seriesId, laterDisplayOrder.seriesId],
|
||||||
|
);
|
||||||
|
assert.equal(rows.every(({ games }) => games.length === 0), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("separates lifecycle status from played and adjudicated result labels", () => {
|
||||||
|
const teamA = teamId("team-a");
|
||||||
|
const teamB = teamId("team-b");
|
||||||
|
const running = inProgressSeries("running", teamA, teamB, 1, 0);
|
||||||
|
const ready = readySeries("ready-status", teamA, teamB);
|
||||||
|
const waiting = waitingSeries("waiting-status");
|
||||||
|
const conditional = withSchedule(inactiveSeries("conditional-status"), {
|
||||||
|
date: "2026-07-16",
|
||||||
|
time: null,
|
||||||
|
timeZone: "Asia/Seoul",
|
||||||
|
});
|
||||||
|
const played = completedSeries({
|
||||||
|
id: "played",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 1,
|
||||||
|
});
|
||||||
|
const playedDraw = completedSeries({
|
||||||
|
id: "played-draw",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 1,
|
||||||
|
outcome: "draw",
|
||||||
|
});
|
||||||
|
const administrativeDraw = {
|
||||||
|
...playedDraw,
|
||||||
|
seriesId: seriesId("administrative-draw-label"),
|
||||||
|
outcome: {
|
||||||
|
...playedDraw.outcome,
|
||||||
|
basis: {
|
||||||
|
type: "administrative" as const,
|
||||||
|
decisionFactId: "draw-label-fact" as never,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const walkover = completedSeries({
|
||||||
|
id: "walkover",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
outcome: "walkover",
|
||||||
|
});
|
||||||
|
const forfeit = completedSeries({
|
||||||
|
id: "forfeit",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 1,
|
||||||
|
outcome: "forfeit",
|
||||||
|
});
|
||||||
|
const administrative = completedSeries({
|
||||||
|
id: "administrative",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
outcome: "administrative",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(ready), "예정");
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(waiting), "예정");
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(conditional), "필요 시");
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(running), "진행 중");
|
||||||
|
for (const completed of [
|
||||||
|
played,
|
||||||
|
playedDraw,
|
||||||
|
administrativeDraw,
|
||||||
|
walkover,
|
||||||
|
forfeit,
|
||||||
|
administrative,
|
||||||
|
]) {
|
||||||
|
assert.equal(getSeriesHistoryStatusLabel(completed), "최종");
|
||||||
|
}
|
||||||
|
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(ready), "VS");
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(waiting), "VS");
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(conditional), "VS");
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(running), null);
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(played), null);
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(playedDraw), "무승부");
|
||||||
|
assert.equal(
|
||||||
|
getSeriesHistoryResultLabel(administrativeDraw),
|
||||||
|
"판정 무승부",
|
||||||
|
);
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(walkover), "부전승");
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(forfeit), "기권승");
|
||||||
|
assert.equal(getSeriesHistoryResultLabel(administrative), "판정승");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("describes recorded Games, decisions, and legacy missing records", () => {
|
||||||
|
const teamA = teamId("record-team-a");
|
||||||
|
const teamB = teamId("record-team-b");
|
||||||
|
const played = completedSeries({
|
||||||
|
id: "recorded-played",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 0,
|
||||||
|
});
|
||||||
|
const decision = completedSeries({
|
||||||
|
id: "recorded-decision",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 0,
|
||||||
|
outcome: "walkover",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(getSeriesHistoryRecordLabel(played, 2, false), "게임 상세 (2)");
|
||||||
|
assert.equal(getSeriesHistoryRecordLabel(played, 2, true), "게임 상세 접기");
|
||||||
|
assert.equal(getSeriesHistoryRecordLabel(decision, 0, false), "경기 없이 결정");
|
||||||
|
assert.equal(getSeriesHistoryRecordLabel(played, 0, false), "게임 기록 미등록");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("presents known and unknown future times without an invalid time value", () => {
|
||||||
|
const teamA = teamId("time-team-a");
|
||||||
|
const teamB = teamId("time-team-b");
|
||||||
|
const knownTime = withSchedule(
|
||||||
|
readySeries("known-scheduled-time", teamA, teamB),
|
||||||
|
{ date: "2026-07-15", time: "21:30", timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const unknownTime = withSchedule(
|
||||||
|
readySeries("unknown-scheduled-time", teamA, teamB),
|
||||||
|
{ date: "2026-07-15", time: null, timeZone: "Asia/Seoul" },
|
||||||
|
);
|
||||||
|
const rows = createCompetitionSeriesHistory({
|
||||||
|
series: [unknownTime, knownTime],
|
||||||
|
games: [],
|
||||||
|
}).flatMap(({ rows }) => rows);
|
||||||
|
const knownRow = rows.find(
|
||||||
|
({ series }) => series.seriesId === knownTime.seriesId,
|
||||||
|
);
|
||||||
|
const unknownRow = rows.find(
|
||||||
|
({ series }) => series.seriesId === unknownTime.seriesId,
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.ok(knownRow);
|
||||||
|
assert.ok(unknownRow);
|
||||||
|
|
||||||
|
assert.deepEqual(getSeriesHistoryTimePresentation(knownRow), {
|
||||||
|
text: "21:30",
|
||||||
|
dateTime: "2026-07-15T21:30:00+09:00",
|
||||||
|
screenReaderText: null,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesHistoryTimePresentation(unknownRow), {
|
||||||
|
text: "--:--",
|
||||||
|
dateTime: null,
|
||||||
|
screenReaderText: "시작 시간 미정",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows a numeric score only for played records", () => {
|
||||||
|
const teamA = teamId("team-a");
|
||||||
|
const teamB = teamId("team-b");
|
||||||
|
const playedDraw = completedSeries({
|
||||||
|
id: "played-draw",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 1,
|
||||||
|
outcome: "draw",
|
||||||
|
});
|
||||||
|
const administrativeDraw = {
|
||||||
|
...playedDraw,
|
||||||
|
seriesId: seriesId("administrative-draw"),
|
||||||
|
outcome: {
|
||||||
|
...playedDraw.outcome,
|
||||||
|
basis: {
|
||||||
|
type: "administrative" as const,
|
||||||
|
decisionFactId: "draw-fact" as never,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
shouldDisplaySeriesHistoryScore(
|
||||||
|
inProgressSeries("running-score", teamA, teamB, 1, 0),
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
shouldDisplaySeriesHistoryScore(
|
||||||
|
completedSeries({
|
||||||
|
id: "played-score",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 1,
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
assert.equal(shouldDisplaySeriesHistoryScore(playedDraw), true);
|
||||||
|
assert.equal(shouldDisplaySeriesHistoryScore(administrativeDraw), false);
|
||||||
|
assert.equal(
|
||||||
|
shouldDisplaySeriesHistoryScore(
|
||||||
|
completedSeries({
|
||||||
|
id: "forfeit-score",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 1,
|
||||||
|
scoreB: 1,
|
||||||
|
outcome: "forfeit",
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses the official outcome winner even when adjudicated score order differs", () => {
|
||||||
|
const teamA = teamId("official-winner");
|
||||||
|
const teamB = teamId("score-leader");
|
||||||
|
const series = completedSeries({
|
||||||
|
id: "adjudicated-winner",
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 0,
|
||||||
|
scoreB: 1,
|
||||||
|
outcome: "forfeit",
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(isSeriesEntryWinner(series, teamA), true);
|
||||||
|
assert.equal(isSeriesEntryWinner(series, teamB), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("formats recorded Game duration and omits unknown legacy zero values", () => {
|
||||||
|
assert.equal(formatSeriesGameDuration(1_875), "31:15");
|
||||||
|
assert.equal(formatSeriesGameDuration(3_661), "1:01:01");
|
||||||
|
assert.equal(formatSeriesGameDuration(0), null);
|
||||||
|
assert.equal(formatSeriesGameDuration(-1), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("formats history dates and times explicitly in Asia/Seoul", () => {
|
||||||
|
assert.equal(formatCompetitionHistoryDate("2026-07-05"), "7월 05일 (일)");
|
||||||
|
assert.equal(formatCompetitionHistoryDate("2026-07-13"), "7월 13일 (월)");
|
||||||
|
assert.equal(
|
||||||
|
formatCompetitionHistoryTime("2026-07-12T15:05:00.000Z"),
|
||||||
|
"00:05",
|
||||||
|
);
|
||||||
|
assert.equal(formatCompetitionHistoryDate("unknown"), "일정 미정");
|
||||||
|
assert.equal(
|
||||||
|
formatCompetitionHistoryDate("record-unknown"),
|
||||||
|
"기록 일시 미상",
|
||||||
|
);
|
||||||
|
assert.equal(isCompetitionHistoryCalendarDate("2026-07-05"), true);
|
||||||
|
assert.equal(isCompetitionHistoryCalendarDate("record-unknown"), false);
|
||||||
|
assert.equal(isCompetitionHistoryCalendarDate("unknown"), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
function playedSeriesWithGame({
|
||||||
|
id,
|
||||||
|
displayOrder,
|
||||||
|
startedAt,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
displayOrder: number;
|
||||||
|
startedAt: string;
|
||||||
|
}) {
|
||||||
|
const teamA = teamId(`${id}-a`);
|
||||||
|
const teamB = teamId(`${id}-b`);
|
||||||
|
const series = completedSeries({
|
||||||
|
id,
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA: 2,
|
||||||
|
scoreB: 0,
|
||||||
|
displayOrder,
|
||||||
|
completedAt: startedAt,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
series,
|
||||||
|
game: game({
|
||||||
|
id: `${id}-game`,
|
||||||
|
seriesId: series.seriesId,
|
||||||
|
ordinal: 1,
|
||||||
|
displayNumber: displayOrder,
|
||||||
|
blueTeamId: teamA,
|
||||||
|
redTeamId: teamB,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
startedAt,
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedSeries({
|
||||||
|
id,
|
||||||
|
teamA,
|
||||||
|
teamB,
|
||||||
|
scoreA,
|
||||||
|
scoreB,
|
||||||
|
displayOrder = 1,
|
||||||
|
completedAt = "2026-07-13T00:00:00.000Z",
|
||||||
|
outcome = "played",
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
teamA: TeamId;
|
||||||
|
teamB: TeamId;
|
||||||
|
scoreA: number;
|
||||||
|
scoreB: number;
|
||||||
|
displayOrder?: number;
|
||||||
|
completedAt?: string;
|
||||||
|
outcome?: "played" | "draw" | "walkover" | "forfeit" | "administrative";
|
||||||
|
}): Extract<SeriesProjection, { status: "completed" }> {
|
||||||
|
const base = {
|
||||||
|
seriesId: seriesId(id),
|
||||||
|
stage: { type: "upper" as const, roundNumber: 1, displayOrder },
|
||||||
|
rule: { type: "first-to" as const, winsRequired: 2, maxGames: 3 },
|
||||||
|
status: "completed" as const,
|
||||||
|
entries: [
|
||||||
|
{ slot: "A" as const, teamId: teamA, gameWins: scoreA },
|
||||||
|
{ slot: "B" as const, teamId: teamB, gameWins: scoreB },
|
||||||
|
] as const,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (outcome === "draw") {
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
outcome: {
|
||||||
|
type: "draw",
|
||||||
|
basis: { type: "played", decidedByGameIds: [] },
|
||||||
|
completedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (outcome !== "played") {
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
outcome: {
|
||||||
|
type: outcome,
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
loserTeamId: teamB,
|
||||||
|
decisionFactId: `fact-${id}` as never,
|
||||||
|
completedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
...base,
|
||||||
|
outcome: {
|
||||||
|
type: "played",
|
||||||
|
winnerTeamId: teamA,
|
||||||
|
loserTeamId: teamB,
|
||||||
|
decidedByGameIds: [],
|
||||||
|
completedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function inProgressSeries(
|
||||||
|
id: string,
|
||||||
|
teamA: TeamId,
|
||||||
|
teamB: TeamId,
|
||||||
|
scoreA: number,
|
||||||
|
scoreB: number,
|
||||||
|
): Extract<SeriesProjection, { status: "in-progress" }> {
|
||||||
|
return {
|
||||||
|
seriesId: seriesId(id),
|
||||||
|
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
|
||||||
|
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
|
||||||
|
status: "in-progress",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: teamA, gameWins: scoreA },
|
||||||
|
{ slot: "B", teamId: teamB, gameWins: scoreB },
|
||||||
|
],
|
||||||
|
...(scoreA === scoreB
|
||||||
|
? {}
|
||||||
|
: { leaderTeamId: scoreA > scoreB ? teamA : teamB }),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readySeries(
|
||||||
|
id: string,
|
||||||
|
teamA: TeamId,
|
||||||
|
teamB: TeamId,
|
||||||
|
): Extract<SeriesProjection, { status: "ready" }> {
|
||||||
|
return {
|
||||||
|
seriesId: seriesId(id),
|
||||||
|
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
|
||||||
|
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
|
||||||
|
status: "ready",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: teamA, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: teamB, gameWins: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function waitingSeries(
|
||||||
|
id: string,
|
||||||
|
): Extract<SeriesProjection, { status: "waiting" }> {
|
||||||
|
return {
|
||||||
|
seriesId: seriesId(id),
|
||||||
|
stage: { type: "upper", roundNumber: 1, displayOrder: 1 },
|
||||||
|
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
|
||||||
|
status: "waiting",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: null, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: null, gameWins: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function inactiveSeries(
|
||||||
|
id: string,
|
||||||
|
): Extract<SeriesProjection, { status: "inactive" }> {
|
||||||
|
return { ...waitingSeries(id), status: "inactive" };
|
||||||
|
}
|
||||||
|
|
||||||
|
function game({
|
||||||
|
id,
|
||||||
|
seriesId: parentSeriesId,
|
||||||
|
ordinal,
|
||||||
|
displayNumber,
|
||||||
|
blueTeamId,
|
||||||
|
redTeamId,
|
||||||
|
winnerTeamId,
|
||||||
|
startedAt,
|
||||||
|
}: {
|
||||||
|
id: string;
|
||||||
|
seriesId: SeriesId;
|
||||||
|
ordinal: number;
|
||||||
|
displayNumber: number;
|
||||||
|
blueTeamId: TeamId;
|
||||||
|
redTeamId: TeamId;
|
||||||
|
winnerTeamId: TeamId;
|
||||||
|
startedAt: string;
|
||||||
|
}): CompetitionGameView {
|
||||||
|
return {
|
||||||
|
id: id as GameId,
|
||||||
|
seriesId: parentSeriesId,
|
||||||
|
gameSlotId: `${id}-slot` as GameSlotId,
|
||||||
|
ordinal,
|
||||||
|
displayNumber,
|
||||||
|
evidence: { type: "legacy", legacyReference: id },
|
||||||
|
teams: {
|
||||||
|
blue: { side: "blue", teamId: blueTeamId },
|
||||||
|
red: { side: "red", teamId: redTeamId },
|
||||||
|
},
|
||||||
|
winnerTeamId,
|
||||||
|
startedAt,
|
||||||
|
durationSeconds: 1_875,
|
||||||
|
participants: [],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function seriesId(value: string): SeriesId {
|
||||||
|
return value as SeriesId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function teamId(value: string): TeamId {
|
||||||
|
return value as TeamId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function withSchedule<T extends SeriesProjection>(
|
||||||
|
series: T,
|
||||||
|
schedule: {
|
||||||
|
date: string;
|
||||||
|
time: string | null;
|
||||||
|
timeZone: "Asia/Seoul";
|
||||||
|
},
|
||||||
|
): T & { schedule: typeof schedule } {
|
||||||
|
return { ...series, schedule };
|
||||||
|
}
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
const stylesheet = await readFile(
|
||||||
|
new URL("../src/index.css", import.meta.url),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
const BRAND_COLORS = {
|
||||||
|
coral: "oklch(0.708008 0.234375 24)",
|
||||||
|
violet: "oklch(0.481934 0.285938 285)",
|
||||||
|
gold: "oklch(0.853027 0.2 90)",
|
||||||
|
cyan: "oklch(70% 0.14523 200)",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
test("defines each brand color once as a primitive token", () => {
|
||||||
|
for (const [name, value] of Object.entries(BRAND_COLORS)) {
|
||||||
|
assert.match(
|
||||||
|
stylesheet,
|
||||||
|
new RegExp(`--color-brand-${name}: ${escapeRegExp(value)};`),
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
stylesheet.split(value).length - 1,
|
||||||
|
1,
|
||||||
|
`${name} should have one literal source`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("maps the light theme semantic roles to the brand primitives", () => {
|
||||||
|
const lightTheme = cssBlocksForSelector('[data-theme="light"]');
|
||||||
|
const mappings = [
|
||||||
|
["--color-primary", "--color-brand-coral"],
|
||||||
|
["--color-secondary", "--color-brand-violet"],
|
||||||
|
["--color-accent", "--color-brand-gold"],
|
||||||
|
["--color-info", "--color-brand-cyan"],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
for (const [semanticToken, primitiveToken] of mappings) {
|
||||||
|
assert.match(
|
||||||
|
lightTheme,
|
||||||
|
new RegExp(
|
||||||
|
`${escapeRegExp(semanticToken)}: var\\(${escapeRegExp(primitiveToken)}\\);`,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps coral scopes without overriding the global dark primary", () => {
|
||||||
|
assert.match(
|
||||||
|
stylesheet,
|
||||||
|
/--color-bracket-winner: var\(--color-brand-coral\);/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
stylesheet,
|
||||||
|
/\.competition-series-history\s*{\s*--color-primary: var\(--color-brand-coral\);\s*}/,
|
||||||
|
);
|
||||||
|
|
||||||
|
const darkTheme = cssBlocksForSelector('[data-theme="dark"]');
|
||||||
|
assert.doesNotMatch(darkTheme, /--color-primary/);
|
||||||
|
});
|
||||||
|
|
||||||
|
function cssBlocksForSelector(selector: string): string {
|
||||||
|
const blocks = stylesheet.matchAll(
|
||||||
|
new RegExp(`${escapeRegExp(selector)}\\s*{([^}]*)}`, "g"),
|
||||||
|
);
|
||||||
|
const contents = [...blocks].map((match) => match[1] ?? "").join("\n");
|
||||||
|
assert.notEqual(contents, "", `${selector} should have a CSS block`);
|
||||||
|
return contents;
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeRegExp(value: string): string {
|
||||||
|
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||||
|
}
|
||||||
@@ -0,0 +1,146 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import type { SeriesId } from "@lolympus/contracts";
|
||||||
|
import {
|
||||||
|
bracketConnectorKey,
|
||||||
|
getBracketConnectorColorClass,
|
||||||
|
getBracketFocusState,
|
||||||
|
getHorizontalOverflowCues,
|
||||||
|
type BracketFocusConnector,
|
||||||
|
} from "../src/components/competition/double-elimination-bracket-interaction.ts";
|
||||||
|
|
||||||
|
const A = seriesId("a");
|
||||||
|
const B = seriesId("b");
|
||||||
|
const C = seriesId("c");
|
||||||
|
const D = seriesId("d");
|
||||||
|
const E = seriesId("e");
|
||||||
|
|
||||||
|
const CONNECTORS: BracketFocusConnector[] = [
|
||||||
|
connector(A, "winner", B, "A"),
|
||||||
|
connector(B, "winner", C, "A"),
|
||||||
|
connector(B, "loser", D, "B"),
|
||||||
|
connector(D, "winner", E, "A"),
|
||||||
|
];
|
||||||
|
|
||||||
|
test("focuses directly incoming and outgoing routes plus adjacent matches", () => {
|
||||||
|
const focus = getBracketFocusState(CONNECTORS, B);
|
||||||
|
|
||||||
|
assert.deepEqual([...focus.seriesIds].sort(), [A, B, C, D].sort());
|
||||||
|
assert.deepEqual(
|
||||||
|
[...focus.connectorKeys].sort(),
|
||||||
|
CONNECTORS.slice(0, 3).map(bracketConnectorKey).sort(),
|
||||||
|
);
|
||||||
|
assert.equal(focus.connectorKeys.has(bracketConnectorKey(CONNECTORS[3])), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns a neutral focus state when no match is active", () => {
|
||||||
|
const focus = getBracketFocusState(CONNECTORS, null);
|
||||||
|
|
||||||
|
assert.equal(focus.seriesIds.size, 0);
|
||||||
|
assert.equal(focus.connectorKeys.size, 0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps both grand-final carry-over routes focused", () => {
|
||||||
|
const grandFinal = seriesId("grand-final");
|
||||||
|
const resetFinal = seriesId("reset-final");
|
||||||
|
const resetConnectors = [
|
||||||
|
connector(grandFinal, "slot-a", resetFinal, "A"),
|
||||||
|
connector(grandFinal, "slot-b", resetFinal, "B"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const focus = getBracketFocusState(resetConnectors, grandFinal);
|
||||||
|
|
||||||
|
assert.deepEqual([...focus.seriesIds].sort(), [grandFinal, resetFinal].sort());
|
||||||
|
assert.equal(focus.connectorKeys.size, 2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps both grand-final carry-over routes focused from the reset final", () => {
|
||||||
|
const grandFinal = seriesId("grand-final");
|
||||||
|
const resetFinal = seriesId("reset-final");
|
||||||
|
const resetConnectors = [
|
||||||
|
connector(grandFinal, "slot-b", resetFinal, "B"),
|
||||||
|
connector(grandFinal, "slot-a", resetFinal, "A"),
|
||||||
|
];
|
||||||
|
|
||||||
|
const focus = getBracketFocusState(resetConnectors, resetFinal);
|
||||||
|
|
||||||
|
assert.deepEqual([...focus.seriesIds].sort(), [grandFinal, resetFinal].sort());
|
||||||
|
assert.deepEqual(
|
||||||
|
[...focus.connectorKeys].sort(),
|
||||||
|
resetConnectors.map(bracketConnectorKey).sort(),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses the brand coral for winner routes without losing patterned route semantics", () => {
|
||||||
|
assert.equal(getBracketConnectorColorClass("winner"), "text-bracket-winner");
|
||||||
|
assert.equal(
|
||||||
|
getBracketConnectorColorClass("winner", true),
|
||||||
|
"text-bracket-winner",
|
||||||
|
);
|
||||||
|
assert.equal(getBracketConnectorColorClass("loser"), "text-base-content/55");
|
||||||
|
assert.equal(
|
||||||
|
getBracketConnectorColorClass("loser", true),
|
||||||
|
"text-base-content",
|
||||||
|
);
|
||||||
|
assert.equal(getBracketConnectorColorClass("reset"), "text-base-content/55");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("derives truthful horizontal overflow cues at each scroll position", () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 0, scrollWidth: 1600, clientWidth: 1200 }),
|
||||||
|
{ showStart: false, showEnd: true },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({
|
||||||
|
scrollLeft: 200,
|
||||||
|
scrollWidth: 1600,
|
||||||
|
clientWidth: 1200,
|
||||||
|
}),
|
||||||
|
{ showStart: true, showEnd: true },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({
|
||||||
|
scrollLeft: 400,
|
||||||
|
scrollWidth: 1600,
|
||||||
|
clientWidth: 1200,
|
||||||
|
}),
|
||||||
|
{ showStart: true, showEnd: false },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 0, scrollWidth: 1200, clientWidth: 1200 }),
|
||||||
|
{ showStart: false, showEnd: false },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 1, scrollWidth: 1600, clientWidth: 1200 }),
|
||||||
|
{ showStart: false, showEnd: true },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 1.01, scrollWidth: 1600, clientWidth: 1200 }),
|
||||||
|
{ showStart: true, showEnd: true },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 399, scrollWidth: 1600, clientWidth: 1200 }),
|
||||||
|
{ showStart: true, showEnd: false },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 398.99, scrollWidth: 1600, clientWidth: 1200 }),
|
||||||
|
{ showStart: true, showEnd: true },
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
getHorizontalOverflowCues({ scrollLeft: 0, scrollWidth: 1201, clientWidth: 1200 }),
|
||||||
|
{ showStart: false, showEnd: false },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
function connector(
|
||||||
|
fromSeriesId: SeriesId,
|
||||||
|
select: BracketFocusConnector["select"],
|
||||||
|
toSeriesId: SeriesId,
|
||||||
|
toSlot: BracketFocusConnector["toSlot"],
|
||||||
|
): BracketFocusConnector {
|
||||||
|
return { fromSeriesId, select, toSeriesId, toSlot };
|
||||||
|
}
|
||||||
|
|
||||||
|
function seriesId(value: string): SeriesId {
|
||||||
|
return value as SeriesId;
|
||||||
|
}
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,134 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
import {
|
||||||
|
DEFAULT_LANE_CHECKPOINT,
|
||||||
|
pairLaneParticipants,
|
||||||
|
resolveCheckpointComparison,
|
||||||
|
} from "../src/lib/internal-game-matchups.ts";
|
||||||
|
|
||||||
|
function participant(
|
||||||
|
name: string,
|
||||||
|
side: "blue" | "red",
|
||||||
|
teamPosition: string,
|
||||||
|
gold: number,
|
||||||
|
cs: number,
|
||||||
|
xp: number,
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
name,
|
||||||
|
side,
|
||||||
|
teamPosition,
|
||||||
|
checkpoints: {
|
||||||
|
at15: {
|
||||||
|
timestamp: 900,
|
||||||
|
gold,
|
||||||
|
cs,
|
||||||
|
xp,
|
||||||
|
kills: side === "blue" ? 2 : 1,
|
||||||
|
deaths: side === "blue" ? 1 : 2,
|
||||||
|
assists: 3,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
test("pairLaneParticipants matches shuffled players by normalized team position", () => {
|
||||||
|
const blue = [
|
||||||
|
participant("Blue ADC", "blue", "BOTTOM", 6_000, 120, 7_000),
|
||||||
|
participant("Blue Top", "blue", "TOP", 5_500, 110, 6_800),
|
||||||
|
participant("Blue Mid", "blue", "MID", 6_200, 115, 7_100),
|
||||||
|
];
|
||||||
|
const red = [
|
||||||
|
participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900),
|
||||||
|
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
|
||||||
|
participant("Red ADC", "red", "ADC", 5_800, 116, 6_850),
|
||||||
|
];
|
||||||
|
|
||||||
|
const pairs = pairLaneParticipants(blue, red);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
pairs.map((pair) => [pair.position, pair.blue?.name, pair.red?.name]),
|
||||||
|
[
|
||||||
|
["TOP", "Blue Top", "Red Top"],
|
||||||
|
["MIDDLE", "Blue Mid", "Red Mid"],
|
||||||
|
["BOTTOM", "Blue ADC", "Red ADC"],
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pairLaneParticipants leaves a duplicated role ambiguous instead of pairing by index", () => {
|
||||||
|
const blue = [
|
||||||
|
participant("Blue Top A", "blue", "TOP", 5_500, 110, 6_800),
|
||||||
|
participant("Blue Top B", "blue", "TOP", 5_000, 100, 6_200),
|
||||||
|
];
|
||||||
|
const red = [
|
||||||
|
participant("Red Top", "red", "TOP", 5_300, 105, 6_600),
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.deepEqual(pairLaneParticipants(blue, red), [
|
||||||
|
{
|
||||||
|
position: "TOP",
|
||||||
|
blue: null,
|
||||||
|
red: red[0],
|
||||||
|
ambiguousBlue: true,
|
||||||
|
ambiguousRed: false,
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveCheckpointComparison calculates blue-side GD, CSD, and XPD", () => {
|
||||||
|
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
|
||||||
|
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
|
||||||
|
|
||||||
|
const comparison = resolveCheckpointComparison(blue, red, "at15");
|
||||||
|
|
||||||
|
assert.deepEqual(comparison, {
|
||||||
|
blue: blue.checkpoints.at15,
|
||||||
|
red: red.checkpoints.at15,
|
||||||
|
goldDiff: 300,
|
||||||
|
csDiff: 6,
|
||||||
|
xpDiff: 200,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("resolveCheckpointComparison returns null when either checkpoint is unavailable", () => {
|
||||||
|
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
|
||||||
|
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
|
||||||
|
|
||||||
|
assert.equal(resolveCheckpointComparison(blue, red, "at10"), null);
|
||||||
|
assert.equal(resolveCheckpointComparison(blue, null, "at15"), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the lane panel defaults to 15 minutes and supports an available 10-minute comparison", () => {
|
||||||
|
assert.equal(DEFAULT_LANE_CHECKPOINT, "at15");
|
||||||
|
|
||||||
|
const blue = participant("Blue Mid", "blue", "MIDDLE", 6_200, 115, 7_100);
|
||||||
|
const red = participant("Red Mid", "red", "MIDDLE", 5_900, 109, 6_900);
|
||||||
|
blue.checkpoints.at10 = {
|
||||||
|
timestamp: 590,
|
||||||
|
gold: 4_000,
|
||||||
|
cs: 75,
|
||||||
|
xp: 4_600,
|
||||||
|
kills: 1,
|
||||||
|
deaths: 0,
|
||||||
|
assists: 2,
|
||||||
|
};
|
||||||
|
red.checkpoints.at10 = {
|
||||||
|
timestamp: 590,
|
||||||
|
gold: 3_700,
|
||||||
|
cs: 69,
|
||||||
|
xp: 4_450,
|
||||||
|
kills: 0,
|
||||||
|
deaths: 1,
|
||||||
|
assists: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.deepEqual(resolveCheckpointComparison(blue, red, "at10"), {
|
||||||
|
blue: blue.checkpoints.at10,
|
||||||
|
red: red.checkpoints.at10,
|
||||||
|
goldDiff: 300,
|
||||||
|
csDiff: 6,
|
||||||
|
xpDiff: 150,
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import { selectInternalMatchGame } from "../src/lib/internal-match-game-selection.ts";
|
||||||
|
|
||||||
|
test("selects only the Game explicitly requested by its global number", () => {
|
||||||
|
const firstGame = { gameNumber: 1, id: "first" };
|
||||||
|
const requestedGame = { gameNumber: 17, id: "requested" };
|
||||||
|
const games = [firstGame, requestedGame];
|
||||||
|
|
||||||
|
assert.equal(selectInternalMatchGame(games, 17), requestedGame);
|
||||||
|
assert.equal(selectInternalMatchGame(games, 99), null);
|
||||||
|
assert.equal(selectInternalMatchGame(games, Number.NaN), null);
|
||||||
|
});
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
|
||||||
|
import {
|
||||||
|
dragonTypeLabel,
|
||||||
|
filterTimelineEvents,
|
||||||
|
normalizeObjectiveEvents,
|
||||||
|
normalizeTimelineEvents,
|
||||||
|
projectObjectiveMarkers,
|
||||||
|
selectTimelineEventSource,
|
||||||
|
summarizeDragonTypes,
|
||||||
|
} from "../src/lib/internal-match-timeline.ts";
|
||||||
|
|
||||||
|
test("dragonTypeLabel maps Riot dragon subtypes to Korean labels", () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
[
|
||||||
|
"AIR_DRAGON",
|
||||||
|
"EARTH_DRAGON",
|
||||||
|
"WATER_DRAGON",
|
||||||
|
"FIRE_DRAGON",
|
||||||
|
"HEXTECH_DRAGON",
|
||||||
|
"CHEMTECH_DRAGON",
|
||||||
|
"ELDER_DRAGON",
|
||||||
|
].map(dragonTypeLabel),
|
||||||
|
["바람", "대지", "바다", "화염", "마법공학", "화학공학", "장로"],
|
||||||
|
);
|
||||||
|
assert.equal(dragonTypeLabel("UNKNOWN_DRAGON"), null);
|
||||||
|
assert.equal(dragonTypeLabel(undefined), null);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("normalizeObjectiveEvents sorts events and adds conservative Korean labels", () => {
|
||||||
|
const events = normalizeObjectiveEvents([
|
||||||
|
{ timestamp: 1_443, side: "blue", type: "baron" },
|
||||||
|
{
|
||||||
|
timestamp: 339,
|
||||||
|
side: "blue",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "EARTH_DRAGON",
|
||||||
|
},
|
||||||
|
{ timestamp: 963, side: "red", type: "riftHerald" },
|
||||||
|
{
|
||||||
|
timestamp: 1_356,
|
||||||
|
side: "red",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "UNKNOWN_DRAGON",
|
||||||
|
},
|
||||||
|
{ timestamp: 530, side: "blue", type: "voidGrub" },
|
||||||
|
{ timestamp: 1_600, side: "red", type: "elderDragon" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
events.map(({ timestamp, label, markerLabel }) => ({
|
||||||
|
timestamp,
|
||||||
|
label,
|
||||||
|
markerLabel,
|
||||||
|
})),
|
||||||
|
[
|
||||||
|
{ timestamp: 339, label: "대지 드래곤", markerLabel: "대지" },
|
||||||
|
{ timestamp: 530, label: "공허 유충", markerLabel: "유충" },
|
||||||
|
{ timestamp: 963, label: "협곡의 전령", markerLabel: "전령" },
|
||||||
|
{ timestamp: 1_356, label: "드래곤", markerLabel: "용" },
|
||||||
|
{ timestamp: 1_443, label: "바론", markerLabel: "바론" },
|
||||||
|
{ timestamp: 1_600, label: "장로 드래곤", markerLabel: "장로" },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("summarizeDragonTypes groups repeated dragon types per side in event order", () => {
|
||||||
|
const events = normalizeObjectiveEvents([
|
||||||
|
{
|
||||||
|
timestamp: 300,
|
||||||
|
side: "blue",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "FIRE_DRAGON",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 600,
|
||||||
|
side: "red",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "WATER_DRAGON",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 900,
|
||||||
|
side: "blue",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "FIRE_DRAGON",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 1_200,
|
||||||
|
side: "blue",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "HEXTECH_DRAGON",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 1_500,
|
||||||
|
side: "red",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "UNKNOWN_DRAGON",
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(summarizeDragonTypes(events, "blue"), [
|
||||||
|
{ label: "화염", count: 2 },
|
||||||
|
{ label: "마법공학", count: 1 },
|
||||||
|
]);
|
||||||
|
assert.deepEqual(summarizeDragonTypes(events, "red"), [
|
||||||
|
{ label: "바다", count: 1 },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("projectObjectiveMarkers anchors events to the latest available chart value", () => {
|
||||||
|
const events = normalizeObjectiveEvents([
|
||||||
|
{ timestamp: 10, side: "blue", type: "voidGrub" },
|
||||||
|
{ timestamp: 90, side: "red", type: "riftHerald" },
|
||||||
|
{ timestamp: 180, side: "blue", type: "baron" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
projectObjectiveMarkers(events, [
|
||||||
|
{ timestamp: 0, value: 0 },
|
||||||
|
{ timestamp: 60, value: 100 },
|
||||||
|
{ timestamp: 120, value: 80 },
|
||||||
|
]).map(({ timestamp, value }) => ({ timestamp, value })),
|
||||||
|
[
|
||||||
|
{ timestamp: 10, value: 0 },
|
||||||
|
{ timestamp: 90, value: 100 },
|
||||||
|
{ timestamp: 180, value: 80 },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("normalizeTimelineEvents labels and sorts objectives, kills, and structures", () => {
|
||||||
|
const events = normalizeTimelineEvents([
|
||||||
|
{
|
||||||
|
timestamp: 700,
|
||||||
|
side: "blue",
|
||||||
|
type: "tower",
|
||||||
|
killerParticipantId: 1,
|
||||||
|
towerType: "OUTER_TURRET",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 500,
|
||||||
|
side: "red",
|
||||||
|
type: "championKill",
|
||||||
|
killerParticipantId: 6,
|
||||||
|
victimParticipantId: 1,
|
||||||
|
assistingParticipantIds: [7, 8],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 300,
|
||||||
|
side: "blue",
|
||||||
|
type: "dragon",
|
||||||
|
monsterSubType: "FIRE_DRAGON",
|
||||||
|
},
|
||||||
|
{ timestamp: 800, side: "red", type: "inhibitor" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
events.map(({ timestamp, category, label, markerLabel }) => ({
|
||||||
|
timestamp,
|
||||||
|
category,
|
||||||
|
label,
|
||||||
|
markerLabel,
|
||||||
|
})),
|
||||||
|
[
|
||||||
|
{
|
||||||
|
timestamp: 300,
|
||||||
|
category: "objective",
|
||||||
|
label: "화염 드래곤",
|
||||||
|
markerLabel: "화염",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 500,
|
||||||
|
category: "kill",
|
||||||
|
label: "챔피언 처치",
|
||||||
|
markerLabel: "킬",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 700,
|
||||||
|
category: "structure",
|
||||||
|
label: "포탑 파괴",
|
||||||
|
markerLabel: "포탑",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
timestamp: 800,
|
||||||
|
category: "structure",
|
||||||
|
label: "억제기 파괴",
|
||||||
|
markerLabel: "억제기",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
);
|
||||||
|
assert.equal(events[1].killerParticipantId, 6);
|
||||||
|
assert.equal(events[1].victimParticipantId, 1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("selectTimelineEventSource falls back to objective events during rolling updates", () => {
|
||||||
|
const objectives = [
|
||||||
|
{ timestamp: 300, side: "blue" as const, type: "voidGrub" as const },
|
||||||
|
];
|
||||||
|
const timeline = [
|
||||||
|
{ timestamp: 400, side: "red" as const, type: "championKill" as const },
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.equal(selectTimelineEventSource(timeline, objectives), timeline);
|
||||||
|
assert.equal(selectTimelineEventSource([], objectives), objectives);
|
||||||
|
assert.equal(selectTimelineEventSource(undefined, objectives), objectives);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("filterTimelineEvents filters event categories without changing order", () => {
|
||||||
|
const events = normalizeTimelineEvents([
|
||||||
|
{ timestamp: 300, side: "blue", type: "dragon" },
|
||||||
|
{ timestamp: 500, side: "red", type: "championKill" },
|
||||||
|
{ timestamp: 700, side: "blue", type: "tower" },
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
filterTimelineEvents(events, "all").map((event) => event.timestamp),
|
||||||
|
[300, 500, 700],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
filterTimelineEvents(events, "kill").map((event) => event.timestamp),
|
||||||
|
[500],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
filterTimelineEvents(events, "structure").map((event) => event.timestamp),
|
||||||
|
[700],
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import {
|
||||||
|
createMatchDetailTabSearchParams,
|
||||||
|
createMatchDetailTabs,
|
||||||
|
moveMatchDetailTabFocus,
|
||||||
|
resolveMatchDetailTab,
|
||||||
|
} from "../src/components/competition/match-detail-tabs.ts";
|
||||||
|
|
||||||
|
test("uses tabs only in progress or when finished and exposes operations only to managers", () => {
|
||||||
|
assert.deepEqual(
|
||||||
|
createMatchDetailTabs({ status: "recruiting", canManage: true }),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
createMatchDetailTabs({ status: "team-built", canManage: true }),
|
||||||
|
[],
|
||||||
|
);
|
||||||
|
|
||||||
|
const publicTabs = createMatchDetailTabs({
|
||||||
|
status: "in-progress",
|
||||||
|
canManage: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
publicTabs.map((tab) => tab.id),
|
||||||
|
["bracket", "games", "teams", "info"],
|
||||||
|
);
|
||||||
|
assert.deepEqual(
|
||||||
|
publicTabs.map((tab) => tab.label),
|
||||||
|
["대진표·순위", "경기 일정·결과", "팀", "안내"],
|
||||||
|
);
|
||||||
|
|
||||||
|
const managerTabs = createMatchDetailTabs({
|
||||||
|
status: "finished",
|
||||||
|
canManage: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(
|
||||||
|
managerTabs.map((tab) => tab.id),
|
||||||
|
["bracket", "games", "teams", "info", "ops"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back to the bracket for missing, invalid, or unauthorized tabs", () => {
|
||||||
|
const publicTabs = createMatchDetailTabs({
|
||||||
|
status: "in-progress",
|
||||||
|
canManage: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(resolveMatchDetailTab(null, []), null);
|
||||||
|
assert.equal(resolveMatchDetailTab(null, publicTabs), "bracket");
|
||||||
|
assert.equal(resolveMatchDetailTab("unknown", publicTabs), "bracket");
|
||||||
|
assert.equal(resolveMatchDetailTab("ops", publicTabs), "bracket");
|
||||||
|
assert.equal(resolveMatchDetailTab("games", publicTabs), "games");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("updates the tab query without mutating or dropping unrelated parameters", () => {
|
||||||
|
const current = new URLSearchParams("season=2026&tab=teams&from=history");
|
||||||
|
const next = createMatchDetailTabSearchParams(current, "games");
|
||||||
|
|
||||||
|
assert.equal(next.get("tab"), "games");
|
||||||
|
assert.equal(next.get("season"), "2026");
|
||||||
|
assert.equal(next.get("from"), "history");
|
||||||
|
assert.equal(current.get("tab"), "teams");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("moves tab focus with wrapping arrow keys and boundary keys", () => {
|
||||||
|
const tabs = createMatchDetailTabs({
|
||||||
|
status: "in-progress",
|
||||||
|
canManage: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
assert.equal(moveMatchDetailTabFocus(tabs, "bracket", "ArrowRight"), "games");
|
||||||
|
assert.equal(moveMatchDetailTabFocus(tabs, "bracket", "ArrowLeft"), "info");
|
||||||
|
assert.equal(moveMatchDetailTabFocus(tabs, "info", "ArrowRight"), "bracket");
|
||||||
|
assert.equal(moveMatchDetailTabFocus(tabs, "teams", "Home"), "bracket");
|
||||||
|
assert.equal(moveMatchDetailTabFocus(tabs, "games", "End"), "info");
|
||||||
|
});
|
||||||
@@ -3,8 +3,20 @@ import test from "node:test";
|
|||||||
import {
|
import {
|
||||||
getTeamProgressErrorContent,
|
getTeamProgressErrorContent,
|
||||||
isConsistentTeamProgressSnapshot,
|
isConsistentTeamProgressSnapshot,
|
||||||
|
shouldOfferTeamSelection,
|
||||||
} from "../src/pages/match-team-progress-state.ts";
|
} from "../src/pages/match-team-progress-state.ts";
|
||||||
|
|
||||||
|
test("offers team selection when the caller cannot be resolved to a team", () => {
|
||||||
|
assert.equal(shouldOfferTeamSelection([{ status: 401 }], undefined), true);
|
||||||
|
assert.equal(shouldOfferTeamSelection([{ status: 403 }], undefined), true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not offer team selection once a team is named or the failure is unrelated", () => {
|
||||||
|
assert.equal(shouldOfferTeamSelection([{ status: 401 }], "team-a"), false);
|
||||||
|
assert.equal(shouldOfferTeamSelection([{ status: 404 }], undefined), false);
|
||||||
|
assert.equal(shouldOfferTeamSelection([{ status: 503 }], undefined), false);
|
||||||
|
});
|
||||||
|
|
||||||
test("only accepts Competition and team snapshots with the same revision", () => {
|
test("only accepts Competition and team snapshots with the same revision", () => {
|
||||||
assert.equal(
|
assert.equal(
|
||||||
isConsistentTeamProgressSnapshot({ revision: 7 }, { revision: 7 }),
|
isConsistentTeamProgressSnapshot({ revision: 7 }, { revision: 7 }),
|
||||||
|
|||||||
@@ -0,0 +1,448 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import type {
|
||||||
|
BracketRoundView,
|
||||||
|
CompetitionTeamMemberView,
|
||||||
|
CompetitionFactId,
|
||||||
|
GameSlotId,
|
||||||
|
SeriesId,
|
||||||
|
SeriesProjection,
|
||||||
|
TeamId,
|
||||||
|
TeamTournamentCodeView,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import {
|
||||||
|
copyTournamentCode,
|
||||||
|
createTeamSeriesGroups,
|
||||||
|
getTeamSeriesDisplayLabel,
|
||||||
|
getTeamSeriesPresentation,
|
||||||
|
getNextTournamentCodeExpiryDelay,
|
||||||
|
getTournamentCodeExpiryLabel,
|
||||||
|
getTournamentCodeCopyLabel,
|
||||||
|
getTournamentCodePresentation,
|
||||||
|
sortCompletedTeamSeries,
|
||||||
|
sortTeamMembersForRoster,
|
||||||
|
} from "../src/pages/match-team-progress-view.ts";
|
||||||
|
|
||||||
|
const TEAM_A = "team-a" as TeamId;
|
||||||
|
const TEAM_B = "team-b" as TeamId;
|
||||||
|
|
||||||
|
test("groups only matching tournament codes under each active Series", () => {
|
||||||
|
const earlier = readySeries("series-earlier", 1);
|
||||||
|
const later = readySeries("series-later", 2);
|
||||||
|
const groups = createTeamSeriesGroups(
|
||||||
|
[later, earlier],
|
||||||
|
[
|
||||||
|
tournamentCode("later-2", later.seriesId, 2, 20),
|
||||||
|
tournamentCode("orphan", "series-orphan" as SeriesId, 1, 99),
|
||||||
|
tournamentCode("earlier-1", earlier.seriesId, 1, 17),
|
||||||
|
tournamentCode("later-1", later.seriesId, 1, 19),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
groups.map(({ series, codes }) => ({
|
||||||
|
seriesId: series.seriesId,
|
||||||
|
gameSlotIds: codes.map(({ gameSlotId }) => gameSlotId),
|
||||||
|
})),
|
||||||
|
[
|
||||||
|
{ seriesId: earlier.seriesId, gameSlotIds: ["earlier-1"] },
|
||||||
|
{ seriesId: later.seriesId, gameSlotIds: ["later-1", "later-2"] },
|
||||||
|
],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses bracket match names while keeping global game numbers secondary", () => {
|
||||||
|
const opening = readySeries("upper-opening-2", 1, "WB_R1_M2");
|
||||||
|
const upperLater = readySeries("upper-final", 3, "WB_FINAL");
|
||||||
|
const lower: SeriesProjection = {
|
||||||
|
...readySeries("lower-opening", 4, "LB_R1_M1"),
|
||||||
|
stage: { type: "lower", roundNumber: 1, displayOrder: 4 },
|
||||||
|
};
|
||||||
|
const rounds: BracketRoundView[] = [
|
||||||
|
round("upper", 1, 1, ["upper-opening-1", opening.seriesId]),
|
||||||
|
round("upper", 3, 3, [upperLater.seriesId]),
|
||||||
|
round("lower", 1, 4, [lower.seriesId]),
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
getTeamSeriesDisplayLabel(opening, rounds),
|
||||||
|
"브래킷 1R · 2경기",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
getTeamSeriesDisplayLabel(upperLater, rounds),
|
||||||
|
"브래킷 상위 3R",
|
||||||
|
);
|
||||||
|
assert.equal(getTeamSeriesDisplayLabel(lower, rounds), "브래킷 하위 1R");
|
||||||
|
|
||||||
|
const assignment = tournamentCode(
|
||||||
|
"final-1",
|
||||||
|
upperLater.seriesId,
|
||||||
|
1,
|
||||||
|
19,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
getTournamentCodeCopyLabel(assignment, "브래킷 상위 3R"),
|
||||||
|
"브래킷 상위 3R 1세트 토너먼트 코드 복사 (전체 19번 게임)",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("hides misleading scores before play and for adjudicated outcomes", () => {
|
||||||
|
const ready = readySeries("ready", 1);
|
||||||
|
const walkover = completedSeries(
|
||||||
|
"walkover",
|
||||||
|
"2026-07-13T10:00:00.000Z",
|
||||||
|
2,
|
||||||
|
);
|
||||||
|
const played: Extract<SeriesProjection, { status: "completed" }> = {
|
||||||
|
...walkover,
|
||||||
|
code: "PLAYED",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: 2 },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: 1 },
|
||||||
|
],
|
||||||
|
outcome: {
|
||||||
|
type: "played",
|
||||||
|
winnerTeamId: TEAM_A,
|
||||||
|
loserTeamId: TEAM_B,
|
||||||
|
decidedByGameIds: [],
|
||||||
|
completedAt: "2026-07-13T11:00:00.000Z",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
assert.deepEqual(getTeamSeriesPresentation(ready), {
|
||||||
|
label: "경기 가능",
|
||||||
|
tone: "ready",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
for (const [status, expected] of [
|
||||||
|
["inactive", { label: "비활성", tone: "muted", showScore: false }],
|
||||||
|
["waiting", { label: "대진 대기", tone: "muted", showScore: false }],
|
||||||
|
["in-progress", { label: "진행 중", tone: "live", showScore: true }],
|
||||||
|
] as const) {
|
||||||
|
assert.deepEqual(
|
||||||
|
getTeamSeriesPresentation({ ...ready, status } as SeriesProjection),
|
||||||
|
expected,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert.deepEqual(getTeamSeriesPresentation(walkover), {
|
||||||
|
label: "부전승",
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTeamSeriesPresentation(played), {
|
||||||
|
label: "종료",
|
||||||
|
tone: "completed",
|
||||||
|
showScore: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const adjudicatedOutcomes = [
|
||||||
|
["forfeit", "기권승"],
|
||||||
|
["administrative", "판정승"],
|
||||||
|
] as const;
|
||||||
|
for (const [type, label] of adjudicatedOutcomes) {
|
||||||
|
const series: Extract<SeriesProjection, { status: "completed" }> = {
|
||||||
|
...walkover,
|
||||||
|
outcome: {
|
||||||
|
...walkover.outcome,
|
||||||
|
type,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
assert.deepEqual(getTeamSeriesPresentation(series), {
|
||||||
|
label,
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const basis of ["played", "administrative"] as const) {
|
||||||
|
const draw: Extract<SeriesProjection, { status: "completed" }> = {
|
||||||
|
...walkover,
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: 1 },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: 1 },
|
||||||
|
],
|
||||||
|
outcome: {
|
||||||
|
type: "draw",
|
||||||
|
basis:
|
||||||
|
basis === "played"
|
||||||
|
? { type: basis, decidedByGameIds: [] }
|
||||||
|
: {
|
||||||
|
type: basis,
|
||||||
|
decisionFactId: "draw-fact" as CompetitionFactId,
|
||||||
|
},
|
||||||
|
completedAt: "2026-07-13T12:00:00.000Z",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
assert.deepEqual(getTeamSeriesPresentation(draw), {
|
||||||
|
label: "무승부",
|
||||||
|
tone: basis === "played" ? "completed" : "adjudicated",
|
||||||
|
showScore: basis === "played",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("distinguishes pending, available, expired, and used code states", () => {
|
||||||
|
const now = Date.parse("2026-07-13T12:00:00.000Z");
|
||||||
|
const pending = tournamentCode("pending", "series-a" as SeriesId, 1, 1, {
|
||||||
|
state: "pending",
|
||||||
|
code: null,
|
||||||
|
});
|
||||||
|
const available = tournamentCode(
|
||||||
|
"available",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
2,
|
||||||
|
2,
|
||||||
|
{ expiresAt: "2026-07-13T13:00:00.000Z" },
|
||||||
|
);
|
||||||
|
const expired = tournamentCode(
|
||||||
|
"expired",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
{ expiresAt: "2026-07-13T11:00:00.000Z" },
|
||||||
|
);
|
||||||
|
const used = tournamentCode("used", "series-a" as SeriesId, 4, 4, {
|
||||||
|
state: "used",
|
||||||
|
expiresAt: "2026-07-13T11:00:00.000Z",
|
||||||
|
});
|
||||||
|
const expiresNow = tournamentCode(
|
||||||
|
"expires-now",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
5,
|
||||||
|
5,
|
||||||
|
{ expiresAt: "2026-07-13T12:00:00.000Z" },
|
||||||
|
);
|
||||||
|
const noExpiry = tournamentCode(
|
||||||
|
"no-expiry",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
6,
|
||||||
|
6,
|
||||||
|
);
|
||||||
|
const invalidExpiry = tournamentCode(
|
||||||
|
"invalid-expiry",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
7,
|
||||||
|
7,
|
||||||
|
{ expiresAt: "not-a-date" },
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(pending, now), {
|
||||||
|
label: "발급 대기",
|
||||||
|
tone: "pending",
|
||||||
|
canCopy: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(available, now), {
|
||||||
|
label: "사용 가능",
|
||||||
|
tone: "available",
|
||||||
|
canCopy: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(expired, now), {
|
||||||
|
label: "만료",
|
||||||
|
tone: "expired",
|
||||||
|
canCopy: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(used, now), {
|
||||||
|
label: "사용 완료",
|
||||||
|
tone: "used",
|
||||||
|
canCopy: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(expiresNow, now), {
|
||||||
|
label: "만료",
|
||||||
|
tone: "expired",
|
||||||
|
canCopy: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(noExpiry, now), {
|
||||||
|
label: "사용 가능",
|
||||||
|
tone: "available",
|
||||||
|
canCopy: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getTournamentCodePresentation(invalidExpiry, now), {
|
||||||
|
label: "만료 정보 오류",
|
||||||
|
tone: "expired",
|
||||||
|
canCopy: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("describes tournament-code expiry according to its current state", () => {
|
||||||
|
const beforeExpiry = Date.parse("2026-07-13T12:00:00.000Z");
|
||||||
|
const atExpiry = Date.parse("2026-07-13T13:00:00.000Z");
|
||||||
|
const expiresAt = "2026-07-13T13:00:00.000Z";
|
||||||
|
const formatter = new Intl.DateTimeFormat("ko-KR", {
|
||||||
|
year: "numeric",
|
||||||
|
month: "long",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "2-digit",
|
||||||
|
minute: "2-digit",
|
||||||
|
timeZone: "Asia/Seoul",
|
||||||
|
timeZoneName: "short",
|
||||||
|
});
|
||||||
|
const formatted = formatter.format(new Date(expiresAt));
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
getTournamentCodeExpiryLabel(expiresAt, beforeExpiry),
|
||||||
|
`${formatted}까지 사용 가능`,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
getTournamentCodeExpiryLabel(expiresAt, atExpiry),
|
||||||
|
`${formatted}에 만료됨`,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
getTournamentCodeExpiryLabel("not-a-date", beforeExpiry),
|
||||||
|
"만료 시각 정보 없음",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("schedules the next code-state refresh at the nearest future expiry", () => {
|
||||||
|
const now = Date.parse("2026-07-13T12:00:00.000Z");
|
||||||
|
const first = tournamentCode("first", "series-a" as SeriesId, 1, 1, {
|
||||||
|
expiresAt: "2026-07-13T12:01:00.000Z",
|
||||||
|
});
|
||||||
|
const later = tournamentCode("later", "series-a" as SeriesId, 2, 2, {
|
||||||
|
expiresAt: "2026-07-13T13:00:00.000Z",
|
||||||
|
});
|
||||||
|
const alreadyExpired = tournamentCode(
|
||||||
|
"expired",
|
||||||
|
"series-a" as SeriesId,
|
||||||
|
3,
|
||||||
|
3,
|
||||||
|
{ expiresAt: "2026-07-13T11:00:00.000Z" },
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
getNextTournamentCodeExpiryDelay([later, alreadyExpired, first], now),
|
||||||
|
60_000,
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
getNextTournamentCodeExpiryDelay([alreadyExpired], now),
|
||||||
|
null,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns explicit game-specific clipboard success and failure feedback", async () => {
|
||||||
|
const writes: string[] = [];
|
||||||
|
const success = await copyTournamentCode(
|
||||||
|
async (value) => {
|
||||||
|
writes.push(value);
|
||||||
|
},
|
||||||
|
"KR-CODE-19",
|
||||||
|
"승자조 결승 1세트",
|
||||||
|
);
|
||||||
|
const failure = await copyTournamentCode(
|
||||||
|
async () => {
|
||||||
|
throw new Error("clipboard denied");
|
||||||
|
},
|
||||||
|
"KR-CODE-20",
|
||||||
|
"승자조 결승 2세트",
|
||||||
|
);
|
||||||
|
|
||||||
|
assert.deepEqual(writes, ["KR-CODE-19"]);
|
||||||
|
assert.deepEqual(success, {
|
||||||
|
kind: "success",
|
||||||
|
message: "승자조 결승 1세트 코드를 복사했습니다.",
|
||||||
|
});
|
||||||
|
assert.deepEqual(failure, {
|
||||||
|
kind: "error",
|
||||||
|
message:
|
||||||
|
"승자조 결승 2세트 코드를 복사하지 못했습니다. 코드를 직접 선택해 복사해 주세요.",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("sorts completed Series by most recent decision time", () => {
|
||||||
|
const older = completedSeries("older", "2026-07-12T10:00:00.000Z", 1);
|
||||||
|
const newer = completedSeries("newer", "2026-07-13T10:00:00.000Z", 2);
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
sortCompletedTeamSeries([older, newer]).map(({ seriesId }) => seriesId),
|
||||||
|
[newer.seriesId, older.seriesId],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("orders the roster by the canonical League positions", () => {
|
||||||
|
const members: CompetitionTeamMemberView[] = [
|
||||||
|
{ userId: "support" as never, displayName: "Support", assignedPosition: "SUP" },
|
||||||
|
{ userId: "top" as never, displayName: "Top", assignedPosition: "TOP" },
|
||||||
|
{ userId: "unknown" as never, displayName: "Unknown" },
|
||||||
|
{ userId: "mid" as never, displayName: "Mid", assignedPosition: "MID" },
|
||||||
|
{ userId: "jungle" as never, displayName: "Jungle", assignedPosition: "JGL" },
|
||||||
|
{ userId: "adc" as never, displayName: "Adc", assignedPosition: "ADC" },
|
||||||
|
];
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
sortTeamMembersForRoster(members).map(({ displayName }) => displayName),
|
||||||
|
["Top", "Jungle", "Mid", "Adc", "Support", "Unknown"],
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
function readySeries(
|
||||||
|
id: string,
|
||||||
|
displayOrder: number,
|
||||||
|
code = id.toUpperCase(),
|
||||||
|
): SeriesProjection {
|
||||||
|
return {
|
||||||
|
seriesId: id as SeriesId,
|
||||||
|
code,
|
||||||
|
stage: { type: "upper", roundNumber: displayOrder, displayOrder },
|
||||||
|
rule: { type: "first-to", winsRequired: 2, maxGames: 3 },
|
||||||
|
status: "ready",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedSeries(
|
||||||
|
id: string,
|
||||||
|
completedAt: string,
|
||||||
|
displayOrder: number,
|
||||||
|
): Extract<SeriesProjection, { status: "completed" }> {
|
||||||
|
return {
|
||||||
|
...readySeries(id, displayOrder),
|
||||||
|
status: "completed",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: 0 },
|
||||||
|
],
|
||||||
|
outcome: {
|
||||||
|
type: "walkover",
|
||||||
|
winnerTeamId: TEAM_A,
|
||||||
|
loserTeamId: TEAM_B,
|
||||||
|
decisionFactId: `${id}-fact` as CompetitionFactId,
|
||||||
|
completedAt,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function tournamentCode(
|
||||||
|
id: string,
|
||||||
|
seriesId: SeriesId,
|
||||||
|
ordinal: number,
|
||||||
|
displayNumber: number,
|
||||||
|
overrides: Partial<TeamTournamentCodeView> = {},
|
||||||
|
): TeamTournamentCodeView {
|
||||||
|
return {
|
||||||
|
gameSlotId: id as GameSlotId,
|
||||||
|
seriesId,
|
||||||
|
ordinal,
|
||||||
|
displayNumber,
|
||||||
|
state: "reserved",
|
||||||
|
code: `KR-${id}`,
|
||||||
|
expiresAt: null,
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(
|
||||||
|
stage: BracketRoundView["stage"],
|
||||||
|
roundNumber: number,
|
||||||
|
displayOrder: number,
|
||||||
|
seriesIds: Array<string | SeriesId>,
|
||||||
|
): BracketRoundView {
|
||||||
|
return {
|
||||||
|
stage,
|
||||||
|
roundNumber,
|
||||||
|
displayOrder,
|
||||||
|
label: `${stage}-${roundNumber}`,
|
||||||
|
seriesIds: seriesIds.map((id) => id as SeriesId),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readFile } from "node:fs/promises";
|
||||||
|
import test from "node:test";
|
||||||
|
import { SERIES_SCORE_CARD_GEOMETRY } from "../src/components/competition/series-score-card-geometry.ts";
|
||||||
|
|
||||||
|
const component = await readFile(
|
||||||
|
new URL(
|
||||||
|
"../src/components/competition/SeriesScoreCard.tsx",
|
||||||
|
import.meta.url,
|
||||||
|
),
|
||||||
|
"utf8",
|
||||||
|
);
|
||||||
|
|
||||||
|
test("keeps bracket entry rows equal by overlaying their divider", () => {
|
||||||
|
assert.equal(
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.height -
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.borderWidth * 2 -
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.headerHeight,
|
||||||
|
SERIES_SCORE_CARD_GEOMETRY.entryHeight * 2,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/className=\{\s*isBracket\s*\?\s*"relative"\s*:\s*"divide-y divide-base-content\/8"\s*\}/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/className="pointer-events-none absolute inset-x-0 border-t border-base-content\/8"/,
|
||||||
|
);
|
||||||
|
assert.match(
|
||||||
|
component,
|
||||||
|
/style=\{\{ top: SERIES_SCORE_CARD_GEOMETRY\.entryHeight \}\}/,
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import type {
|
||||||
|
CompetitionFactId,
|
||||||
|
SeriesId,
|
||||||
|
SeriesProjection,
|
||||||
|
TeamId,
|
||||||
|
} from "@lolympus/contracts";
|
||||||
|
import {
|
||||||
|
formatSeriesScore,
|
||||||
|
getSeriesScoreCardAccessibleLabel,
|
||||||
|
getSeriesScoreCardIdentity,
|
||||||
|
getSeriesScoreCardPresentation,
|
||||||
|
} from "../src/components/competition/series-score-card-model.ts";
|
||||||
|
|
||||||
|
const TEAM_A = "team-a" as TeamId;
|
||||||
|
const TEAM_B = "team-b" as TeamId;
|
||||||
|
|
||||||
|
test("presents future and active Series with distinct status hierarchy", () => {
|
||||||
|
const inactive = pendingSeries("inactive", "inactive");
|
||||||
|
const waiting = pendingSeries("waiting", "waiting");
|
||||||
|
const ready = readySeries("ready");
|
||||||
|
const inProgress = inProgressSeries("running", 1, 0);
|
||||||
|
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(inactive), {
|
||||||
|
label: "비활성",
|
||||||
|
tone: "muted",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(waiting), {
|
||||||
|
label: "대진 대기",
|
||||||
|
tone: "muted",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(ready), {
|
||||||
|
label: "경기 가능",
|
||||||
|
tone: "ready",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(inProgress), {
|
||||||
|
label: "진행 중",
|
||||||
|
tone: "live",
|
||||||
|
showScore: true,
|
||||||
|
});
|
||||||
|
assert.equal(formatSeriesScore(waiting, 0), "—");
|
||||||
|
assert.equal(formatSeriesScore(ready, 0), "—");
|
||||||
|
assert.equal(formatSeriesScore(inProgress, 0), "0");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("prioritizes a human-readable match name and keeps the code as metadata", () => {
|
||||||
|
const series = readySeries("WB_R2_M2");
|
||||||
|
|
||||||
|
assert.deepEqual(
|
||||||
|
getSeriesScoreCardIdentity(series, "브래킷 상위 2R · 2경기"),
|
||||||
|
{
|
||||||
|
label: "브래킷 상위 2R · 2경기",
|
||||||
|
code: "WB_R2_M2",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
assert.deepEqual(getSeriesScoreCardIdentity(series), {
|
||||||
|
label: "WB_R2_M2",
|
||||||
|
code: undefined,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows numeric scores only for played completed outcomes", () => {
|
||||||
|
const played = completedSeries("played", 2, 1);
|
||||||
|
const playedDraw = completedDraw("played", 1, 1);
|
||||||
|
const administrativeDraw = completedDraw("administrative", 0, 0);
|
||||||
|
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(played), {
|
||||||
|
label: "종료",
|
||||||
|
tone: "completed",
|
||||||
|
showScore: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(playedDraw), {
|
||||||
|
label: "무승부",
|
||||||
|
tone: "completed",
|
||||||
|
showScore: true,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(administrativeDraw), {
|
||||||
|
label: "무승부",
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.equal(formatSeriesScore(played, 2), "2");
|
||||||
|
assert.equal(formatSeriesScore(playedDraw, 1), "1");
|
||||||
|
assert.equal(formatSeriesScore(administrativeDraw, 0), "—");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("names adjudicated outcomes without inferring from their scores", () => {
|
||||||
|
const walkover = completedSeries("walkover", 0, 0);
|
||||||
|
const forfeit = completedSeries("forfeit", 0, 1);
|
||||||
|
const administrative = completedSeries("administrative", 1, 0);
|
||||||
|
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(walkover), {
|
||||||
|
label: "부전승",
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(forfeit), {
|
||||||
|
label: "기권승",
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.deepEqual(getSeriesScoreCardPresentation(administrative), {
|
||||||
|
label: "판정",
|
||||||
|
tone: "adjudicated",
|
||||||
|
showScore: false,
|
||||||
|
});
|
||||||
|
assert.equal(getSeriesScoreCardPresentation(walkover).showScore, false);
|
||||||
|
assert.equal(getSeriesScoreCardPresentation(forfeit).showScore, false);
|
||||||
|
assert.equal(getSeriesScoreCardPresentation(administrative).showScore, false);
|
||||||
|
assert.equal(formatSeriesScore(walkover, 0), "—");
|
||||||
|
assert.equal(formatSeriesScore(forfeit, 1), "—");
|
||||||
|
assert.equal(formatSeriesScore(administrative, 1), "—");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("summarizes status, teams, scores, and winner for a focus target", () => {
|
||||||
|
const series = completedSeries("played", 2, 1);
|
||||||
|
const teamById = new Map([
|
||||||
|
[TEAM_A, { name: "나물장수" }],
|
||||||
|
[TEAM_B, { name: "원딜미아요" }],
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
getSeriesScoreCardAccessibleLabel(
|
||||||
|
series,
|
||||||
|
"브래킷 1라운드 · 1경기",
|
||||||
|
teamById,
|
||||||
|
),
|
||||||
|
"브래킷 1라운드 · 1경기, 코드 PLAYED, 종료. A 나물장수, 2승, 승리. B 원딜미아요, 1승.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("announces an adjudicated official winner without a numeric score", () => {
|
||||||
|
const series = completedSeries("forfeit", 0, 1);
|
||||||
|
const teamById = new Map([
|
||||||
|
[TEAM_A, { name: "나물장수" }],
|
||||||
|
[TEAM_B, { name: "원딜미아요" }],
|
||||||
|
]);
|
||||||
|
|
||||||
|
assert.equal(
|
||||||
|
getSeriesScoreCardAccessibleLabel(
|
||||||
|
series,
|
||||||
|
"브래킷 1라운드 · 1경기",
|
||||||
|
teamById,
|
||||||
|
),
|
||||||
|
"브래킷 1라운드 · 1경기, 코드 FORFEIT, 기권승. A 나물장수, 점수 없음, 승리. B 원딜미아요, 점수 없음.",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
function baseSeries(id: string) {
|
||||||
|
return {
|
||||||
|
seriesId: id as SeriesId,
|
||||||
|
code: id.toUpperCase(),
|
||||||
|
stage: { type: "upper" as const, roundNumber: 1, displayOrder: 1 },
|
||||||
|
rule: { type: "first-to" as const, winsRequired: 2, maxGames: 3 },
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function pendingSeries(
|
||||||
|
id: string,
|
||||||
|
status: "inactive" | "waiting",
|
||||||
|
): SeriesProjection {
|
||||||
|
return {
|
||||||
|
...baseSeries(id),
|
||||||
|
status,
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: null, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: null, gameWins: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function readySeries(id: string): SeriesProjection {
|
||||||
|
return {
|
||||||
|
...baseSeries(id),
|
||||||
|
status: "ready",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: 0 },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: 0 },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function inProgressSeries(
|
||||||
|
id: string,
|
||||||
|
scoreA: number,
|
||||||
|
scoreB: number,
|
||||||
|
): SeriesProjection {
|
||||||
|
return {
|
||||||
|
...baseSeries(id),
|
||||||
|
status: "in-progress",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: scoreA },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: scoreB },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedSeries(
|
||||||
|
outcome: "played" | "walkover" | "forfeit" | "administrative",
|
||||||
|
scoreA: number,
|
||||||
|
scoreB: number,
|
||||||
|
): SeriesProjection {
|
||||||
|
const sharedOutcome = {
|
||||||
|
winnerTeamId: TEAM_A,
|
||||||
|
loserTeamId: TEAM_B,
|
||||||
|
completedAt: "2026-07-13T00:00:00.000Z",
|
||||||
|
};
|
||||||
|
return {
|
||||||
|
...baseSeries(outcome),
|
||||||
|
status: "completed",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: scoreA },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: scoreB },
|
||||||
|
],
|
||||||
|
outcome:
|
||||||
|
outcome === "played"
|
||||||
|
? { ...sharedOutcome, type: outcome, decidedByGameIds: [] }
|
||||||
|
: {
|
||||||
|
...sharedOutcome,
|
||||||
|
type: outcome,
|
||||||
|
decisionFactId: `${outcome}-fact` as CompetitionFactId,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function completedDraw(
|
||||||
|
basis: "played" | "administrative",
|
||||||
|
scoreA: number,
|
||||||
|
scoreB: number,
|
||||||
|
): SeriesProjection {
|
||||||
|
return {
|
||||||
|
...baseSeries(`${basis}-draw`),
|
||||||
|
status: "completed",
|
||||||
|
entries: [
|
||||||
|
{ slot: "A", teamId: TEAM_A, gameWins: scoreA },
|
||||||
|
{ slot: "B", teamId: TEAM_B, gameWins: scoreB },
|
||||||
|
],
|
||||||
|
outcome: {
|
||||||
|
type: "draw",
|
||||||
|
basis:
|
||||||
|
basis === "played"
|
||||||
|
? { type: basis, decidedByGameIds: [] }
|
||||||
|
: {
|
||||||
|
type: basis,
|
||||||
|
decisionFactId: "draw-fact" as CompetitionFactId,
|
||||||
|
},
|
||||||
|
completedAt: "2026-07-13T00:00:00.000Z",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,203 @@
|
|||||||
|
# Implementation Plan: Series Result History UI
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Replace the existing completed-Game mini-card grid with a tested chronological
|
||||||
|
Series result history. Keep data derivation pure, render responsive semantic rows,
|
||||||
|
and preserve all current Competition/API contracts.
|
||||||
|
|
||||||
|
## Architecture Decisions
|
||||||
|
|
||||||
|
- Derive a local view model from `projection.series` and `projection.games`; no API
|
||||||
|
or persistence change is required.
|
||||||
|
- Anchor a played Series to its earliest accepted Game start. Anchor a game-less
|
||||||
|
completed decision to its decision time only for grouping and sorting.
|
||||||
|
- Keep the original narrowed Series and Game objects in each row so the UI does not
|
||||||
|
duplicate domain state or collapse outcome semantics.
|
||||||
|
- Use a native `details/summary` disclosure for Game history and omit it when a
|
||||||
|
Series has no Games.
|
||||||
|
- Extract the new UI from `CompetitionResults.tsx` so the format selector remains
|
||||||
|
focused.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Result-History Contract
|
||||||
|
|
||||||
|
#### Task 1: Specify aggregation and chronology test-first
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] Tests cover Series aggregation, ordinal Game order, KST date boundaries,
|
||||||
|
chronological order, outcome variants, and deterministic fallbacks.
|
||||||
|
- [x] The focused test fails because the model module does not yet exist.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Run the focused Node test and record the expected RED failure.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/test/competition-series-history.test.ts`
|
||||||
|
|
||||||
|
#### Task 2: Implement the pure history model
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] Only recorded in-progress and completed Series are returned.
|
||||||
|
- [x] Date grouping and format helpers are explicitly KST-aware.
|
||||||
|
- [x] Decision outcomes and missing legacy durations remain distinguishable.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Focused history tests pass.
|
||||||
|
- [x] Existing web tests still pass.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/competition-series-history.ts`
|
||||||
|
- `apps/web/test/competition-series-history.test.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Model
|
||||||
|
|
||||||
|
- [x] Pure tests pass without a React or browser dependency.
|
||||||
|
|
||||||
|
### Phase 2: Responsive Result UI
|
||||||
|
|
||||||
|
#### Task 3: Render date sections and Series rows
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] Desktop uses a flat schedule-like row; mobile stacks metadata and matchup
|
||||||
|
without horizontal scrolling.
|
||||||
|
- [x] Status and official winner are communicated with visible text and typography,
|
||||||
|
not color alone.
|
||||||
|
- [x] Game-less decisions do not show fake start times or `0 : 0`.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Changed component files pass ESLint.
|
||||||
|
- [x] Web build succeeds.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx`
|
||||||
|
|
||||||
|
#### Task 4: Integrate accessible Game disclosures
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] Each Series with Games exposes a native keyboard-operable disclosure.
|
||||||
|
- [x] Games use Series-local ordinal, team-ID winner lookup, and omit unknown
|
||||||
|
zero-duration values.
|
||||||
|
- [x] The old completed-Game mini-card block is removed.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Full web tests, changed-file lint, and build pass. Repository-wide lint remains
|
||||||
|
blocked by pre-existing errors outside this change.
|
||||||
|
- [x] Source review checks heading order, disclosure semantics, and 320px layout.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx`
|
||||||
|
- `apps/web/src/components/competition/CompetitionResults.tsx`
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] All specification success criteria are met.
|
||||||
|
- [x] Git diff contains only the feature spec, plan, tests, model, and UI integration.
|
||||||
|
- [x] Unrelated working-tree files are unchanged.
|
||||||
|
|
||||||
|
### Phase 3: Game Detail Navigation
|
||||||
|
|
||||||
|
#### Task 5: Specify the canonical Game route test-first
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] A Game whose `ordinal` and `displayNumber` differ links with
|
||||||
|
`displayNumber`.
|
||||||
|
- [x] Non-positive or non-integer legacy display numbers do not produce a broken
|
||||||
|
detail link.
|
||||||
|
- [x] The focused test is observed failing before the route adapter exists.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Run the focused Node test for RED and GREEN states.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/test/competition-series-history.test.ts`
|
||||||
|
- `apps/web/src/components/competition/competition-series-history.ts`
|
||||||
|
|
||||||
|
#### Task 6: Make disclosed Game rows navigable
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] The full Game row is one React Router link with an always-visible detail cue.
|
||||||
|
- [x] The link carries the current Competition location as `backTo` and a Korean
|
||||||
|
return label.
|
||||||
|
- [x] Mobile targets are at least 44px high; keyboard focus is visible; hover and
|
||||||
|
active states use restrained semantic-primary coral accents.
|
||||||
|
- [x] The scoped primary token keeps that coral accent in both themes without a
|
||||||
|
global dark-theme color migration.
|
||||||
|
- [x] Winner, score, and status colors retain their existing domain meaning.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Focused and full web tests pass.
|
||||||
|
- [x] Changed-file ESLint and the production web build pass.
|
||||||
|
- [x] Independent review checks route identity, interaction semantics, accessibility,
|
||||||
|
and unrelated working-tree preservation.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/CompetitionGameHistory.tsx`
|
||||||
|
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx`
|
||||||
|
- `apps/web/src/components/competition/CompetitionResults.tsx`
|
||||||
|
|
||||||
|
#### Task 7: Refuse incorrect Game-detail fallbacks
|
||||||
|
|
||||||
|
**Acceptance criteria:**
|
||||||
|
|
||||||
|
- [x] Exact requested Game numbers resolve to that Game.
|
||||||
|
- [x] Missing or invalid requested Game numbers return no selection instead of the
|
||||||
|
first Game.
|
||||||
|
- [x] The detail page renders an explicit missing-Game state with the preserved return
|
||||||
|
target.
|
||||||
|
- [x] The policy is covered by an observed RED→GREEN pure regression test.
|
||||||
|
|
||||||
|
**Verification:**
|
||||||
|
|
||||||
|
- [x] Focused selection tests, full web tests, changed-file ESLint, and build pass.
|
||||||
|
|
||||||
|
**Files likely touched:**
|
||||||
|
|
||||||
|
- `apps/web/src/lib/internal-match-game-selection.ts`
|
||||||
|
- `apps/web/src/pages/MatchGameDetailPage.tsx`
|
||||||
|
- `apps/web/test/internal-match-game-selection.test.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Navigable Game History
|
||||||
|
|
||||||
|
- [x] Every valid recorded Game opens its own internal-stat detail view.
|
||||||
|
- [x] Browser back and the detail page return link restore the Competition result
|
||||||
|
page.
|
||||||
|
- [x] Invalid legacy route data degrades to a non-clickable row instead of a wrong
|
||||||
|
destination.
|
||||||
|
- [x] A stale detail payload cannot substitute a different Game for the requested
|
||||||
|
route.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Game sides are mistaken for Series slots | High | Use Series A/B entries and outcome team IDs; test side swaps. |
|
||||||
|
| Completion time is shown as start time | Medium | Track timestamp source and render a blank time for decisions. |
|
||||||
|
| KST day changes by deploy environment | Medium | Use explicit `Intl.DateTimeFormat` timezone and boundary tests. |
|
||||||
|
| Long team names break mobile rows | Medium | Use balanced minmax columns and allow wrapping. |
|
||||||
|
| Existing dirty work is overwritten | High | Restrict patches and verification to named feature files. |
|
||||||
|
| Series-local ordinal opens another Series' Game | High | Generate routes only from tested global `displayNumber`. |
|
||||||
|
| Coral is mistaken for the winning side | Medium | Restrict primary color to interaction edges, focus, and arrows. |
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
# Implementation Plan: Double-Elimination Connector Routing
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Replace per-edge winner rail staggering with deterministic, collision-aware winner
|
||||||
|
bundles while retaining the existing target-corridor `H-V-H` path model and the
|
||||||
|
current loser/reset routing behavior.
|
||||||
|
|
||||||
|
## Architecture Decisions
|
||||||
|
|
||||||
|
- Keep routing as a pure layout calculation; the React renderer consumes unchanged
|
||||||
|
`BracketConnectorLayout` paths.
|
||||||
|
- Allocate baseline rails first, then choose one rail for each same-target winner
|
||||||
|
bundle while leaving loser/reset coordinates unchanged.
|
||||||
|
- Score complete candidate paths by parallel-stroke clearance, strict crossings,
|
||||||
|
and distance from the corridor midpoint.
|
||||||
|
- Permit shared `verticalX` only when the participating vertical intervals do not
|
||||||
|
overlap; otherwise search the same corridor for the nearest deterministic pair
|
||||||
|
of separate rails with focused-stroke clearance.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Regression Contract
|
||||||
|
|
||||||
|
- [x] Add tests proving quiet winner bundles use the corridor midpoint and all
|
||||||
|
shareable same-target winner paths remain aligned.
|
||||||
|
- [x] Replace target-column rail uniqueness with interval-aware segment assertions.
|
||||||
|
- [x] Cover reversed A/B input where overlapping vertical spans require the
|
||||||
|
deterministic separate-rail fallback.
|
||||||
|
- [x] Confirm the focused test fails with the current allocator.
|
||||||
|
|
||||||
|
### Checkpoint: RED
|
||||||
|
|
||||||
|
- [x] The new behavioral assertion fails for the expected unequal `verticalX`.
|
||||||
|
- [x] Existing tests remain unchanged except where their invariant is obsolete.
|
||||||
|
|
||||||
|
### Phase 2: Bundle-Aware Allocator
|
||||||
|
|
||||||
|
- [x] Represent connector routing inputs with precomputed source/target anchors.
|
||||||
|
- [x] Retain stable independent rails for loser/reset routes.
|
||||||
|
- [x] Group the two winners entering each target and select the nearest safe shared
|
||||||
|
rail without card penetration, forbidden overlap, or avoidable added crossings.
|
||||||
|
- [x] Fall back to the nearest deterministic, stroke-clear separate rails only
|
||||||
|
when the pair's own vertical intervals overlap and cannot safely share a rail.
|
||||||
|
|
||||||
|
### Checkpoint: GREEN
|
||||||
|
|
||||||
|
- [x] Focused layout tests pass for four-team, eight-team, reset-final, and shuffled
|
||||||
|
input fixtures.
|
||||||
|
- [x] Strict crossing, collinear-overlap, and 5px parallel-clearance safeguards pass.
|
||||||
|
|
||||||
|
### Phase 3: Verification and Review
|
||||||
|
|
||||||
|
- [x] Run the full web suite, lint, and production build; document the unrelated
|
||||||
|
pre-existing full-lint failures while verifying changed files separately.
|
||||||
|
- [x] Inspect the diff for correctness, simplicity, security, performance, and
|
||||||
|
adherence to the approved spec.
|
||||||
|
- [x] Perform an independent review and address all required findings.
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] All success criteria in the spec are verified.
|
||||||
|
- [x] No unrelated files are modified.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Blind midpoint alignment adds crossings in busy upper rounds | High | Score complete candidate paths and move the winner bundle together to the nearest safe rail. |
|
||||||
|
| Shared rails create overlapping vertical segments | High | Check interval overlap before allowing a shared `verticalX`; search deterministic fallback rails with 5px clearance otherwise. |
|
||||||
|
| Visually parallel rails pass exact-coordinate tests but overlap at stroke width | High | Require 5px clearance across overlapping vertical runs and cover it for 4/8-team fixtures. |
|
||||||
|
| Routing changes depend on input array order | Medium | Sort routes and bundles by graph display order and retain shuffled-fixture equality tests. |
|
||||||
|
| A long connector bends through an intermediate card | High | Restrict every candidate to the target corridor and retain card-penetration assertions. |
|
||||||
|
| Reset-final slot carry-over is accidentally treated as a winner pair | Medium | Bundle only connectors whose computed kind is `winner`; keep reset paths independent. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
Regression contract -> bundle-aware rail allocator -> full verification -> review
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# Implementation Plan: Internal Match Game Analysis P0/P1
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deliver three independently verifiable slices: P0 existing-data UI, P1-A timeline
|
||||||
|
checkpoints and lane comparison, and P1-B unified notable events. Preserve the
|
||||||
|
existing detail endpoint and use builder/cache versioning to refresh old projections.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: P0 Existing Data
|
||||||
|
|
||||||
|
- [x] Add tested objective normalization, chart markers, an accessible event list,
|
||||||
|
and move game flow above the detail tabs.
|
||||||
|
- [x] Add a complete objective comparison strip with conservative dragon-type
|
||||||
|
fallback behavior.
|
||||||
|
- [x] Label KP and add participant gold/GPM to the combined CS/economy presentation.
|
||||||
|
|
||||||
|
### Checkpoint: P0
|
||||||
|
|
||||||
|
- [x] Web tests, lint, and production build pass.
|
||||||
|
- [x] Desktop and mobile layouts retain all existing scoreboard/build behavior.
|
||||||
|
|
||||||
|
### Phase 2: P1-A Lane Checkpoints
|
||||||
|
|
||||||
|
- [x] Parse the remaining participant event identifier fields and project tested
|
||||||
|
participant checkpoints at 10 and 15 minutes.
|
||||||
|
- [x] Persist and expose optional checkpoint fields, reject stale caches, and bump
|
||||||
|
the match-stats builder/detail-response versions.
|
||||||
|
- [x] Replace final-state lane comparisons with tested role-based 10/15-minute
|
||||||
|
GD/CSD/XPD and K/D/A comparisons.
|
||||||
|
|
||||||
|
### Checkpoint: P1-A
|
||||||
|
|
||||||
|
- [x] Focused API tests and builds pass.
|
||||||
|
- [x] Web tests and production build pass.
|
||||||
|
- [x] Short and missing-timeline games show unavailable states rather than zeros.
|
||||||
|
|
||||||
|
### Phase 3: P1-B Unified Events
|
||||||
|
|
||||||
|
- [x] Project objectives, champion kills, towers, and inhibitors into a deterministic
|
||||||
|
tested event stream.
|
||||||
|
- [x] Expose `timelineEvents` while retaining `objectiveEvents` compatibility and
|
||||||
|
bump persisted/cache versions as required.
|
||||||
|
- [x] Add accessible event filtering and chart selection with objective-only fallback.
|
||||||
|
- [x] Coalesce concurrent hydration and short-cache incomplete results so transient
|
||||||
|
failures retry without rebuilding on every sequential page request.
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] API and web focused suites pass without skipped tests.
|
||||||
|
- [x] API and web production builds pass.
|
||||||
|
- [x] Responsive runtime review passes at 320px, 390px, 768px, 1024px, and 1440px.
|
||||||
|
- [x] P0/P1 edits exclude unrelated Competition/bracket modifications already in
|
||||||
|
the shared worktree.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| Missing or delayed Riot frames misrepresent @10/@15 | High | Use only a frame at/before the target within one frame interval and expose its actual timestamp. |
|
||||||
|
| Building events attribute the destroyed team's side as the scorer | High | Prefer killer participant side; otherwise invert the destroyed `teamId`; cover both paths in tests. |
|
||||||
|
| Old cached shapes hide new fields | High | Increment builder and response cache versions and strengthen completeness validation. |
|
||||||
|
| A kill-heavy game makes the page excessively long | Medium | Add event-category filters and a bounded scroll region. |
|
||||||
|
| Mobile chart remains hard to reach | Medium | Move flow directly below the summary before any participant cards. |
|
||||||
|
| Existing dirty work is accidentally included | High | Restrict edits and verification to the named game-analysis files and inspect the final diff by path. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
P0 event normalization -> P0 objective strip
|
||||||
|
P1 checkpoint projector -> response contract -> lane UI
|
||||||
|
P1 checkpoint identifiers -> event projector -> response contract -> event UI
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
# Implementation Plan: Team Progress Page UX Refresh
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
Deliver the redesign in three verifiable slices: tested presentation rules, shared
|
||||||
|
Series semantics, and the integrated page/copy experience. No API or dependency
|
||||||
|
change is required because the team view already exposes `seriesId`, ordinal, round
|
||||||
|
metadata, outcome categories, and code expiry.
|
||||||
|
|
||||||
|
## Architecture Decisions
|
||||||
|
|
||||||
|
- Keep API/query ownership in the page and move deterministic presentation logic
|
||||||
|
into a pure module that the existing Node test runner can exercise.
|
||||||
|
- Compose the active-Series card with code rows instead of maintaining a separate
|
||||||
|
page-wide code grid.
|
||||||
|
- Keep the team page's Series presentation in a page-specific card so shared
|
||||||
|
bracket/history layouts are unaffected; exhaustively test its outcome mapping.
|
||||||
|
- Reuse the bracket's canonical round-label helper so the bracket and team detail
|
||||||
|
cannot drift to different visible match names.
|
||||||
|
- Use one responsive layout and native disclosure/table semantics rather than
|
||||||
|
separate desktop and mobile component trees.
|
||||||
|
|
||||||
|
## Task List
|
||||||
|
|
||||||
|
### Phase 1: Tested View Model
|
||||||
|
|
||||||
|
- [x] Add failing tests for Series/code grouping, stable ordering, Korean round
|
||||||
|
labels, code availability/expiry, unique copy labels, and explicit clipboard
|
||||||
|
results.
|
||||||
|
- Acceptance: the new focused test fails because the behavior is not implemented.
|
||||||
|
- Verify: `pnpm --filter web exec node --test --experimental-strip-types test/match-team-progress-view.test.ts`
|
||||||
|
- Files: `apps/web/test/match-team-progress-view.test.ts`
|
||||||
|
- [x] Implement the minimal pure view helpers.
|
||||||
|
- Acceptance: all focused assertions pass without React or DOM mocks.
|
||||||
|
- Verify: rerun the focused command once after implementation.
|
||||||
|
- Files: `apps/web/src/pages/match-team-progress-view.ts`
|
||||||
|
|
||||||
|
### Checkpoint: View Model
|
||||||
|
|
||||||
|
- [x] Focused tests pass and no API/contract file changed.
|
||||||
|
|
||||||
|
### Phase 2: Series Semantics and Code Interaction
|
||||||
|
|
||||||
|
- [x] Add a page-specific Series card that prefers supplied human labels, shows
|
||||||
|
technical codes secondarily, and hides misleading pre-start/adjudicated scores.
|
||||||
|
- Acceptance: ready and adjudicated cards show `—`; result categories remain
|
||||||
|
text-visible; bracket geometry stays unchanged.
|
||||||
|
- Verify: `pnpm --filter web test`
|
||||||
|
- Files: `apps/web/src/components/competition/TeamSeriesCard.tsx`
|
||||||
|
- [x] Add the responsive tournament-code list with accessible clipboard feedback.
|
||||||
|
- Acceptance: code rows show local set number first, full selectable codes,
|
||||||
|
unique 44px copy controls, expiry/state text, and success/failure announcements.
|
||||||
|
- Verify: TypeScript build plus runtime keyboard/copy check.
|
||||||
|
- Files: `apps/web/src/components/competition/TeamTournamentCodes.tsx`
|
||||||
|
|
||||||
|
### Checkpoint: Interaction
|
||||||
|
|
||||||
|
- [x] Full web tests pass and the web build succeeds.
|
||||||
|
|
||||||
|
### Phase 3: Page Hierarchy and Polish
|
||||||
|
|
||||||
|
- [x] Reorder the page and integrate code rows with matching active Series.
|
||||||
|
- Acceptance: order is next match, roster, recent results; every code appears
|
||||||
|
under exactly one matching Series; empty states remain meaningful.
|
||||||
|
- Verify: desktop and mobile runtime screenshots.
|
||||||
|
- Files: `apps/web/src/pages/MatchTeamProgressPage.tsx`
|
||||||
|
|
||||||
|
- [x] Compact and order the roster, and collapse results beyond the newest two.
|
||||||
|
- Acceptance: position labels are Korean and role-ordered, captain is adjacent,
|
||||||
|
and older results remain keyboard-accessible.
|
||||||
|
- Verify: 320/768/1024/1440px reflow and keyboard traversal.
|
||||||
|
- Files: `apps/web/src/pages/MatchTeamProgressPage.tsx`
|
||||||
|
|
||||||
|
### Phase 4: Bracket Naming Alignment
|
||||||
|
|
||||||
|
- [x] Reuse canonical bracket round labels in the team-detail view model.
|
||||||
|
- Acceptance: upper round 1 displays `브래킷 1R`, later upper rounds display
|
||||||
|
`브래킷 상위 nR`, lower rounds display `브래킷 하위 nR`, and multi-match
|
||||||
|
rounds keep the `· n경기` suffix.
|
||||||
|
- Verify: focused view-model test, full web suite, scoped lint, and build.
|
||||||
|
- Files: `apps/web/src/components/competition/double-elimination-bracket-layout.ts`,
|
||||||
|
`apps/web/src/pages/match-team-progress-view.ts`, and
|
||||||
|
`apps/web/test/match-team-progress-view.test.ts`
|
||||||
|
|
||||||
|
### Checkpoint: Complete
|
||||||
|
|
||||||
|
- [x] Focused (9) and full web tests (88) pass without skips.
|
||||||
|
- [x] Scoped lint and the production build pass.
|
||||||
|
- [ ] Full repository lint passes. It is currently blocked by pre-existing errors
|
||||||
|
outside the team-progress scope.
|
||||||
|
- [ ] Runtime review confirms no console errors or horizontal overflow. The
|
||||||
|
required in-app browser was unavailable in this session.
|
||||||
|
- [x] The scoped implementation contains only the spec, plan, focused tests, and
|
||||||
|
team-progress UI; unrelated concurrent worktree changes are excluded.
|
||||||
|
|
||||||
|
## Risks and Mitigations
|
||||||
|
|
||||||
|
| Risk | Impact | Mitigation |
|
||||||
|
|---|---|---|
|
||||||
|
| A code appears under the wrong Series | High | Join only on exact `seriesId` and cover opponent/other-Series codes in tests. |
|
||||||
|
| Global and local game numbers are confused | High | Lead with `ordinal` as set number and demote `displayNumber`. |
|
||||||
|
| Adjudication looks like a played 0–0 | High | Reuse tested outcome/score helpers from Competition history. |
|
||||||
|
| Clipboard permissions fail silently | Medium | Return a typed result and render an alert with manual-selection guidance. |
|
||||||
|
| Long codes overflow at mobile widths | Medium | Use `minmax(0,1fr)`, `break-all`, selectable text, and a stacked mobile row. |
|
||||||
|
| Page-specific result semantics drift | Medium | Cover every lifecycle/outcome branch in the pure presentation tests. |
|
||||||
|
|
||||||
|
## Dependencies
|
||||||
|
|
||||||
|
```text
|
||||||
|
View-model tests -> view helpers -> code component -> page composition
|
||||||
|
Exhaustive Series outcome tests -> page-specific score semantics -> recent results
|
||||||
|
```
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None.
|
||||||
@@ -274,10 +274,19 @@ Migration builds new collections without dual canonical writes.
|
|||||||
`null`, mapping it to `pair`; an explicitly stored unknown mode remains
|
`null`, mapping it to `pair`; an explicitly stored unknown mode remains
|
||||||
quarantined instead of being guessed.
|
quarantined instead of being guessed.
|
||||||
- A persisted legacy round-robin `gameSchedule` is authoritative. Migration
|
- A persisted legacy round-robin `gameSchedule` is authoritative. Migration
|
||||||
normalizes it into explicit seed-based pairings on the Competition format so the
|
normalizes it into explicit TeamId-based pairings on the Competition format so the
|
||||||
immutable Series graph reproduces the historical opponents and rounds instead of
|
immutable Series graph reproduces the historical opponents and rounds instead of
|
||||||
generating a different canonical schedule. Matches without a persisted schedule
|
generating a different canonical schedule. The persisted schedule must completely
|
||||||
continue to use deterministic canonical round-robin generation.
|
cover every configured round and every Series in each round; incomplete schedules
|
||||||
|
are quarantined. If every round number is absent on an older schedule, migration
|
||||||
|
deterministically partitions its persisted opponent pairs into complete playable
|
||||||
|
rounds and emits a warning; mixed or unpartitionable schedules are quarantined.
|
||||||
|
Complete opponent sets use direct canonical factorization at any supported team
|
||||||
|
count. Partial opponent-only schedules use bounded reconstruction for at most 16
|
||||||
|
teams; larger or search-limit-exceeding inputs receive dedicated quarantine codes
|
||||||
|
instead of being mislabeled as invalid.
|
||||||
|
Matches without a persisted schedule continue to use deterministic canonical
|
||||||
|
round-robin generation.
|
||||||
- Legacy TournamentCode `gameNumber` is a global GameSlot number, not a Series
|
- Legacy TournamentCode `gameNumber` is a global GameSlot number, not a Series
|
||||||
ordinal. Migration resolves it through accepted Riot evidence first, then the
|
ordinal. Migration resolves it through accepted Riot evidence first, then the
|
||||||
persisted format topology (`gameSchedule` or double-elimination bracket layout),
|
persisted format topology (`gameSchedule` or double-elimination bracket layout),
|
||||||
@@ -286,7 +295,28 @@ Migration builds new collections without dual canonical writes.
|
|||||||
Series/GameSlot must agree. A multi-slot Series is never assigned to its first
|
Series/GameSlot must agree. A multi-slot Series is never assigned to its first
|
||||||
GameSlot as a fallback; missing, conflicting, duplicated, or out-of-range evidence
|
GameSlot as a fallback; missing, conflicting, duplicated, or out-of-range evidence
|
||||||
is quarantined without changing the legacy Match or TournamentCode.
|
is quarantined without changing the legacy Match or TournamentCode.
|
||||||
- Dry-run is the default and emits machine-readable and human-readable reports.
|
- TournamentCode pool documents may retain timestamps from an earlier binding after
|
||||||
|
reuse. Migration preserves only the lifecycle reachable from the current state
|
||||||
|
(`reserved`, `used`, `released`, or `voided`) and validates that current lifecycle;
|
||||||
|
stale timestamps from a previous binding are not copied into the new assignment.
|
||||||
|
Riot match identity is likewise carried only for the current `used` or `voided`
|
||||||
|
binding, never from a restored `reserved` or `released` pool document.
|
||||||
|
- Historical result collection and repair paths stored Riot occurrence time (archive
|
||||||
|
game end/game creation, or game creation plus duration) in legacy `usedAt`, whereas
|
||||||
|
Competition assignments define `usedAt` as the persisted state-transition time.
|
||||||
|
Migration maps recognized legacy occurrence values to `TournamentCode.updatedAt`
|
||||||
|
for every `used` assignment only when an archive-backed accepted game has the same
|
||||||
|
Riot identity and
|
||||||
|
`max(reservedAt, original usedAt) <= updatedAt <= fact.recordedAt`. This also
|
||||||
|
safely covers post-game attachment where legacy `usedAt < reservedAt`. Source
|
||||||
|
values, evidence strategy, slot identity, and normalized time are emitted as an
|
||||||
|
audit warning. A recognized occurrence value without a valid persisted transition,
|
||||||
|
and any uncorroborated inverted lifecycle, remains quarantined. A chronological
|
||||||
|
`usedAt` that does not match a known occurrence encoding continues through the
|
||||||
|
ordinary lifecycle validation because it may already represent transition time.
|
||||||
|
- Dry-run is the default and emits machine-readable and human-readable reports. Every
|
||||||
|
ready/apply result includes a deterministic `planHash` over the graph, facts, and
|
||||||
|
TournamentCode targets so audits detect target changes even when counts stay equal.
|
||||||
- Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact
|
- Apply is resumable, idempotent, transactionally scoped per Match, and verifies fact
|
||||||
replay equality after every write.
|
replay equality after every write.
|
||||||
- Apply explicitly creates or verifies every Competition unique/partial index before
|
- Apply explicitly creates or verifies every Competition unique/partial index before
|
||||||
|
|||||||
@@ -0,0 +1,134 @@
|
|||||||
|
# Spec: Double-Elimination Connector Routing
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Make winner advancement lines in the desktop double-elimination bracket bend at a
|
||||||
|
consistent horizontal position. Two winner lines entering the same match should
|
||||||
|
read as one visual pair when their vertical spans can share a rail: use the center
|
||||||
|
of the 40px inter-column corridor when it is safe, and move the pair together only
|
||||||
|
when another connector would interfere. If an accepted A/B mapping reverses the
|
||||||
|
source order and makes those spans overlap, preserve separate deterministic,
|
||||||
|
stroke-clear rails instead of creating a collinear overlap.
|
||||||
|
|
||||||
|
The primary user is a participant or organizer tracing advancement through a busy
|
||||||
|
eight-team bracket. Success means the solid coral winner paths are visually
|
||||||
|
aligned without degrading the existing dashed loser paths, card placement, or
|
||||||
|
keyboard-driven connector highlighting.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Treat the two `winner` connectors entering one Series as a semantic bundle.
|
||||||
|
- Prefer `target.x - columnGap / 2` for a winner bundle.
|
||||||
|
- If the preferred rail causes crossings, collinear overlap, or less than 5px of
|
||||||
|
clearance from an overlapping parallel route, move a shareable bundle to the
|
||||||
|
nearest safe rail. Retain separate rails only when the pair's own vertical spans
|
||||||
|
overlap and therefore cannot safely share any rail; move those rails to the
|
||||||
|
nearest deterministic positions needed to preserve the same 5px clearance.
|
||||||
|
- Preserve the current loser/reset rail ordering unless moving one is required to
|
||||||
|
maintain valid geometry.
|
||||||
|
- Keep every connector as a separate `H-V-H` SVG path so focus highlighting and
|
||||||
|
accessible labels remain independent.
|
||||||
|
- Keep long-distance bends inside the corridor immediately before the target
|
||||||
|
column; do not use the midpoint between source and target cards.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19, TypeScript 6, Vite 8, Tailwind CSS 4, and daisyUI under `apps/web`
|
||||||
|
- Node's built-in test runner for the pure bracket layout calculation
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused layout tests: `pnpm --filter web exec node --test --experimental-strip-types test/double-elimination-bracket-layout.test.ts`
|
||||||
|
- Full web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web production build: `pnpm --filter web build:prod`
|
||||||
|
- Development server: `pnpm --filter web start:dev`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
|
||||||
|
validates the bracket graph, positions cards, assigns connector rails, and emits
|
||||||
|
SVG path geometry.
|
||||||
|
- `apps/web/src/components/competition/DoubleEliminationBracket.tsx` renders the
|
||||||
|
computed paths and must not need routing-specific changes.
|
||||||
|
- `apps/web/test/double-elimination-bracket-layout.test.ts` contains canonical
|
||||||
|
four-team, eight-team, and reset-final fixtures plus geometry assertions.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep routing deterministic and express geometry through small named helpers:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const preferredX = target.x - geometry.columnGap / 2;
|
||||||
|
const verticalX = nearestSafeRail(preferredX, bundle, occupiedRoutes);
|
||||||
|
```
|
||||||
|
|
||||||
|
Use existing layout types and semantic connector kinds. Do not add a dependency,
|
||||||
|
DOM measurement, mutable global state, or renderer-specific routing behavior.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Add regression tests before implementation and confirm they fail against the
|
||||||
|
current per-edge rail allocator.
|
||||||
|
- Assert observable geometry: safe winner pairs share a rail, quiet corridors use
|
||||||
|
their exact midpoint, busy corridors keep a pair aligned, and mixed
|
||||||
|
winner/loser entries remain distinguishable.
|
||||||
|
- Cover reversed A/B winner input explicitly: it remains deterministic and uses
|
||||||
|
separate rails without collinear overlap or focused-stroke clearance conflicts
|
||||||
|
because no shared H-V-H rail is safe.
|
||||||
|
- Replace the obsolete "all rails in a target column are unique" assertion with
|
||||||
|
interval-aware overlap and 5px focused-stroke clearance protection.
|
||||||
|
- Preserve deterministic output for shuffled input, finite path coordinates,
|
||||||
|
target-corridor bounds, card avoidance, endpoint alignment, and canonical graph
|
||||||
|
validation.
|
||||||
|
- Verify four-team, eight-team, and reset-final layouts; run the complete web test,
|
||||||
|
lint, and production build commands.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Keep winner, loser, and reset connectors visually distinguishable by the existing
|
||||||
|
solid/dashed patterns and brand tokens.
|
||||||
|
- Keep connector rails strictly inside the target corridor.
|
||||||
|
- Avoid strict segment crossings and collinear overlaps whenever a safe candidate
|
||||||
|
exists.
|
||||||
|
- Keep overlapping parallel winner and loser rails at least 5px apart, matching
|
||||||
|
the widest focused connector underlay.
|
||||||
|
- Produce the same layout regardless of projection input ordering.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Add dependencies or change the public projection contract.
|
||||||
|
- Change bracket card dimensions, round columns, or the 40px column gap.
|
||||||
|
- Redesign mobile bracket presentation or connector interaction behavior.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Route a connector through a match card.
|
||||||
|
- Infer routing from Series codes; use canonical graph identity and topology.
|
||||||
|
- Merge two logical connectors into one SVG path.
|
||||||
|
- Modify unrelated competition or score-card behavior.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- The two winner paths into `LB_R3_M1` bend at the corridor midpoint and share the
|
||||||
|
same `verticalX`.
|
||||||
|
- The winner paths into the grand final share the corridor midpoint when safe.
|
||||||
|
- Every same-target winner pair whose vertical spans do not overlap shares one
|
||||||
|
`verticalX`, using the nearest collision-safe rail when the midpoint is busy.
|
||||||
|
- A reversed A/B pair with overlapping vertical spans retains deterministic
|
||||||
|
separate rails, produces no collinear segment overlap, and remains at least 5px
|
||||||
|
from every overlapping vertical route.
|
||||||
|
- Loser/reset paths retain their baseline rails, and winner bundles remain at least
|
||||||
|
5px away where their vertical runs overlap.
|
||||||
|
- All rails remain inside their target corridors without card penetration or
|
||||||
|
collinear overlap.
|
||||||
|
- Canonical four-team, eight-team, reset-final, and shuffled-input tests pass.
|
||||||
|
- Full web tests and production build pass; changed-file lint passes, and any
|
||||||
|
unrelated full-lint baseline failures are documented.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user reviewed the proposed bundle-aware routing behavior and requested
|
||||||
|
implementation.
|
||||||
@@ -0,0 +1,170 @@
|
|||||||
|
# Spec: Internal Match Game Analysis P0/P1
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Make an internal-match game result explain both the final numbers and how the game
|
||||||
|
reached them. P0 exposes data already present in the detail response: objective
|
||||||
|
events, complete team objectives, participant gold/GPM, and explicitly labelled
|
||||||
|
kill participation. P1 projects Riot Match-V5 timeline frames into real 10- and
|
||||||
|
15-minute lane checkpoints and a unified event stream for kills and structures.
|
||||||
|
|
||||||
|
The primary user is a tournament participant or organizer reviewing a completed
|
||||||
|
game on desktop or mobile. Success means the user can identify the major objective
|
||||||
|
sequence before reading ten player cards, compare lane state at 10/15 minutes, and
|
||||||
|
trace kills and building events without mistaking unavailable data for zero.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Place game flow immediately after the game summary and before detail tabs.
|
||||||
|
- Render chart events as both visual markers and a keyboard-readable text list.
|
||||||
|
- Keep the existing gold/XP toggle and runes/build experience.
|
||||||
|
- Show tower, dragon, inhibitor, Baron, Rift Herald, Void Grub, and Elder Dragon
|
||||||
|
totals; derive dragon type labels only when objective events are available.
|
||||||
|
- Combine participant CS and economy instead of adding another wide table column.
|
||||||
|
- Label kill participation explicitly as `KP`.
|
||||||
|
- Replace final-state values in the lane tab with 10/15-minute checkpoints; default
|
||||||
|
to 15 minutes and pair players by `teamPosition`, never array position.
|
||||||
|
- Keep `objectiveEvents` for compatibility and add `timelineEvents` for the unified
|
||||||
|
P1 stream.
|
||||||
|
- Treat missing checkpoints and events as unavailable, not zero.
|
||||||
|
- Do not add an opaque MVP/rating or new external data feed in this scope.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19, TypeScript 6, Recharts 3, Tailwind CSS 4, and daisyUI under `apps/web`
|
||||||
|
- NestJS 11, TypeScript 5, Mongoose 9, and Jest under `apps/api`
|
||||||
|
- Riot Match-V5 match and timeline payloads already cached in `RiotMatchModel`
|
||||||
|
- Node's built-in test runner for pure web transformations
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web production build: `pnpm --filter web build:prod`
|
||||||
|
- Focused API tests: `pnpm --filter api test -- --runInBand riot-match.service.spec.ts match-stats-fragment.builder.spec.ts community-stats.service.spec.ts`
|
||||||
|
- API build: `pnpm --filter api build`
|
||||||
|
- Development web server: `pnpm --filter web start:dev`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/pages/MatchGameDetailPage.tsx` owns the result summary,
|
||||||
|
participant scoreboard, flow chart, and accessible event list.
|
||||||
|
- `apps/web/src/components/InternalGameAnalysisTabs.tsx` owns the lane and build
|
||||||
|
tabs.
|
||||||
|
- `apps/web/src/lib/internal-match-timeline.ts` owns pure event normalization,
|
||||||
|
labels, filtering, and chart projection.
|
||||||
|
- `apps/web/src/lib/internal-game-matchups.ts` owns pure role pairing and checkpoint
|
||||||
|
comparisons.
|
||||||
|
- `apps/web/test/` contains Node unit tests for the pure web transformations.
|
||||||
|
- `apps/api/src/modules/riot/` parses trusted fields from Riot match timelines.
|
||||||
|
- `apps/api/src/modules/community-stats/match-stats-fragment.builder.ts` projects
|
||||||
|
stored Riot payloads into cached internal-match records.
|
||||||
|
- `apps/api/src/modules/community-stats/community-stats.service.ts` maps persisted
|
||||||
|
records into the public detail response and versions response caches.
|
||||||
|
- `apps/api/src/modules/global/database/schema.ts` defines persisted TypeScript
|
||||||
|
shapes; nested `gameDetails` remains a Mongoose Mixed array.
|
||||||
|
|
||||||
|
## Data Contract
|
||||||
|
|
||||||
|
Participant checkpoint data is additive and optional for legacy/fallback games:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface MatchStatsCheckpoint {
|
||||||
|
timestamp: number;
|
||||||
|
gold: number;
|
||||||
|
cs: number;
|
||||||
|
xp: number;
|
||||||
|
kills: number;
|
||||||
|
deaths: number;
|
||||||
|
assists: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface MatchStatsParticipantCheckpoints {
|
||||||
|
at10?: MatchStatsCheckpoint;
|
||||||
|
at15?: MatchStatsCheckpoint;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Each detailed participant gains optional `participantId` and `checkpoints`. Each
|
||||||
|
game gains optional `timelineEvents`, whose `type` is an existing objective type or
|
||||||
|
`championKill`, `tower`, or `inhibitor`. Actor IDs, assists, monster subtype, and
|
||||||
|
tower subtype are optional fields appropriate to the event type.
|
||||||
|
|
||||||
|
For a 10/15-minute target, use the latest frame at or before the target only when it
|
||||||
|
is less than one `frameInterval` old. Persist the actual selected timestamp. CS is
|
||||||
|
`minionsKilled + jungleMinionsKilled`; checkpoint K/D/A includes champion-kill
|
||||||
|
events through the selected timestamp. A game ending before a target has no value
|
||||||
|
for that checkpoint.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep timeline calculations independent from React and use discriminated event
|
||||||
|
types with conservative fallbacks:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const events = game.timelineEvents?.length
|
||||||
|
? game.timelineEvents
|
||||||
|
: game.objectiveEvents;
|
||||||
|
|
||||||
|
const checkpoint = participant.checkpoints?.at15;
|
||||||
|
if (!checkpoint) return { kind: "unavailable" };
|
||||||
|
```
|
||||||
|
|
||||||
|
Use existing semantic color tokens and square bordered panels. Dynamic chart
|
||||||
|
coordinates may use numeric props; spacing, colors, and typography remain in the
|
||||||
|
existing Tailwind/daisyUI system.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Develop pure event normalization, checkpoint selection, role pairing, and metric
|
||||||
|
comparison test-first.
|
||||||
|
- Builder tests cover exact and missing checkpoints, jungle CS, cumulative K/D/A,
|
||||||
|
executes, objective fallback, building ownership, and deterministic event order.
|
||||||
|
- Service tests reject stale cached response shapes and verify additive mapping.
|
||||||
|
- Browser verification covers 320px, 390px, 768px, 1024px, and 1440px; the event
|
||||||
|
text list is the accessible equivalent of decorative chart markers.
|
||||||
|
- Verify the supplied production-like game as well as a short game and a game with
|
||||||
|
no timeline.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Preserve existing `objectiveEvents`, runes/builds, and match-detail routes.
|
||||||
|
- Derive participant checkpoint values from stored Riot timeline frames.
|
||||||
|
- Pair lanes by normalized `teamPosition` and show unavailable states explicitly.
|
||||||
|
- Communicate team/event meaning with text as well as color.
|
||||||
|
- Increment the match-stats builder and detail-response cache versions whenever a
|
||||||
|
persisted or cached response shape changes.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Add a frontend or backend dependency.
|
||||||
|
- Change the public route or remove compatibility fields.
|
||||||
|
- Add a database migration or make a bulk external Riot API fetch.
|
||||||
|
- Deploy, push, or alter CI configuration.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Infer absent checkpoint data as zero.
|
||||||
|
- Pair opponents by array order.
|
||||||
|
- Claim that a nearby objective caused a gold swing.
|
||||||
|
- Expose unparsed arbitrary Riot event fields.
|
||||||
|
- Modify unrelated Competition/bracket work already present in the worktree.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- Game flow appears before player details and includes objective markers plus an
|
||||||
|
equivalent textual sequence on desktop and mobile.
|
||||||
|
- Summary shows all currently projected objective totals and available dragon types.
|
||||||
|
- Every participant shows labelled KP, gold, GPM, CS, and CS/min without breaking
|
||||||
|
the responsive scoreboard.
|
||||||
|
- The lane tab defaults to 15 minutes, can switch to 10 minutes, and presents
|
||||||
|
GD/CSD/XPD and checkpoint K/D/A for correctly paired roles.
|
||||||
|
- The unified timeline can filter and display objectives, champion kills, towers,
|
||||||
|
and inhibitors, while falling back to objective-only data during rolling updates.
|
||||||
|
- Focused API/web tests, lint, and production builds pass.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user reviewed the P0/P1 task plan and requested implementation.
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# Spec: Series Result History UI
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Replace the compact `Game N - winner` cards below Competition brackets with a
|
||||||
|
chronological, Series-centric result history. Users should be able to scan when a
|
||||||
|
Series was played, its round, participants, official result, and current score,
|
||||||
|
then expand the row to inspect the accepted Games that produced that record.
|
||||||
|
|
||||||
|
This first version is a truthful activity/result history, not a future schedule.
|
||||||
|
It uses only recorded Competition projection data and does not invent scheduled
|
||||||
|
times, venues, replay links, or team logos.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Keep the bracket first as the topology view and place the chronological history
|
||||||
|
below it.
|
||||||
|
- Render one primary row per Series, never one primary row per Game.
|
||||||
|
- Include a started `in-progress` Series when it has at least one accepted Game, so
|
||||||
|
completed Games do not disappear while a best-of Series is still running.
|
||||||
|
- Include every completed Series, including draw, walkover, forfeit, and
|
||||||
|
administrative outcomes with no accepted Game.
|
||||||
|
- Exclude inactive, waiting, ready, and game-less in-progress Series because they do
|
||||||
|
not have a truthful result timestamp.
|
||||||
|
- Use the earliest accepted Game `startedAt` as the Series activity time. For a
|
||||||
|
game-less decision, group by `outcome.completedAt` but display no fake start time.
|
||||||
|
- Group and format dates explicitly in `Asia/Seoul`.
|
||||||
|
- Keep individual Games in a native, keyboard-accessible disclosure below the Series
|
||||||
|
row.
|
||||||
|
- Make each disclosed Game row a real link to its internal-stat Game detail. Keep the
|
||||||
|
visible Series-local `ordinal`, but build the route from the globally unique
|
||||||
|
`displayNumber`.
|
||||||
|
- Preserve the current Competition page path in router state so the detail page can
|
||||||
|
return users to the same result view.
|
||||||
|
- Use the coral semantic primary token as an interaction cue on Game links (leading
|
||||||
|
edge, focus ring, subtle state background, and arrow), not as a winner or score
|
||||||
|
color.
|
||||||
|
- Scope that primary override to the result-history section so the exact coral remains
|
||||||
|
consistent in light and dark themes without changing unrelated dark-theme actions.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19 and TypeScript 6 under `apps/web`
|
||||||
|
- Tailwind CSS 4 and daisyUI semantic tokens
|
||||||
|
- Shared Competition contracts from `@lolympus/contracts`
|
||||||
|
- Node's built-in test runner with TypeScript type stripping for pure model tests
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused RED/GREEN test:
|
||||||
|
`pnpm --filter web exec node --test --experimental-strip-types test/competition-series-history.test.ts`
|
||||||
|
- Full web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web build: `pnpm --filter web build`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/components/competition/competition-series-history.ts` derives the
|
||||||
|
stable, timezone-aware history view model without React.
|
||||||
|
- `apps/web/src/components/competition/CompetitionSeriesHistory.tsx` renders the
|
||||||
|
semantic date sections and responsive Series rows.
|
||||||
|
- `apps/web/src/components/competition/CompetitionGameHistory.tsx` renders the
|
||||||
|
disclosed, navigable Game rows and their responsive interaction states.
|
||||||
|
- `apps/web/src/components/competition/CompetitionResults.tsx` replaces the existing
|
||||||
|
completed-Game card grid with the new component and supplies the route context.
|
||||||
|
- `apps/web/src/lib/internal-match-game-selection.ts` keeps explicit Game-detail
|
||||||
|
routes from silently falling back to a different recorded Game.
|
||||||
|
- `apps/web/test/competition-series-history.test.ts` specifies aggregation, ordering,
|
||||||
|
outcome, and formatting behavior.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Use contract discriminators and team IDs as the source of truth:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const shouldInclude =
|
||||||
|
(series.status === "in-progress" && games.length > 0) ||
|
||||||
|
series.status === "completed";
|
||||||
|
|
||||||
|
const winnerTeamId =
|
||||||
|
series.status === "completed" && series.outcome.type !== "draw"
|
||||||
|
? series.outcome.winnerTeamId
|
||||||
|
: undefined;
|
||||||
|
```
|
||||||
|
|
||||||
|
The UI uses flat, full-width rows and existing semantic tokens. It does not reuse
|
||||||
|
the bordered bracket card layout or introduce new dependencies.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
Develop the pure model test-first. Cover:
|
||||||
|
|
||||||
|
- Games aggregated by `seriesId` and ordered by Series-local `ordinal`;
|
||||||
|
- Series score preserved from A/B entries even when blue/red sides change;
|
||||||
|
- chronological ordering independent of projection graph order;
|
||||||
|
- `Asia/Seoul` grouping across the UTC day boundary;
|
||||||
|
- started in-progress Series and game-less completed decisions;
|
||||||
|
- exclusion of unstarted and orphan data;
|
||||||
|
- played, draw, walkover, forfeit, and administrative status semantics;
|
||||||
|
- deterministic tie-breaking and legacy zero-duration formatting.
|
||||||
|
- Game-detail route generation from `displayNumber`, including rejection of invalid
|
||||||
|
legacy display numbers.
|
||||||
|
- Exact internal Game selection, including a missing-result case when the requested
|
||||||
|
display number is absent from a stale or legacy detail payload.
|
||||||
|
|
||||||
|
After unit tests, run full web tests, changed-file lint, and the TypeScript/Vite build.
|
||||||
|
Review the markup for native keyboard interaction, heading order, visible status text,
|
||||||
|
and mobile layouts down to 320px.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Use `series.entries` for A/B score and `outcome.winnerTeamId` for the official
|
||||||
|
winner; never infer identity from score, array position, or blue/red side.
|
||||||
|
- Keep game-less adjudications visible without presenting `0 : 0` as a played score.
|
||||||
|
- Omit `durationSeconds === 0` because it represents missing legacy data.
|
||||||
|
- Use `displayNumber`, never Series-local `ordinal`, for the internal Game URL.
|
||||||
|
- Keep each Game row as one semantic anchor with no nested interactive control.
|
||||||
|
- Keep link text readable in both themes; coral may indicate interaction but must not
|
||||||
|
be the only visible cue.
|
||||||
|
- Never substitute another Game when the Game number explicitly requested by the URL
|
||||||
|
is not present in the internal-stat payload.
|
||||||
|
- Preserve all unrelated working-tree changes.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Change the public Competition contract, database schema, or projector.
|
||||||
|
- Add Series scheduling or external replay/venue data.
|
||||||
|
- Add a frontend dependency or test framework.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Present `completedAt` as a scheduled or actual start time.
|
||||||
|
- Reuse free-text `match.schedule` as official Series scheduling data.
|
||||||
|
- Parse `series.code` for identity, winner, or ordering.
|
||||||
|
- Make status or winner understandable only through color.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- A completed `2 : 1` Series appears as one chronological row with both teams, the
|
||||||
|
official score, round label, status, and an expandable three-Game history.
|
||||||
|
- In-progress Series retain already accepted Games and display `진행 중`.
|
||||||
|
- No-game decisions appear with the correct decision label and no misleading score
|
||||||
|
or start time.
|
||||||
|
- Date grouping and time display are stable in `Asia/Seoul` regardless of runtime
|
||||||
|
timezone.
|
||||||
|
- The layout is readable without horizontal scrolling at 320px and uses the wider
|
||||||
|
double-elimination page naturally on desktop.
|
||||||
|
- Each recorded Game can be opened by pointer or keyboard, lands on its matching
|
||||||
|
internal-stat Game, and provides a return link to the Competition result page.
|
||||||
|
- A temporarily stale or inconsistent detail payload shows an explicit missing-Game
|
||||||
|
state rather than silently rendering the first Game.
|
||||||
|
- Game rows expose an always-visible detail cue and coral hover, active, and focus
|
||||||
|
affordances without changing winner semantics.
|
||||||
|
- Focused/full tests, changed-file lint, and web build pass without modifying
|
||||||
|
unrelated work.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user approved the Series-centric, result-history-first direction and
|
||||||
|
requested implementation.
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# Spec: Team Progress Page UX Refresh
|
||||||
|
|
||||||
|
## Objective
|
||||||
|
|
||||||
|
Reorganize the team progress page around the participant's primary task: identify
|
||||||
|
the next opponent, understand the Series state, and copy the correct tournament
|
||||||
|
code without cross-referencing separate sections. Keep the existing Competition
|
||||||
|
API and visual language while making status, adjudicated results, copy feedback,
|
||||||
|
the roster, and past results clearer on desktop and mobile.
|
||||||
|
|
||||||
|
The primary user is a team participant preparing to join an official internal-match
|
||||||
|
game. Success means every active Series and its codes form one understandable work
|
||||||
|
area, human-facing Korean labels lead internal identifiers, and the copy flow is
|
||||||
|
accessible and explicit.
|
||||||
|
|
||||||
|
## Approved Product Decisions
|
||||||
|
|
||||||
|
- Group tournament codes under their matching active Series using `seriesId`.
|
||||||
|
- Label a Series-local game as `1세트`, `2세트`, and so on; retain global
|
||||||
|
`Game 19`-style numbers only as secondary metadata.
|
||||||
|
- Use the bracket's canonical visible round names from Competition round metadata:
|
||||||
|
upper round 1 is `브래킷 1R`, later upper rounds are `브래킷 상위 nR`, and
|
||||||
|
lower rounds are `브래킷 하위 nR`. Retain raw Series codes such as `WB_FINAL`
|
||||||
|
as secondary diagnostic text.
|
||||||
|
- Show pre-start and adjudicated Series without misleading `0–0` scores.
|
||||||
|
- Distinguish `부전승`, `기권승`, `판정승`, and `무승부` using the existing
|
||||||
|
outcome discriminator. Do not invent a free-form reason that is not public data.
|
||||||
|
- Make copy targets at least 44 CSS pixels high, uniquely label each button, keep
|
||||||
|
the complete code visible/selectable, and announce copy success or failure.
|
||||||
|
- Order the page as header, next matches with codes, compact roster, then recent
|
||||||
|
results. Show two recent results and collapse older entries.
|
||||||
|
- Preserve existing loading, selection, empty, error, revision-consistency, and
|
||||||
|
authorization behavior.
|
||||||
|
|
||||||
|
## Tech Stack
|
||||||
|
|
||||||
|
- React 19 and TypeScript 6 under `apps/web`
|
||||||
|
- Tailwind CSS 4 and daisyUI 5 using the repository's square bordered surfaces
|
||||||
|
- Node's built-in test runner for pure view-model behavior
|
||||||
|
- Existing `lucide-react` icon set; no new dependency
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
- Focused tests: `pnpm --filter web exec node --test --experimental-strip-types test/match-team-progress-view.test.ts`
|
||||||
|
- Full web tests: `pnpm --filter web test`
|
||||||
|
- Web lint: `pnpm --filter web lint`
|
||||||
|
- Web build: `pnpm --filter web build`
|
||||||
|
- Development server: `pnpm --filter web start:dev`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `apps/web/src/pages/MatchTeamProgressPage.tsx` owns queries, snapshot guards,
|
||||||
|
page ordering, and top-level team navigation.
|
||||||
|
- `apps/web/src/pages/match-team-progress-view.ts` owns pure grouping, ordering,
|
||||||
|
labels, code state, and copy-result behavior.
|
||||||
|
- `apps/web/src/components/competition/double-elimination-bracket-layout.ts`
|
||||||
|
remains the canonical source for visible bracket round names.
|
||||||
|
- `apps/web/src/components/competition/TeamTournamentCodes.tsx` owns code rows and
|
||||||
|
clipboard feedback.
|
||||||
|
- `apps/web/src/components/competition/TeamSeriesCard.tsx` owns the page-specific
|
||||||
|
Series summary, leaving bracket/history card geometry and behavior unchanged.
|
||||||
|
- `apps/web/test/match-team-progress-view.test.ts` specifies the new pure behavior.
|
||||||
|
|
||||||
|
## Code Style
|
||||||
|
|
||||||
|
Keep data transformation outside React and render semantic native controls:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const seriesCodes = tournamentCodesForSeries(
|
||||||
|
teamView.tournamentCodes,
|
||||||
|
series.seriesId,
|
||||||
|
);
|
||||||
|
|
||||||
|
<button aria-label={`${setLabel} 토너먼트 코드 복사`}>
|
||||||
|
복사
|
||||||
|
</button>
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `text-content-subtle` and `text-content-muted` for secondary text. Semantic
|
||||||
|
colors may provide a border or background accent, while normal-size text remains a
|
||||||
|
high-contrast base-content color.
|
||||||
|
|
||||||
|
## Testing Strategy
|
||||||
|
|
||||||
|
- Test code-to-Series association by exact `seriesId` and deterministic ordinal
|
||||||
|
ordering before adding the UI.
|
||||||
|
- Test bracket-aligned round labels, code availability/expiry state, unique copy
|
||||||
|
labels, and explicit clipboard success/failure results as pure functions.
|
||||||
|
- Test every page-specific Series lifecycle/outcome branch, including played and
|
||||||
|
administrative draws, so the local summary cannot drift silently.
|
||||||
|
- Run the complete web suite, lint, and build after the focused tests pass.
|
||||||
|
- When the in-app browser is available, runtime verification covers 320px, 768px,
|
||||||
|
1024px, and 1440px; keyboard focus, copy announcements, long-code reflow, and
|
||||||
|
console output are checked manually.
|
||||||
|
|
||||||
|
## Boundaries
|
||||||
|
|
||||||
|
### Always
|
||||||
|
|
||||||
|
- Join assignments to active Series only by the contract's `seriesId`.
|
||||||
|
- Keep the full tournament code selectable and copy the unmodified string.
|
||||||
|
- Preserve native link, button, list, table, heading, and disclosure semantics.
|
||||||
|
- Use the existing design tokens and icon dependency.
|
||||||
|
|
||||||
|
### Ask First
|
||||||
|
|
||||||
|
- Change the API or public contract.
|
||||||
|
- Add a dependency or browser-test framework.
|
||||||
|
- Change tournament-code authorization or visibility policy.
|
||||||
|
- Deploy, push, or alter CI.
|
||||||
|
|
||||||
|
### Never
|
||||||
|
|
||||||
|
- Infer a Series association from global game numbers.
|
||||||
|
- Display an adjudicated `0–0` as if it were a played result.
|
||||||
|
- Expose private facts or fabricate an adjudication reason.
|
||||||
|
- Hide copy failure or rely on color alone for state.
|
||||||
|
- Modify unrelated Competition, bracket, or theme behavior.
|
||||||
|
|
||||||
|
## Success Criteria
|
||||||
|
|
||||||
|
- Each active Series appears as a full-width next-match panel containing only its
|
||||||
|
own ordered code rows.
|
||||||
|
- Bracket-aligned labels lead raw Series codes, and Series-local set numbers lead
|
||||||
|
global game numbers.
|
||||||
|
- Ready Series show a pending score, while adjudicated results show their result
|
||||||
|
category instead of a numeric score.
|
||||||
|
- Copy buttons have unique accessible names, 44px targets, visible/live feedback,
|
||||||
|
and an explicit failure path.
|
||||||
|
- The roster uses Korean position labels in canonical role order, with the captain
|
||||||
|
marker close to the player name.
|
||||||
|
- At most two recent results are expanded by default; older results are available
|
||||||
|
through a keyboard-accessible disclosure.
|
||||||
|
- Focused and full tests, scoped lint, and build pass. Responsive runtime review is
|
||||||
|
recorded separately when the in-app browser is available.
|
||||||
|
|
||||||
|
## Verification Record
|
||||||
|
|
||||||
|
- Focused view-model tests: 9 passed.
|
||||||
|
- Full web suite: 88 passed without skips.
|
||||||
|
- Scoped ESLint for all team-progress files: passed.
|
||||||
|
- Production TypeScript/Vite build: passed; only the existing large-chunk warning
|
||||||
|
remains.
|
||||||
|
- Full repository lint remains blocked by pre-existing errors in unrelated files.
|
||||||
|
- Runtime screenshot/keyboard verification was not claimed because the required
|
||||||
|
in-app browser was unavailable in this session.
|
||||||
|
|
||||||
|
## Open Questions
|
||||||
|
|
||||||
|
None. The user approved the audit recommendations and requested implementation.
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
import type { TeamId } from "./ids.js";
|
import type { TeamId } from "./ids.js";
|
||||||
import type {
|
import type { FirstToSeriesRule, FixedGamesSeriesRule } from "./series.js";
|
||||||
FirstToSeriesRule,
|
|
||||||
FixedGamesSeriesRule,
|
|
||||||
} from "./series.js";
|
|
||||||
|
|
||||||
export type CompetitionFormatType =
|
export type CompetitionFormatType =
|
||||||
| "paired-series"
|
| "paired-series"
|
||||||
@@ -14,20 +11,21 @@ export interface PairedSeriesCompetitionFormat {
|
|||||||
rule: FixedGamesSeriesRule;
|
rule: FixedGamesSeriesRule;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type RoundRobinTieBreaker =
|
export type RoundRobinTieBreaker = "series-wins" | "game-diff" | "head-to-head";
|
||||||
| "series-wins"
|
|
||||||
| "game-diff"
|
export interface RoundRobinPairing {
|
||||||
| "head-to-head";
|
roundNumber: number;
|
||||||
|
matchNumber: number;
|
||||||
|
teamAId: TeamId;
|
||||||
|
teamBId: TeamId;
|
||||||
|
}
|
||||||
|
|
||||||
export interface RoundRobinCompetitionFormat {
|
export interface RoundRobinCompetitionFormat {
|
||||||
type: "round-robin";
|
type: "round-robin";
|
||||||
rule: FixedGamesSeriesRule;
|
rule: FixedGamesSeriesRule;
|
||||||
maxRounds?: number;
|
maxRounds?: number;
|
||||||
tieBreakers: [
|
pairings?: RoundRobinPairing[];
|
||||||
"series-wins",
|
tieBreakers: ["series-wins", "game-diff", "head-to-head"];
|
||||||
"game-diff",
|
|
||||||
"head-to-head",
|
|
||||||
];
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface DoubleEliminationSeriesRules {
|
export interface DoubleEliminationSeriesRules {
|
||||||
|
|||||||
@@ -68,12 +68,19 @@ export interface GrandFinalResetActivationRule {
|
|||||||
|
|
||||||
export type SeriesActivationRule = GrandFinalResetActivationRule;
|
export type SeriesActivationRule = GrandFinalResetActivationRule;
|
||||||
|
|
||||||
|
export interface SeriesSchedule {
|
||||||
|
date: string;
|
||||||
|
time: string | null;
|
||||||
|
timeZone: "Asia/Seoul";
|
||||||
|
}
|
||||||
|
|
||||||
export interface SeriesDefinition {
|
export interface SeriesDefinition {
|
||||||
id: SeriesId;
|
id: SeriesId;
|
||||||
code?: string;
|
code?: string;
|
||||||
stage: SeriesStage;
|
stage: SeriesStage;
|
||||||
slots: [SeriesSlotDefinition, SeriesSlotDefinition];
|
slots: [SeriesSlotDefinition, SeriesSlotDefinition];
|
||||||
rule: SeriesRule;
|
rule: SeriesRule;
|
||||||
|
schedule?: SeriesSchedule;
|
||||||
activation?: SeriesActivationRule;
|
activation?: SeriesActivationRule;
|
||||||
gameSlots: GameSlotDefinition[];
|
gameSlots: GameSlotDefinition[];
|
||||||
}
|
}
|
||||||
@@ -106,6 +113,7 @@ interface SeriesProjectionBase {
|
|||||||
code?: string;
|
code?: string;
|
||||||
stage: SeriesStage;
|
stage: SeriesStage;
|
||||||
rule: SeriesRule;
|
rule: SeriesRule;
|
||||||
|
schedule?: SeriesSchedule;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PlayedSeriesOutcome {
|
export interface PlayedSeriesOutcome {
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import type {
|
|||||||
CompetitionId,
|
CompetitionId,
|
||||||
CompletedSeriesProjection,
|
CompletedSeriesProjection,
|
||||||
InProgressSeriesProjection,
|
InProgressSeriesProjection,
|
||||||
|
RoundRobinCompetitionFormat,
|
||||||
SeriesOutcome,
|
SeriesOutcome,
|
||||||
TeamId,
|
TeamId,
|
||||||
} from "../src/index.js";
|
} from "../src/index.js";
|
||||||
@@ -26,3 +27,23 @@ export type InProgressSeriesCannotExposeOutcome = Expect<
|
|||||||
export type LegacyBracketModeIsNotACompetitionFormat = Expect<
|
export type LegacyBracketModeIsNotACompetitionFormat = Expect<
|
||||||
Not<IsAssignable<{ type: "bracket" }, CompetitionFormat>>
|
Not<IsAssignable<{ type: "bracket" }, CompetitionFormat>>
|
||||||
>;
|
>;
|
||||||
|
|
||||||
|
type ExplicitRoundRobinPairing = NonNullable<
|
||||||
|
RoundRobinCompetitionFormat["pairings"]
|
||||||
|
>[number];
|
||||||
|
|
||||||
|
export type ExplicitRoundRobinPairingsAreOptional = Expect<
|
||||||
|
IsAssignable<{}, Pick<RoundRobinCompetitionFormat, "pairings">>
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type ExplicitRoundRobinPairingsAreTeamIdBased = Expect<
|
||||||
|
IsAssignable<
|
||||||
|
ExplicitRoundRobinPairing,
|
||||||
|
{
|
||||||
|
roundNumber: number;
|
||||||
|
matchNumber: number;
|
||||||
|
teamAId: TeamId;
|
||||||
|
teamBId: TeamId;
|
||||||
|
}
|
||||||
|
>
|
||||||
|
>;
|
||||||
Reference in new issue
Block a user