Compare commits

..
3 Commits
Author SHA1 Message Date
dahyeon a88562b208 fix: stabilize competition results flow 2026-07-13 13:55:08 +00:00
dahyeon 3bd3120eb1 feat: link competition games to detail analysis
Route each result-history Game by its global display number and preserve the Competition return target. Refuse stale detail fallbacks so a missing requested Game cannot silently show another Game.
2026-07-13 10:41:44 +00:00
dahyeon 3c60081ece feat: add competition series result history 2026-07-13 09:39:26 +00:00
30 changed files with 1249 additions and 116 deletions

No files matched your search

@@ -66,7 +66,10 @@ describe('CompetitionCommandService', () => {
$inc: { revision: 1 },
$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.commitTransaction).not.toHaveBeenCalled();
});
@@ -321,7 +321,7 @@ export class CompetitionCommandService {
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
@@ -475,7 +475,7 @@ export class CompetitionCommandService {
phase: projection.phase,
},
},
{ new: true, runValidators: true, session },
{ returnDocument: 'after', runValidators: true, session },
)
.lean()
.exec();
@@ -1,4 +1,8 @@
import { ConflictException, ForbiddenException } from '@nestjs/common';
import {
ConflictException,
ForbiddenException,
NotFoundException,
} from '@nestjs/common';
import { Types } from 'mongoose';
import { ConnectionService } from '../global/database/connection.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 () => {
const service = createService(createHarness());
@@ -22,6 +22,17 @@ export interface CompetitionScope {
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 {
series?: Array<Record<string, unknown>>;
gameSlots?: Array<Record<string, unknown>>;
@@ -68,15 +79,21 @@ export class CompetitionQueryService {
}
public async getTeamView(
scope: CompetitionScope & { userId: mongoose.Types.ObjectId },
scope: TeamViewScope,
): Promise<TeamCompetitionViewResponse> {
const competition = (await this.getCompetition(scope)) as Competition & {
_id: PersistenceId;
};
const team = competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
const requestedTeamId = scope.teamId;
const team = requestedTeamId
? competition.teams.find(({ teamId }) => sameId(teamId, requestedTeamId))
: competition.teams.find(({ members }) =>
members.some(({ userId }) => sameId(userId, scope.userId)),
);
if (!team) {
if (requestedTeamId) {
throw new NotFoundException('Competition team not found.');
}
throw new ForbiddenException(
'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';
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 response = { setHeader: jest.fn() };
@@ -17,18 +17,14 @@ describe('CompetitionController', () => {
response as never,
);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getDetail,
),
).toBe(true);
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype.getTeamView,
),
).not.toBe(true);
for (const method of ['getDetail', 'getTeamView'] as const) {
expect(
Reflect.getMetadata(
METADATA_KEY_IS_PUBLIC_ACCESS_ALLOWED,
CompetitionController.prototype[method],
),
).toBe(true);
}
expect(response.setHeader).toHaveBeenCalledWith('ETag', '"7"');
expect(result).toMatchObject({ revision: 7 });
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', () => {
for (const method of [
'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')
@AllowPublicAccess()
public async getTeamView(
@CurrentUser() currentUser: UserDocument,
@CurrentUser() currentUser: UserDocument | undefined,
@Param('communityId', ParseObjectIdPipe)
communityId: mongoose.Types.ObjectId,
@Param('matchId', ParseObjectIdPipe) matchId: mongoose.Types.ObjectId,
@Query('teamId') requestedTeamId?: string,
@Res({ passthrough: true }) response?: Response,
): Promise<TeamCompetitionViewResponse> {
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({
communityId,
matchId,
userId: currentUser._id,
...(teamId ? { teamId } : { userId: currentUser!._id }),
});
response?.setHeader('ETag', revisionEtag(result.revision));
return result;
@@ -298,6 +314,21 @@ function requireCommandHeaders(
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 {
const revision = parseRevision(ifMatch);
if (revision === undefined) {
@@ -1,9 +1,75 @@
import mongoose from 'mongoose';
import {
ConnectionService,
resolveMongoAppName,
resolveMongoConnectionOptions,
resolveMongoDbName,
} 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', () => {
it('uses production database only for prod', () => {
expect(resolveMongoDbName('prod')).toBe('lolympus');
@@ -39,6 +39,7 @@ export function resolveMongoConnectionOptions(
export class ConnectionService implements OnModuleInit {
private readonly logger = new Logger(ConnectionService.name);
private connection: mongoose.Connection | null = null;
private connectionPromise: Promise<mongoose.Connection> | null = null;
constructor(private readonly secretService: SecretService) {}
private tournamentModels: Map<string, mongoose.Model<any>> | null = null;
@@ -51,35 +52,49 @@ export class ConnectionService implements OnModuleInit {
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(
'MONGODB_CONNECTION_STRING',
);
const dbName = resolveMongoDbName();
const appName = resolveMongoAppName();
const connectionOptions = resolveMongoConnectionOptions(dbName, appName);
const defaultConnection = await mongoose
const connection = await mongoose
.createConnection(connectionString, connectionOptions)
.asPromise();
this.connection = defaultConnection;
this.connection = connection;
this.tournamentModels = null;
this.logger.log(
`MongoDB connection created. dbName=${dbName} appName=${appName} autoIndex=${
connectionOptions.autoIndex === true
}`,
);
return this.connection;
return connection;
}
public async getModel<K extends keyof TournamentModelTypes>(
modelKey: K,
): Promise<mongoose.Model<TournamentModelTypes[K]>> {
const connection = await this.getConnection();
if (this.tournamentModels)
return this.tournamentModels.get(modelKey) as mongoose.Model<
TournamentModelTypes[K]
>;
const models = new Map<K, mongoose.Model<TournamentModelTypes[K]>>();
const connection = await this.getConnection();
tournamentModelDefinitions.forEach((modelDefinition) => {
applyMongoosePerformancePlugin(modelDefinition.schema);
@@ -36,7 +36,7 @@ describe('CompetitionAssignmentProvisioner', () => {
}),
},
expect.objectContaining({
new: true,
returnDocument: 'after',
session: harness.session,
sort: { expiresAt: 1 },
}),
@@ -122,14 +122,14 @@ describe('CompetitionAssignmentProvisioner', () => {
expect(harness.assignmentModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: assignmentId, state: 'reserved' },
{ $set: expect.objectContaining({ state: 'released' }) },
{ new: true, session: harness.session },
{ returnDocument: 'after', session: harness.session },
);
expect(harness.codeModel.findOneAndUpdate).toHaveBeenCalledWith(
{ _id: harness.codeId, state: 'reserved' },
expect.objectContaining({
$set: expect.objectContaining({ state: 'released' }),
}),
{ new: true, session: harness.session },
{ returnDocument: 'after', session: harness.session },
);
expect(harness.matchModel.updateOne).toHaveBeenCalledWith(
{ _id: harness.matchId },
@@ -156,7 +156,7 @@ export class CompetitionAssignmentProvisioner {
const assignment = (await params.AssignmentModel.findOneAndUpdate(
{ _id: params.assignment._id, state: 'reserved' },
{ $set: { state: 'released', releasedAt } },
{ new: true, session },
{ returnDocument: 'after', session },
).exec()) as AssignmentRecord | null;
if (!assignment) {
await session.commitTransaction();
@@ -173,7 +173,7 @@ export class CompetitionAssignmentProvisioner {
reservedAt: 1,
},
},
{ new: true, session },
{ returnDocument: 'after', session },
).exec()) as CodeRecord | null;
if (!code) {
throw new Error(
@@ -354,7 +354,7 @@ export class CompetitionAssignmentProvisioner {
gameNumber: params.displayNumber,
},
{ $set: { gameNumber: params.displayNumber } },
{ new: true, session: params.session },
{ returnDocument: 'after', session: params.session },
).exec()) as CodeRecord | null;
if (promoted) return promoted;
}
@@ -377,7 +377,11 @@ export class CompetitionAssignmentProvisioner {
reservedAt: new Date(),
},
},
{ new: true, session: params.session, sort: { expiresAt: 1 } },
{
returnDocument: 'after',
session: params.session,
sort: { expiresAt: 1 },
},
).exec()) as CodeRecord | null;
}
@@ -110,7 +110,7 @@ export class CompetitionOutboxProcessor
$unset: { lastError: 1 },
},
{
new: true,
returnDocument: 'after',
sort: { availableAt: 1, revision: 1, _id: 1 },
},
)
+5 -2
View File
@@ -257,12 +257,15 @@ export function useCompetition(
export function useTeamCompetition(
matchId: string | undefined,
communityId = DEFAULT_COMMUNITY_ID,
teamId?: string,
) {
return useQuery({
queryKey: ['competition-team', communityId, matchId ?? null],
queryKey: ['competition-team', communityId, matchId ?? null, teamId ?? null],
queryFn: () =>
apiFetch<TeamCompetitionViewResponse>(
`/communities/${communityId}/matches/${matchId}/competition/team`,
`/communities/${communityId}/matches/${matchId}/competition/team${
teamId ? `?teamId=${encodeURIComponent(teamId)}` : ''
}`,
),
enabled: Boolean(communityId && matchId),
retry: false,
@@ -0,0 +1,133 @@
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="block min-h-11 border-l-2 border-l-transparent px-2 py-2 text-xs text-base-content transition-colors hover:border-l-primary 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="min-h-11 border-l-2 border-l-transparent px-2 py-2 text-xs text-base-content">
{content}
</div>
)}
</li>
);
})}
</ol>
);
}
function GameHistoryRowContent({
game,
winnerName,
duration,
linked,
}: {
game: CompetitionSeriesHistoryRow["games"][number];
winnerName: string;
duration: string | null;
linked: boolean;
}) {
return (
<span
className={
linked
? "grid grid-cols-[3.75rem_3.25rem_minmax(0,1fr)_3.5rem] items-center gap-2 md:grid-cols-[4.5rem_4rem_minmax(0,1fr)_4.5rem_6rem] md:gap-4"
: "grid grid-cols-[3.75rem_3.25rem_minmax(0,1fr)_3.5rem] items-center gap-2 md:grid-cols-[4.5rem_4rem_minmax(0,1fr)_4.5rem] md:gap-4"
}
>
<span className="font-bold text-content-muted">
Game {game.ordinal}
</span>
<time
dateTime={game.startedAt}
className="font-mono tabular-nums text-content-muted"
>
{formatCompetitionHistoryTime(game.startedAt) ?? "—"}
</time>
<span className="min-w-0 break-words font-semibold">
{winnerName} 승
</span>
<span
className="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="col-span-4 mt-1 flex items-center justify-end gap-0.5 font-bold text-content-subtle md:col-span-1 md:mt-0">
<span>상세 분석</span>
<ChevronRight
className="h-3.5 w-3.5 shrink-0 text-primary"
aria-hidden="true"
/>
</span>
)}
</span>
);
}
@@ -5,6 +5,7 @@ import type {
TeamId,
} from "@lolympus/contracts";
import { Link } from "react-router";
import { CompetitionSeriesHistory } from "./CompetitionSeriesHistory";
import { DoubleEliminationBracket } from "./DoubleEliminationBracket";
import { createCompetitionBracketLayout } from "./competition-display-layout";
import { bracketRoundLabel } from "./double-elimination-bracket-layout";
@@ -44,7 +45,7 @@ export function CompetitionResults({
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"
>
내 팀 진행
팀 진행
</Link>
</div>
</header>
@@ -81,28 +82,12 @@ export function CompetitionResults({
</p>
)}
{projection.games.length > 0 && (
<div className="border border-base-content/10 bg-base-content/[0.02] p-4">
<h3 className="text-xs font-bold uppercase tracking-wider text-base-content/40">
완료된 게임
</h3>
<ul className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-3">
{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>
)}
<CompetitionSeriesHistory
communityId={competition.communityId}
matchId={competition.matchId}
projection={projection}
teamById={teamById}
/>
</section>
);
}
@@ -0,0 +1,318 @@
import type {
CommunityId,
CompetitionProjection,
CompetitionTeamView,
MatchId,
TeamId,
} from "@lolympus/contracts";
import { ChevronDown } from "lucide-react";
import { useLocation } from "react-router";
import {
createCompetitionSeriesHistory,
formatCompetitionHistoryDate,
formatCompetitionHistoryTime,
getSeriesHistoryStatusLabel,
shouldDisplaySeriesHistoryScore,
type CompetitionSeriesHistoryRow,
} 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,
projection,
teamById,
}: {
communityId: CommunityId;
matchId: MatchId;
projection: CompetitionProjection;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
const location = useLocation();
const historyBackTo = `${location.pathname}${location.search}${location.hash}`;
const history = createCompetitionSeriesHistory(projection);
if (history.length === 0) return null;
return (
<section
className="competition-series-history border border-base-content/10 bg-base-100"
aria-labelledby="competition-series-history-heading"
>
<header className="border-b border-base-content/10 px-4 py-3">
<h3
id="competition-series-history-heading"
className="text-sm font-bold"
>
경기 결과 기록
</h3>
<p className="mt-0.5 text-xs text-content-muted">
진행 중인 시리즈와 종료 결과를 실제 경기 기록 순서로 보여줍니다.
</p>
</header>
<div>
{history.map((day) => {
const headingId = `competition-history-${day.dateKey}`;
return (
<section key={day.dateKey} aria-labelledby={headingId}>
<h4
id={headingId}
className="border-b border-base-content/10 bg-base-200/60 px-4 py-3 text-sm font-bold"
>
{day.dateKey === "unknown" ? (
formatCompetitionHistoryDate(day.dateKey)
) : (
<time dateTime={day.dateKey}>
{formatCompetitionHistoryDate(day.dateKey)}
</time>
)}
</h4>
<ol className="divide-y divide-base-content/10">
{day.rows.map((row) => (
<li key={row.series.seriesId}>
<SeriesHistoryRow
row={row}
teamById={teamById}
communityId={communityId}
matchId={matchId}
historyBackTo={historyBackTo}
/>
</li>
))}
</ol>
</section>
);
})}
</div>
</section>
);
}
function SeriesHistoryRow({
row,
teamById,
communityId,
matchId,
historyBackTo,
}: {
row: CompetitionSeriesHistoryRow;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
communityId: CommunityId;
matchId: MatchId;
historyBackTo: string;
}) {
if (row.games.length === 0) {
return (
<SeriesSummary row={row} teamById={teamById} hasGameDetails={false} />
);
}
return (
<details className="group">
<summary className="list-none cursor-pointer focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary [&::-webkit-details-marker]:hidden">
<SeriesSummary row={row} teamById={teamById} hasGameDetails />
</summary>
<CompetitionGameHistory
games={row.games}
teamById={teamById}
communityId={communityId}
matchId={matchId}
historyBackTo={historyBackTo}
/>
</details>
);
}
function SeriesSummary({
row,
teamById,
hasGameDetails,
}: {
row: CompetitionSeriesHistoryRow;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
hasGameDetails: boolean;
}) {
const { series } = row;
const statusLabel = getSeriesHistoryStatusLabel(series);
const timeLabel =
row.timestampSource === "game-start"
? formatCompetitionHistoryTime(row.occurredAt)
: null;
const roundLabel = bracketRoundLabel(
series.stage.type,
series.stage.roundNumber,
);
return (
<span className="block px-4 py-3 lg:grid lg:min-h-18 lg:grid-cols-[4.5rem_5rem_9rem_minmax(0,1fr)_6.5rem] lg:items-center lg:gap-4">
<span className="flex min-w-0 items-center gap-2 lg:contents">
<HistoryTime
occurredAt={row.occurredAt}
timeLabel={timeLabel}
/>
<StatusLabel
label={statusLabel}
inProgress={series.status === "in-progress"}
/>
<span className="min-w-0 break-words text-xs leading-4 text-content-muted">
{roundLabel}
</span>
</span>
<span className="mt-3 block lg:mt-0">
<SeriesMatchup row={row} teamById={teamById} />
</span>
<span className="mt-2 flex min-h-6 items-center justify-end text-xs font-bold text-content-muted lg:mt-0">
{hasGameDetails ? (
<>
<span className="group-open:hidden">{row.games.length}게임 보기</span>
<span className="hidden group-open:inline">게임 접기</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>개별 기록 없음</span>
)}
</span>
</span>
);
}
function HistoryTime({
occurredAt,
timeLabel,
}: {
occurredAt: string;
timeLabel: string | null;
}) {
return timeLabel ? (
<time
dateTime={occurredAt}
className="shrink-0 font-mono text-sm font-bold tabular-nums"
>
{timeLabel}
</time>
) : (
<span className="shrink-0 text-sm text-content-muted">
<span aria-hidden="true">—</span>
<span className="sr-only">시작 시간 기록 없음</span>
</span>
);
}
function StatusLabel({
label,
inProgress,
}: {
label: string;
inProgress: boolean;
}) {
return (
<span
className={`shrink-0 px-1.5 py-0.5 text-xs font-bold ${
inProgress
? "border-l-2 border-primary bg-primary/10 text-base-content"
: "border-l-2 border-base-content/15 bg-base-200 text-base-content"
}`}
>
{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 officialWinnerTeamId =
row.series.status === "completed" && row.series.outcome.type !== "draw"
? row.series.outcome.winnerTeamId
: null;
const winnerAnnouncement = officialWinnerTeamId
? `, ${teamName(officialWinnerTeamId, teamById)} 승`
: "";
const accessibleResult = showScore
? `${teamAName} ${entryA.gameWins} 대 ${entryB.gameWins} ${teamBName}${winnerAnnouncement}`
: `${teamAName} 대 ${teamBName}, ${getSeriesHistoryStatusLabel(row.series)}${winnerAnnouncement}`;
return (
<>
<span
className="grid grid-cols-[minmax(0,1fr)_3.5rem_minmax(0,1fr)] items-center gap-2"
aria-hidden="true"
>
<TeamName name={teamAName} winner={teamAWon} align="right" />
<span className="flex items-center justify-center gap-1 font-mono text-base font-bold tabular-nums">
{showScore ? (
<>
<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 className="text-content-disabled">—</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={`min-w-0 break-words text-sm leading-5 ${
align === "right" ? "text-right" : "text-left"
} ${winner ? "font-bold text-base-content" : "text-content-subtle"}`}
aria-hidden="true"
>
{name}
{winner && (
<span className="ml-1 text-xs font-bold text-base-content">승</span>
)}
</span>
);
}
function teamName(
teamId: TeamId,
teamById: ReadonlyMap<TeamId, CompetitionTeamView>,
): string {
return teamById.get(teamId)?.name ?? "알 수 없는 팀";
}
@@ -8,6 +8,7 @@ import type {
DoubleEliminationBracketLayout,
} from "./double-elimination-bracket-layout";
import { DOUBLE_ELIMINATION_BRACKET_GEOMETRY } from "./double-elimination-bracket-layout";
import { DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS } from "./competition-display-layout";
import { DoubleEliminationMobileBracket } from "./DoubleEliminationMobileBracket";
import { SeriesScoreCard } from "./SeriesScoreCard";
@@ -57,7 +58,9 @@ function DesktopBracket({
);
return (
<div className="hidden xl:block">
<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>
승자조와 패자조는 같은 시간축을 공유하며 오른쪽 결승에서 합류합니다.
@@ -1,12 +1,10 @@
import type {
CompetitionDetailResponse,
MatchGameMode,
} from "@lolympus/contracts";
import type { CompetitionDetailResponse } from "@lolympus/contracts";
import { createDoubleEliminationBracketLayout } from "./double-elimination-bracket-layout.ts";
export function matchPageMaxWidthClass(gameMode: MatchGameMode): string {
return gameMode === "double-elimination" ? "max-w-[1600px]" : "max-w-5xl";
}
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,
@@ -4,6 +4,7 @@ import type {
IsoDateTime,
SeriesProjection,
} from "@lolympus/contracts";
import { internalMatchGamePath } from "../../lib/internal-match-routes.ts";
export type CompetitionSeriesHistorySeries = Extract<
SeriesProjection,
@@ -24,6 +25,27 @@ export interface CompetitionSeriesHistoryDay {
type HistoryProjection = Pick<CompetitionProjection, "series" | "games">;
const KOREAN_WEEKDAYS = [
"일",
"월",
"화",
"수",
"목",
"금",
"토",
] as const;
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",
@@ -95,6 +117,16 @@ export function getSeriesHistoryStatusLabel(
}
}
export function shouldDisplaySeriesHistoryScore(
series: CompetitionSeriesHistorySeries,
): boolean {
if (series.status === "in-progress") return true;
if (series.outcome.type === "played") return true;
return (
series.outcome.type === "draw" && series.outcome.basis.type === "played"
);
}
export function formatSeriesGameDuration(
durationSeconds: number,
): string | null {
@@ -109,6 +141,42 @@ export function formatSeriesGameDuration(
return `${minutes}:${padNumber(seconds)}`;
}
export function formatCompetitionHistoryDate(dateKey: string): string {
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 `${padNumber(month)}월 ${padNumber(day)}일 (${KOREAN_WEEKDAYS[date.getUTCDay()]})`;
}
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 compareGames(
left: CompetitionGameView,
right: CompetitionGameView,
+6
View File
@@ -122,6 +122,12 @@ body {
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
}
/* 경기 결과 기록의 링크 강조는 양쪽 테마에서 같은 브랜드 코랄을 쓴다.
전역 dark primary는 유지해 다른 화면의 기존 색상 의미를 바꾸지 않는다. */
.competition-series-history {
--color-primary: oklch(0.708008 0.234375 24);
}
/* ── 실시간 입찰 피드백 모션 ──
입찰가 갱신 시 pop(스케일 펄스), 내가 밀렸을 때 shake(주의 환기). */
@keyframes lts-bid-pop {
@@ -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
);
}
+2 -2
View File
@@ -28,7 +28,7 @@ import {
import { RankBadge } from "../components/RankBadge";
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
import { CompetitionResults } from "../components/competition/CompetitionResults";
import { matchPageMaxWidthClass } from "../components/competition/competition-display-layout";
import { MATCH_PAGE_MAX_WIDTH_CLASS } from "../components/competition/competition-display-layout";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api";
import { profileIconUrl } from "../lib/ddragon";
@@ -1795,7 +1795,7 @@ export default function MatchDetailPage() {
return (
<main
className={`mx-auto px-4 py-6 sm:px-6 ${
matchPageMaxWidthClass(matchQuery.data.gameMode)
MATCH_PAGE_MAX_WIDTH_CLASS
}`}
>
<Link
+20 -4
View File
@@ -28,6 +28,7 @@ import {
internalMatchDetailPath,
internalMatchGamePath,
} from "../lib/internal-match-routes";
import { selectInternalMatchGame } from "../lib/internal-match-game-selection";
import { LANE_LABELS } from "../lib/riot-history";
import {
filterTimelineEvents,
@@ -1681,14 +1682,29 @@ export default function MatchGameDetailPage() {
);
}
const selectedGame =
detail.games.find((game) => game.gameNumber === requestedGameNumber) ??
detail.games[0];
const selectedGame = selectInternalMatchGame(
detail.games,
requestedGameNumber,
);
if (!selectedGame) {
const hasRecordedGames = detail.games.length > 0;
const requestedGameLabel =
Number.isSafeInteger(requestedGameNumber) && requestedGameNumber > 0
? `${requestedGameNumber}경기`
: "요청한 경기";
return (
<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
to={backTarget.to}
className="btn btn-ghost btn-sm mt-4"
+86 -5
View File
@@ -1,18 +1,27 @@
import type { CompetitionDetailResponse } from "@lolympus/contracts";
import { useEffect, useRef, useState } from "react";
import { Link, useParams } from "react-router";
import { Link, useParams, useSearchParams } from "react-router";
import { useCompetition, useTeamCompetition } from "../api/hooks";
import { SeriesScoreCard } from "../components/competition/SeriesScoreCard";
import { DEFAULT_COMMUNITY_ID } from "../config";
import {
getTeamProgressErrorContent,
isConsistentTeamProgressSnapshot,
shouldOfferTeamSelection,
type TeamProgressErrorContent,
} from "./match-team-progress-state";
export default function MatchTeamProgressPage() {
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 teamQuery = useTeamCompetition(id, DEFAULT_COMMUNITY_ID);
const teamQuery = useTeamCompetition(
id,
DEFAULT_COMMUNITY_ID,
selectedTeamId,
);
const refetchCompetition = competitionQuery.refetch;
const refetchTeam = teamQuery.refetch;
const [copiedSlotId, setCopiedSlotId] = useState<string | null>(null);
@@ -63,11 +72,24 @@ export default function MatchTeamProgressPage() {
);
}
if (isSelectingTeam && competition) {
return <TeamSelectionState competition={competition} matchId={id} />;
}
if (competitionQuery.isLoading || teamQuery.isLoading) {
return <TeamProgressLoadingState />;
}
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 (
<TeamProgressProblemState
content={getTeamProgressErrorContent(
@@ -142,12 +164,20 @@ export default function MatchTeamProgressPage() {
<header className="mb-6 border-b border-base-content/10 pb-5">
<p className="text-[11px] font-bold uppercase tracking-wider text-base-content/35">
My Competition
{selectedTeamId ? "Team Competition" : "My Competition"}
</p>
<h1 className="mt-1 text-2xl font-black">{team?.name ?? "내 팀"}</h1>
<h1 className="mt-1 text-2xl font-black">
{team?.name ?? (selectedTeamId ? "팀" : "내 팀")}
</h1>
<p className="mt-1 text-sm text-base-content/45">
우리 팀의 공식 대진과 토너먼트 코드는 이 페이지에서만 표시됩니다.
해당 팀의 공식 대진과 토너먼트 코드가 표시됩니다.
</p>
<Link
to={`/match/${id}/team?select=1`}
className="mt-2 inline-flex text-xs text-base-content/40 hover:text-primary"
>
다른 팀 보기
</Link>
</header>
<section className="mb-6" aria-labelledby="active-series-heading">
@@ -279,6 +309,57 @@ export default function MatchTeamProgressPage() {
);
}
function TeamSelectionState({
competition,
matchId,
}: {
competition: CompetitionDetailResponse;
matchId: string | undefined;
}) {
return (
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
<Link
to={`/match/${matchId}`}
className="mb-5 inline-flex text-xs text-base-content/40 hover:text-base-content"
>
← 내전 상세로
</Link>
<header className="mb-6 border-b border-base-content/10 pb-5">
<p className="text-[11px] font-bold uppercase tracking-wider text-base-content/35">
Team Competition
</p>
<h1 className="mt-1 text-2xl font-black">팀 선택</h1>
<p className="mt-1 text-sm text-base-content/45">
진행 상황과 토너먼트 코드를 확인할 팀을 선택해 주세요.
</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 items-center justify-between gap-3 border border-base-content/10 bg-base-100 px-4 py-4 hover:border-primary/30 hover:text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<span className="min-w-0 truncate text-sm font-bold">
{team.name}
</span>
<span className="shrink-0 text-xs text-base-content/35">
{team.members.length}명
</span>
</Link>
</li>
))}
</ul>
) : (
<EmptyState message="구성된 팀이 없습니다." />
)}
</main>
);
}
function TeamProgressLoadingState() {
return (
<main
@@ -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(
errors: readonly unknown[],
): TeamProgressErrorContent {
const statuses = errors.flatMap((error) => {
if (typeof error !== "object" || error === null || !("status" in error)) {
return [];
}
return typeof error.status === "number" ? [error.status] : [];
});
const statuses = errorStatuses(errors);
if (statuses.includes(401)) {
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 {
return (
error instanceof TypeError ||
@@ -9,10 +9,15 @@ import type {
TeamId,
} from "@lolympus/contracts";
import {
competitionHistoryGameDetailPath,
createCompetitionSeriesHistory,
formatCompetitionHistoryDate,
formatCompetitionHistoryTime,
formatSeriesGameDuration,
getSeriesHistoryStatusLabel,
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");
@@ -66,6 +71,40 @@ test("aggregates Games under their Series and preserves Series slot scores", ()
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",
@@ -265,6 +304,80 @@ test("returns explicit status labels for played and adjudicated outcomes", () =>
);
});
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");
@@ -272,6 +385,15 @@ test("formats recorded Game duration and omits unknown legacy zero values", () =
assert.equal(formatSeriesGameDuration(-1), null);
});
test("formats history dates and times explicitly in Asia/Seoul", () => {
assert.equal(formatCompetitionHistoryDate("2026-07-13"), "07월 13일 (월)");
assert.equal(
formatCompetitionHistoryTime("2026-07-12T15:05:00.000Z"),
"00:05",
);
assert.equal(formatCompetitionHistoryDate("unknown"), "일시 정보 없음");
});
function playedSeriesWithGame({
id,
displayOrder,
@@ -10,8 +10,9 @@ import type {
TeamId,
} from "@lolympus/contracts";
import {
DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS,
MATCH_PAGE_MAX_WIDTH_CLASS,
createCompetitionBracketLayout,
matchPageMaxWidthClass,
} from "../src/components/competition/competition-display-layout.ts";
import {
createDoubleEliminationBracketLayout,
@@ -83,10 +84,13 @@ test("places the canonical four-team DAG in shared time columns", () => {
assert.equal(nodeFor(layout, ids.GF).lane, "final");
});
test("selects the wide page grid only for double-elimination matches", () => {
assert.equal(matchPageMaxWidthClass("double-elimination"), "max-w-[1600px]");
assert.equal(matchPageMaxWidthClass("pair"), "max-w-5xl");
assert.equal(matchPageMaxWidthClass("round-robin"), "max-w-5xl");
test("keeps the match page narrow and gives only the desktop bracket a wide viewport", () => {
assert.equal(MATCH_PAGE_MAX_WIDTH_CLASS, "max-w-5xl");
assert.match(DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS, /max-w-\[1600px\]/);
assert.match(
DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS,
/w-\[calc\(100vw-3rem\)\]/,
);
});
test("selects the bracket only for a coherent double-elimination snapshot", () => {
@@ -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);
});
@@ -3,8 +3,20 @@ import test from "node:test";
import {
getTeamProgressErrorContent,
isConsistentTeamProgressSnapshot,
shouldOfferTeamSelection,
} 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", () => {
assert.equal(
isConsistentTeamProgressSnapshot({ revision: 7 }, { revision: 7 }),
+103 -22
View File
@@ -27,13 +27,13 @@ and preserve all current Competition/API contracts.
**Acceptance criteria:**
- [ ] Tests cover Series aggregation, ordinal Game order, KST date boundaries,
- [x] Tests cover Series aggregation, ordinal Game order, KST date boundaries,
chronological order, outcome variants, and deterministic fallbacks.
- [ ] The focused test fails because the model module does not yet exist.
- [x] The focused test fails because the model module does not yet exist.
**Verification:**
- [ ] Run the focused Node test and record the expected RED failure.
- [x] Run the focused Node test and record the expected RED failure.
**Files likely touched:**
@@ -43,14 +43,14 @@ and preserve all current Competition/API contracts.
**Acceptance criteria:**
- [ ] Only recorded in-progress and completed Series are returned.
- [ ] Date grouping and format helpers are explicitly KST-aware.
- [ ] Decision outcomes and missing legacy durations remain distinguishable.
- [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:**
- [ ] Focused history tests pass.
- [ ] Existing web tests still pass.
- [x] Focused history tests pass.
- [x] Existing web tests still pass.
**Files likely touched:**
@@ -59,7 +59,7 @@ and preserve all current Competition/API contracts.
### Checkpoint: Model
- [ ] Pure tests pass without a React or browser dependency.
- [x] Pure tests pass without a React or browser dependency.
### Phase 2: Responsive Result UI
@@ -67,16 +67,16 @@ and preserve all current Competition/API contracts.
**Acceptance criteria:**
- [ ] Desktop uses a flat schedule-like row; mobile stacks metadata and matchup
- [x] Desktop uses a flat schedule-like row; mobile stacks metadata and matchup
without horizontal scrolling.
- [ ] Status and official winner are communicated with visible text and typography,
- [x] Status and official winner are communicated with visible text and typography,
not color alone.
- [ ] Game-less decisions do not show fake start times or `0 : 0`.
- [x] Game-less decisions do not show fake start times or `0 : 0`.
**Verification:**
- [ ] Changed component files pass ESLint.
- [ ] Web build succeeds.
- [x] Changed component files pass ESLint.
- [x] Web build succeeds.
**Files likely touched:**
@@ -86,15 +86,16 @@ and preserve all current Competition/API contracts.
**Acceptance criteria:**
- [ ] Each Series with Games exposes a native keyboard-operable disclosure.
- [ ] Games use Series-local ordinal, team-ID winner lookup, and omit unknown
- [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.
- [ ] The old completed-Game mini-card block is removed.
- [x] The old completed-Game mini-card block is removed.
**Verification:**
- [ ] Full web tests, lint, and build pass.
- [ ] Source review checks heading order, disclosure semantics, and 320px layout.
- [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:**
@@ -103,9 +104,87 @@ and preserve all current Competition/API contracts.
### Checkpoint: Complete
- [ ] All specification success criteria are met.
- [ ] Git diff contains only the feature spec, plan, tests, model, and UI integration.
- [ ] Unrelated working-tree files are unchanged.
- [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
@@ -116,6 +195,8 @@ and preserve all current Competition/API contracts.
| 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
+34 -3
View File
@@ -27,6 +27,16 @@ times, venues, replay links, or team logos.
- 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
@@ -48,9 +58,13 @@ times, venues, replay links, or team logos.
- `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, responsive Series rows, and Game disclosures.
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.
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.
@@ -84,6 +98,10 @@ Develop the pure model test-first. Cover:
- 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,
@@ -97,6 +115,12 @@ and mobile layouts down to 320px.
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
@@ -123,7 +147,14 @@ and mobile layouts down to 320px.
timezone.
- The layout is readable without horizontal scrolling at 320px and uses the wider
double-elimination page naturally on desktop.
- Focused/full tests, lint, and web build pass without modifying unrelated work.
- 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