Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2004ea03fe | ||
|
|
8ec9edc35f | ||
|
|
61f1db0e6a | ||
|
|
c9140b8622 | ||
|
|
4e10998794 | ||
|
|
b115072005 | ||
|
|
03e88a03bc | ||
|
|
43c25c05cd | ||
|
|
dc77b37494 | ||
|
|
bb32c26694 | ||
|
|
81b951889f | ||
|
|
96bae0ce28 | ||
|
|
a88562b208 | ||
|
|
3bd3120eb1 | ||
|
|
3c60081ece |
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
|
||||
@@ -28,6 +28,8 @@ website/LICENSE
|
||||
!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
|
||||
!skills/**/*.md
|
||||
/tmp/
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -51,6 +51,11 @@ export interface SeriesDefinition {
|
||||
{ position: 'B'; source: ParticipantSource },
|
||||
];
|
||||
rule: SeriesRule;
|
||||
schedule?: {
|
||||
date: string;
|
||||
time: string | null;
|
||||
timeZone: 'Asia/Seoul';
|
||||
};
|
||||
activation?: {
|
||||
type: 'grand-final-reset-required';
|
||||
grandFinalSeriesId: string;
|
||||
|
||||
@@ -1,6 +1,110 @@
|
||||
import { projectSeries } from './series-projector';
|
||||
|
||||
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', () => {
|
||||
const definition = seriesDefinition({
|
||||
id: 'series-pair',
|
||||
|
||||
@@ -13,6 +13,12 @@ export type SeriesRule =
|
||||
drawPolicy: 'allow' | 'tiebreak-required';
|
||||
};
|
||||
|
||||
export interface SeriesSchedule {
|
||||
date: string;
|
||||
time: string | null;
|
||||
timeZone: 'Asia/Seoul';
|
||||
}
|
||||
|
||||
export interface SeriesDefinitionLike {
|
||||
id: string;
|
||||
code?: string;
|
||||
@@ -26,6 +32,7 @@ export interface SeriesDefinitionLike {
|
||||
source: Readonly<Record<string, unknown>>;
|
||||
}>;
|
||||
rule: SeriesRule;
|
||||
schedule?: SeriesSchedule;
|
||||
gameSlots: ReadonlyArray<{
|
||||
id: string;
|
||||
seriesId: string;
|
||||
@@ -75,6 +82,7 @@ interface SeriesProjectionBase {
|
||||
code?: string;
|
||||
stage: SeriesDefinitionLike['stage'];
|
||||
rule: SeriesRule;
|
||||
schedule?: SeriesSchedule;
|
||||
entries: [SeriesProjectionEntry, SeriesProjectionEntry];
|
||||
}
|
||||
|
||||
@@ -311,6 +319,15 @@ function validateDefinition(definition: SeriesDefinitionLike): void {
|
||||
`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 =
|
||||
definition.rule.type === 'fixed-games'
|
||||
? definition.rule.gameCount
|
||||
@@ -753,6 +770,7 @@ function projectionBase(
|
||||
...(definition.code ? { code: definition.code } : {}),
|
||||
stage: definition.stage,
|
||||
rule: definition.rule,
|
||||
...(definition.schedule ? { schedule: { ...definition.schedule } } : {}),
|
||||
entries: [
|
||||
{ slot: 'A', teamId: participants[0], 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(
|
||||
participants: [string, string],
|
||||
winsByTeam: Map<string, number>,
|
||||
|
||||
@@ -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 },
|
||||
},
|
||||
)
|
||||
|
||||
@@ -3,7 +3,7 @@ VITE_DEFAULT_COMMUNITY_ID=69ebe0adf627c11be2f020a1
|
||||
VITE_MSAL_CLIENT_ID=66dadf46-418c-43c8-a908-3c15dcc0465d
|
||||
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_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_APPLICATION_ID=601654991
|
||||
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_TRUST_KEY=8100154
|
||||
VITE_NEW_RELIC_BEACON=bam.nr-data.net
|
||||
VITE_NEW_RELIC_APPLICATION_VERSION=83
|
||||
VITE_NEW_RELIC_RELEASE_ID=release-83
|
||||
VITE_NEW_RELIC_APPLICATION_VERSION=86
|
||||
VITE_NEW_RELIC_RELEASE_ID=release-86
|
||||
VITE_NEW_RELIC_RELEASE_NAME=lolympus-web
|
||||
@@ -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,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,7 +5,9 @@ import type {
|
||||
TeamId,
|
||||
} from "@lolympus/contracts";
|
||||
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";
|
||||
@@ -13,13 +15,41 @@ import { SeriesScoreCard } from "./SeriesScoreCard";
|
||||
|
||||
export function CompetitionResults({
|
||||
competition,
|
||||
view = "all",
|
||||
}: {
|
||||
competition: CompetitionDetailResponse;
|
||||
view?: "all" | "bracket" | "games";
|
||||
}) {
|
||||
const { projection } = competition;
|
||||
const teamById = new Map(
|
||||
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(
|
||||
projection.series.map((series) => [series.seriesId, series]),
|
||||
);
|
||||
@@ -33,7 +63,7 @@ export function CompetitionResults({
|
||||
Competition
|
||||
</p>
|
||||
<h2 id="competition-heading" className="mt-1 text-lg font-bold">
|
||||
공식 경기 결과
|
||||
공식 경기 일정·결과
|
||||
</h2>
|
||||
</div>
|
||||
<div className="flex items-center gap-3">
|
||||
@@ -44,7 +74,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,27 +111,13 @@ 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>
|
||||
{view === "all" && (
|
||||
<CompetitionSeriesHistory
|
||||
communityId={competition.communityId}
|
||||
matchId={competition.matchId}
|
||||
history={seriesHistory}
|
||||
teamById={teamById}
|
||||
/>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -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}`;
|
||||
}
|
||||
@@ -1,15 +1,26 @@
|
||||
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,
|
||||
@@ -51,152 +62,256 @@ function DesktopBracket({
|
||||
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">
|
||||
<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>
|
||||
<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="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="더블 엘리미네이션 대진표"
|
||||
tabIndex={0}
|
||||
>
|
||||
<div className="relative">
|
||||
<div
|
||||
className="relative"
|
||||
style={{ width: layout.width, height: layout.height }}
|
||||
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)}
|
||||
>
|
||||
<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/15 bg-primary/[0.025]"
|
||||
style={{
|
||||
left: finalZoneLeft,
|
||||
top: 0,
|
||||
width: layout.width - finalZoneLeft,
|
||||
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"
|
||||
<div
|
||||
className="relative"
|
||||
style={{ width: layout.width, height: layout.height }}
|
||||
>
|
||||
{layout.connectors.map((connector) => (
|
||||
<g
|
||||
key={`${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`}
|
||||
className={connectorClass(connector.kind)}
|
||||
>
|
||||
<path
|
||||
d={connector.path}
|
||||
fill="none"
|
||||
stroke="var(--color-base-100)"
|
||||
strokeWidth="4"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
<path
|
||||
d={connector.path}
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.25"
|
||||
strokeDasharray={connectorDash(connector.kind)}
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
vectorEffect="non-scaling-stroke"
|
||||
/>
|
||||
<circle
|
||||
cx={connector.targetX}
|
||||
cy={connector.targetY}
|
||||
r="2.25"
|
||||
fill="currentColor"
|
||||
/>
|
||||
</g>
|
||||
))}
|
||||
</svg>
|
||||
|
||||
{layout.rounds.map((round) => (
|
||||
<section
|
||||
key={`${round.stage}:${round.roundNumber}`}
|
||||
aria-labelledby={`competition-round-${round.stage}-${round.roundNumber}`}
|
||||
>
|
||||
<h3
|
||||
id={`competition-round-${round.stage}-${round.roundNumber}`}
|
||||
className="absolute z-[2] truncate px-1 text-xs font-bold text-content-muted"
|
||||
<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: round.x,
|
||||
top: round.labelY,
|
||||
width: DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnWidth,
|
||||
left: finalZoneLeft,
|
||||
top: 0,
|
||||
width: layout.width - finalZoneLeft,
|
||||
height: layout.height,
|
||||
}}
|
||||
>
|
||||
{round.label}
|
||||
</h3>
|
||||
{round.seriesIds.map((seriesId) => {
|
||||
const node = nodeById.get(seriesId);
|
||||
const series = seriesById.get(seriesId);
|
||||
if (!node || !series) return null;
|
||||
const routes = layout.connectors.filter(
|
||||
(connector) => connector.fromSeriesId === node.seriesId,
|
||||
);
|
||||
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 (
|
||||
<div
|
||||
key={node.seriesId}
|
||||
className="absolute z-[3]"
|
||||
style={{
|
||||
left: node.x,
|
||||
top: node.y,
|
||||
width: node.width,
|
||||
minHeight: node.height,
|
||||
}}
|
||||
>
|
||||
<SeriesScoreCard
|
||||
series={series}
|
||||
displayLabel={node.label}
|
||||
teamById={teamById}
|
||||
variant="bracket"
|
||||
/>
|
||||
{routes.length > 0 && (
|
||||
<span className="sr-only">
|
||||
{routes.map(({ label }) => label).join(". ")}
|
||||
</span>
|
||||
<g
|
||||
key={connectorKey}
|
||||
className={getBracketConnectorColorClass(
|
||||
connector.kind,
|
||||
isFocused,
|
||||
)}
|
||||
</div>
|
||||
>
|
||||
<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>
|
||||
);
|
||||
})}
|
||||
</section>
|
||||
))}
|
||||
</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>
|
||||
);
|
||||
@@ -218,7 +333,7 @@ function LaneBand({
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className="absolute border-y border-base-content/8 bg-base-content/[0.018]"
|
||||
className="absolute border-y border-base-content/10 bg-base-content/[0.03]"
|
||||
style={{ top: top - 6, width, height: height + 12 }}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
@@ -237,7 +352,11 @@ function LaneBand({
|
||||
|
||||
function ConnectorLegend({ showReset }: { showReset: boolean }) {
|
||||
return (
|
||||
<div className="flex flex-wrap items-center gap-4" aria-label="연결선 범례">
|
||||
<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" />}
|
||||
@@ -261,7 +380,7 @@ function LegendItem({
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.25"
|
||||
strokeDasharray={connectorDash(kind)}
|
||||
className={connectorClass(kind)}
|
||||
className={getBracketConnectorColorClass(kind)}
|
||||
/>
|
||||
</svg>
|
||||
{label}
|
||||
@@ -269,12 +388,6 @@ function LegendItem({
|
||||
);
|
||||
}
|
||||
|
||||
function connectorClass(kind: BracketConnectorKind): string {
|
||||
if (kind === "loser") return "text-warning/65";
|
||||
if (kind === "reset") return "text-primary/55";
|
||||
return "text-base-content/30";
|
||||
}
|
||||
|
||||
function connectorDash(kind: BracketConnectorKind): string | undefined {
|
||||
if (kind === "loser") return "6 5";
|
||||
if (kind === "reset") return "2 5";
|
||||
|
||||
@@ -4,8 +4,10 @@ import type {
|
||||
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,
|
||||
@@ -16,6 +18,7 @@ export function DoubleEliminationMobileBracket({
|
||||
layout: DoubleEliminationBracketLayout;
|
||||
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||
}) {
|
||||
const bracketId = useId();
|
||||
const seriesById = new Map(
|
||||
projection.series.map((series) => [series.seriesId, series]),
|
||||
);
|
||||
@@ -53,9 +56,15 @@ export function DoubleEliminationMobileBracket({
|
||||
);
|
||||
if (groups.length === 0) return null;
|
||||
return (
|
||||
<section key={section.key} aria-labelledby={`bracket-${section.key}`}>
|
||||
<section
|
||||
key={section.key}
|
||||
aria-labelledby={`${bracketId}-${section.key}`}
|
||||
>
|
||||
<div className="mb-3 border-b border-base-content/10 pb-2">
|
||||
<h3 id={`bracket-${section.key}`} className="text-sm font-bold">
|
||||
<h3
|
||||
id={`${bracketId}-${section.key}`}
|
||||
className="text-sm font-bold"
|
||||
>
|
||||
{section.title}
|
||||
</h3>
|
||||
<p className="mt-0.5 text-xs text-content-muted">
|
||||
@@ -66,24 +75,40 @@ export function DoubleEliminationMobileBracket({
|
||||
{groups.map((group) => (
|
||||
<section
|
||||
key={`${group.stage}:${group.roundNumber}`}
|
||||
aria-label={group.label}
|
||||
aria-labelledby={`${bracketId}-${group.stage}-${group.roundNumber}`}
|
||||
>
|
||||
<h4 className="mb-2 text-xs font-bold text-content-muted">
|
||||
<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={nodeById.get(seriesId)?.label}
|
||||
displayLabel={node?.label}
|
||||
teamById={teamById}
|
||||
variant="bracket"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
/>
|
||||
<MobileRoutes
|
||||
layout={layout}
|
||||
seriesId={seriesId}
|
||||
seriesLabel={node?.accessibleLabel ?? "경기"}
|
||||
/>
|
||||
<MobileRoutes layout={layout} seriesId={seriesId} />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
@@ -101,19 +126,25 @@ export function DoubleEliminationMobileBracket({
|
||||
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">
|
||||
<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}`}>
|
||||
{route.label}
|
||||
<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"
|
||||
);
|
||||
}
|
||||
@@ -4,14 +4,37 @@ import type {
|
||||
TeamId,
|
||||
} from "@lolympus/contracts";
|
||||
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry";
|
||||
import { isSeriesEntryWinner } from "./series-score-card-model";
|
||||
import {
|
||||
formatSeriesScore,
|
||||
getSeriesScoreCardAccessibleLabel,
|
||||
getSeriesScoreCardIdentity,
|
||||
getSeriesScoreCardPresentation,
|
||||
isSeriesEntryWinner,
|
||||
type SeriesScoreCardTone,
|
||||
} from "./series-score-card-model";
|
||||
|
||||
const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
|
||||
inactive: "비활성",
|
||||
waiting: "대진 대기",
|
||||
ready: "경기 가능",
|
||||
"in-progress": "진행 중",
|
||||
completed: "종료",
|
||||
const CARD_TONE_CLASS: Record<SeriesScoreCardTone, string> = {
|
||||
muted: "",
|
||||
ready: "border-l-2 border-l-success/70",
|
||||
live: "border-l-2 border-l-primary/70",
|
||||
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({
|
||||
@@ -19,25 +42,31 @@ export function SeriesScoreCard({
|
||||
displayLabel,
|
||||
teamById,
|
||||
variant = "default",
|
||||
accessibilityLabel,
|
||||
}: {
|
||||
series: SeriesProjection;
|
||||
displayLabel?: string;
|
||||
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
|
||||
variant?: "default" | "bracket";
|
||||
accessibilityLabel?: string;
|
||||
}) {
|
||||
const isBracket = variant === "bracket";
|
||||
const seriesLabel = series.code ?? displayLabel;
|
||||
const identity = getSeriesScoreCardIdentity(series, displayLabel);
|
||||
const presentation = getSeriesScoreCardPresentation(series);
|
||||
const cardAccessibilityLabel =
|
||||
accessibilityLabel ??
|
||||
getSeriesScoreCardAccessibleLabel(series, displayLabel, teamById);
|
||||
|
||||
return (
|
||||
<article
|
||||
className="border border-base-content/10 bg-base-100"
|
||||
aria-label={`${seriesLabel ?? "경기"} ${STATUS_LABEL[series.status]}`}
|
||||
className={`border border-base-content/10 bg-base-100 ${CARD_TONE_CLASS[presentation.tone]}`}
|
||||
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 ${
|
||||
className={`flex items-center justify-between gap-2 border-b border-base-content/8 ${HEADER_TONE_CLASS[presentation.tone]} ${
|
||||
isBracket ? "px-2" : "px-3 py-2"
|
||||
}`}
|
||||
style={
|
||||
@@ -47,19 +76,43 @@ export function SeriesScoreCard({
|
||||
}
|
||||
>
|
||||
<span
|
||||
className="truncate text-xs font-bold text-base-content/65"
|
||||
title={seriesLabel ?? "Series"}
|
||||
className="min-w-0"
|
||||
title={
|
||||
identity.code
|
||||
? `${identity.label} (${identity.code})`
|
||||
: identity.label
|
||||
}
|
||||
>
|
||||
{seriesLabel ?? "Series"}
|
||||
<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 className="shrink-0 text-[11px] text-base-content/40">
|
||||
{STATUS_LABEL[series.status]}
|
||||
<span
|
||||
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>
|
||||
</header>
|
||||
<div className="divide-y divide-base-content/8">
|
||||
<div
|
||||
className={
|
||||
isBracket ? "relative" : "divide-y divide-base-content/8"
|
||||
}
|
||||
>
|
||||
{series.entries.map((entry) => {
|
||||
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
|
||||
const isWinner = isSeriesEntryWinner(series, entry.teamId);
|
||||
const score = formatSeriesScore(series, entry.gameWins);
|
||||
const teamName =
|
||||
team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중");
|
||||
return isBracket ? (
|
||||
@@ -67,6 +120,7 @@ export function SeriesScoreCard({
|
||||
key={entry.slot}
|
||||
entry={entry}
|
||||
isWinner={isWinner}
|
||||
score={score}
|
||||
teamName={teamName}
|
||||
/>
|
||||
) : (
|
||||
@@ -74,10 +128,18 @@ export function SeriesScoreCard({
|
||||
key={entry.slot}
|
||||
entry={entry}
|
||||
isWinner={isWinner}
|
||||
score={score}
|
||||
teamName={teamName}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{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>
|
||||
</article>
|
||||
);
|
||||
@@ -86,10 +148,12 @@ export function SeriesScoreCard({
|
||||
function DefaultEntryRow({
|
||||
entry,
|
||||
isWinner,
|
||||
score,
|
||||
teamName,
|
||||
}: {
|
||||
entry: SeriesProjection["entries"][number];
|
||||
isWinner: boolean;
|
||||
score: string;
|
||||
teamName: string;
|
||||
}) {
|
||||
return (
|
||||
@@ -99,15 +163,17 @@ function DefaultEntryRow({
|
||||
</span>
|
||||
<span
|
||||
className={`truncate text-sm ${
|
||||
isWinner ? "font-bold text-base-content" : "text-base-content/60"
|
||||
isWinner ? "font-bold text-base-content" : "text-content-subtle"
|
||||
}`}
|
||||
>
|
||||
{teamName}
|
||||
{isWinner && (
|
||||
<span className="ml-2 text-[10px] font-bold text-success">승리</span>
|
||||
<span className="ml-2 text-[10px] font-bold text-base-content">
|
||||
승리
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<Score gameWins={entry.gameWins} />
|
||||
<Score score={score} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -115,10 +181,12 @@ function DefaultEntryRow({
|
||||
function BracketEntryRow({
|
||||
entry,
|
||||
isWinner,
|
||||
score,
|
||||
teamName,
|
||||
}: {
|
||||
entry: SeriesProjection["entries"][number];
|
||||
isWinner: boolean;
|
||||
score: string;
|
||||
teamName: string;
|
||||
}) {
|
||||
return (
|
||||
@@ -131,24 +199,27 @@ function BracketEntryRow({
|
||||
</span>
|
||||
<span
|
||||
className={`line-clamp-2 break-words text-[13px] leading-4 ${
|
||||
isWinner ? "font-bold text-base-content" : "text-base-content/60"
|
||||
isWinner ? "font-bold text-base-content" : "text-content-subtle"
|
||||
}`}
|
||||
title={teamName}
|
||||
>
|
||||
{teamName}
|
||||
</span>
|
||||
<span className="text-center text-[10px] font-bold text-success">
|
||||
<span className="text-center text-[10px] font-bold text-base-content">
|
||||
{isWinner ? "승리" : null}
|
||||
</span>
|
||||
<Score gameWins={entry.gameWins} />
|
||||
<Score score={score} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Score({ gameWins }: { gameWins: number }) {
|
||||
function Score({ score }: { score: string }) {
|
||||
return (
|
||||
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
|
||||
{gameWins}
|
||||
<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"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -3,18 +3,24 @@ import type {
|
||||
CompetitionProjection,
|
||||
IsoDateTime,
|
||||
SeriesProjection,
|
||||
SeriesSchedule,
|
||||
} from "@lolympus/contracts";
|
||||
import { internalMatchGamePath } from "../../lib/internal-match-routes.ts";
|
||||
|
||||
export type CompetitionSeriesHistorySeries = Extract<
|
||||
SeriesProjection,
|
||||
{ status: "in-progress" | "completed" }
|
||||
>;
|
||||
export type CompetitionSeriesHistorySeries = SeriesProjection;
|
||||
|
||||
export type CompetitionSeriesHistoryTimestampSource =
|
||||
| "game-start"
|
||||
| "decision"
|
||||
| "scheduled"
|
||||
| "unavailable";
|
||||
|
||||
export interface CompetitionSeriesHistoryRow {
|
||||
series: CompetitionSeriesHistorySeries;
|
||||
games: CompetitionGameView[];
|
||||
occurredAt: IsoDateTime;
|
||||
timestampSource: "game-start" | "decision";
|
||||
occurredAt: IsoDateTime | null;
|
||||
timestampSource: CompetitionSeriesHistoryTimestampSource;
|
||||
dateKey: string;
|
||||
}
|
||||
|
||||
export interface CompetitionSeriesHistoryDay {
|
||||
@@ -22,8 +28,38 @@ export interface CompetitionSeriesHistoryDay {
|
||||
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",
|
||||
@@ -40,38 +76,72 @@ export function createCompetitionSeriesHistory(
|
||||
const games = [...(gamesBySeriesId.get(series.seriesId) ?? [])].sort(
|
||||
compareGames,
|
||||
);
|
||||
if (series.status === "in-progress") {
|
||||
const occurredAt = earliestStartedAt(games);
|
||||
if (!occurredAt) continue;
|
||||
rows.push({
|
||||
series,
|
||||
games,
|
||||
occurredAt,
|
||||
timestampSource: "game-start",
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (series.status !== "completed") continue;
|
||||
|
||||
const gameStartedAt = earliestStartedAt(games);
|
||||
rows.push({
|
||||
series,
|
||||
games,
|
||||
occurredAt: gameStartedAt ?? series.outcome.completedAt,
|
||||
timestampSource: gameStartedAt ? "game-start" : "decision",
|
||||
});
|
||||
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 dateKey = dateKeyInTimeZone(row.occurredAt, timeZone);
|
||||
const currentDay = days.at(-1);
|
||||
if (currentDay?.dateKey === dateKey) {
|
||||
if (currentDay?.dateKey === row.dateKey) {
|
||||
currentDay.rows.push(row);
|
||||
} else {
|
||||
days.push({ dateKey, rows: [row] });
|
||||
days.push({ dateKey: row.dateKey, rows: [row] });
|
||||
}
|
||||
}
|
||||
return days;
|
||||
@@ -80,21 +150,121 @@ export function createCompetitionSeriesHistory(
|
||||
export function getSeriesHistoryStatusLabel(
|
||||
series: CompetitionSeriesHistorySeries,
|
||||
): string {
|
||||
if (series.status === "in-progress") return "진행 중";
|
||||
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 "종료";
|
||||
return null;
|
||||
case "draw":
|
||||
return "무승부";
|
||||
return series.outcome.basis.type === "played"
|
||||
? "무승부"
|
||||
: "판정 무승부";
|
||||
case "walkover":
|
||||
return "부전승";
|
||||
case "forfeit":
|
||||
return "기권승";
|
||||
case "administrative":
|
||||
return "판정";
|
||||
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 {
|
||||
@@ -109,6 +279,88 @@ export function formatSeriesGameDuration(
|
||||
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,
|
||||
@@ -125,12 +377,32 @@ function compareRows(
|
||||
right: CompetitionSeriesHistoryRow,
|
||||
): number {
|
||||
return (
|
||||
timestampValue(left.occurredAt) - timestampValue(right.occurredAt) ||
|
||||
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) {
|
||||
@@ -143,9 +415,18 @@ function earliestStartedAt(games: CompetitionGameView[]): IsoDateTime | null {
|
||||
return earliest?.startedAt ?? null;
|
||||
}
|
||||
|
||||
function dateKeyInTimeZone(value: IsoDateTime, timeZone: string): string {
|
||||
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 "unknown";
|
||||
if (Number.isNaN(date.getTime())) return null;
|
||||
const parts = new Intl.DateTimeFormat("en-US", {
|
||||
timeZone,
|
||||
year: "numeric",
|
||||
@@ -157,7 +438,7 @@ function dateKeyInTimeZone(value: IsoDateTime, timeZone: string): string {
|
||||
const year = part("year");
|
||||
const month = part("month");
|
||||
const day = part("day");
|
||||
return year && month && day ? `${year}-${month}-${day}` : "unknown";
|
||||
return year && month && day ? `${year}-${month}-${day}` : null;
|
||||
}
|
||||
|
||||
function timestampValue(value: IsoDateTime): number {
|
||||
@@ -165,6 +446,34 @@ function timestampValue(value: IsoDateTime): number {
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -16,7 +16,9 @@ export type BracketConnectorKind = "winner" | "loser" | "reset";
|
||||
export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
|
||||
boardPadding: 12,
|
||||
columnWidth: 228,
|
||||
columnGap: 32,
|
||||
columnGap: 40,
|
||||
// Matches the widest focused connector underlay so parallel routes stay legible.
|
||||
connectorRailClearance: 5,
|
||||
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
|
||||
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
|
||||
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
|
||||
@@ -29,6 +31,7 @@ export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
|
||||
export interface BracketNodeLayout {
|
||||
seriesId: SeriesId;
|
||||
label: string;
|
||||
accessibleLabel: string;
|
||||
stage: BracketStage;
|
||||
roundNumber: number;
|
||||
lane: BracketLane;
|
||||
@@ -52,6 +55,7 @@ export interface BracketConnectorLayout {
|
||||
targetY: number;
|
||||
path: string;
|
||||
label: string;
|
||||
accessibleLabel: string;
|
||||
}
|
||||
|
||||
export interface DoubleEliminationBracketConfiguration {
|
||||
@@ -63,6 +67,7 @@ export interface BracketRoundLayout {
|
||||
stage: BracketStage;
|
||||
roundNumber: number;
|
||||
label: string;
|
||||
accessibleLabel: string;
|
||||
lane: BracketLane;
|
||||
column: number;
|
||||
x: number;
|
||||
@@ -74,6 +79,7 @@ export interface MobileBracketGroup {
|
||||
stage: BracketStage;
|
||||
roundNumber: number;
|
||||
label: string;
|
||||
accessibleLabel: string;
|
||||
seriesIds: SeriesId[];
|
||||
}
|
||||
|
||||
@@ -101,9 +107,33 @@ interface NormalizedRound {
|
||||
stage: BracketStage;
|
||||
roundNumber: number;
|
||||
label: string;
|
||||
accessibleLabel: string;
|
||||
seriesIds: SeriesId[];
|
||||
}
|
||||
|
||||
interface ConnectorRoute {
|
||||
connector: SeriesConnectorView;
|
||||
key: string;
|
||||
kind: BracketConnectorKind;
|
||||
targetColumn: number;
|
||||
targetNodeY: number;
|
||||
sourceX: number;
|
||||
sourceY: number;
|
||||
targetX: number;
|
||||
targetY: number;
|
||||
}
|
||||
|
||||
interface SeparateWinnerRailChoice {
|
||||
verticalXs: [number, number];
|
||||
crossings: number;
|
||||
distanceFromBaseline: number;
|
||||
distanceFromCenter: number;
|
||||
}
|
||||
|
||||
type OrthogonalSegment =
|
||||
| { orientation: "horizontal"; fixed: number; start: number; end: number }
|
||||
| { orientation: "vertical"; fixed: number; start: number; end: number };
|
||||
|
||||
const STAGE_ORDER: Record<BracketStage, number> = {
|
||||
upper: 0,
|
||||
lower: 1,
|
||||
@@ -121,6 +151,9 @@ const CONNECTOR_SELECTION_ORDER: Record<
|
||||
"slot-b": 3,
|
||||
};
|
||||
|
||||
// A focused 5px underlay extends 2.5px from its centerline.
|
||||
const CONNECTOR_RAIL_EDGE_INSET = 3;
|
||||
|
||||
export function createDoubleEliminationBracketLayout(
|
||||
projection: DoubleEliminationCompetitionProjection,
|
||||
configuration: DoubleEliminationBracketConfiguration,
|
||||
@@ -170,11 +203,29 @@ export function bracketRoundLabel(
|
||||
stage: SeriesStageType,
|
||||
roundNumber?: number,
|
||||
): string {
|
||||
return formatBracketRoundLabel(stage, roundNumber, "R");
|
||||
}
|
||||
|
||||
export function bracketRoundAccessibleLabel(
|
||||
stage: SeriesStageType,
|
||||
roundNumber?: number,
|
||||
): string {
|
||||
return formatBracketRoundLabel(stage, roundNumber, "라운드");
|
||||
}
|
||||
|
||||
function formatBracketRoundLabel(
|
||||
stage: SeriesStageType,
|
||||
roundNumber: number | undefined,
|
||||
roundUnit: "R" | "라운드",
|
||||
): string {
|
||||
const round = roundNumber ?? 1;
|
||||
switch (stage) {
|
||||
case "upper":
|
||||
return `승자조 ${roundNumber ?? 1}라운드`;
|
||||
return round === 1
|
||||
? `브래킷 1${roundUnit}`
|
||||
: `브래킷 상위 ${round}${roundUnit}`;
|
||||
case "lower":
|
||||
return `패자조 ${roundNumber ?? 1}라운드`;
|
||||
return `브래킷 하위 ${round}${roundUnit}`;
|
||||
case "grand-final":
|
||||
return "그랜드 파이널";
|
||||
case "reset-final":
|
||||
@@ -182,7 +233,7 @@ export function bracketRoundLabel(
|
||||
case "pair":
|
||||
return "대진";
|
||||
case "round-robin":
|
||||
return `${roundNumber ?? 1}라운드`;
|
||||
return `${round}라운드`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -310,6 +361,10 @@ function normalizeRounds(
|
||||
stage: round.stage,
|
||||
roundNumber: round.roundNumber,
|
||||
label: bracketRoundLabel(round.stage, round.roundNumber),
|
||||
accessibleLabel: bracketRoundAccessibleLabel(
|
||||
round.stage,
|
||||
round.roundNumber,
|
||||
),
|
||||
seriesIds: ids,
|
||||
});
|
||||
}
|
||||
@@ -460,7 +515,12 @@ function buildNodes(
|
||||
(laneGeometry.height * (index + 0.5)) / round.seriesIds.length;
|
||||
result.push({
|
||||
seriesId,
|
||||
label: seriesName(graph.seriesById.get(seriesId), round),
|
||||
label: seriesDisplayName(round, seriesId, round.label),
|
||||
accessibleLabel: seriesDisplayName(
|
||||
round,
|
||||
seriesId,
|
||||
round.accessibleLabel,
|
||||
),
|
||||
stage: round.stage,
|
||||
roundNumber: round.roundNumber,
|
||||
lane,
|
||||
@@ -508,56 +568,53 @@ function buildConnectors(
|
||||
nodeById: Map<SeriesId, BracketNodeLayout>,
|
||||
): BracketConnectorLayout[] | null {
|
||||
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
|
||||
const connectorsByTargetColumn = new Map<
|
||||
number,
|
||||
Array<{
|
||||
connector: SeriesConnectorView;
|
||||
source: BracketNodeLayout;
|
||||
target: BracketNodeLayout;
|
||||
}>
|
||||
>();
|
||||
const routes: ConnectorRoute[] = [];
|
||||
const routesByTargetColumn = new Map<number, ConnectorRoute[]>();
|
||||
for (const connector of projection.connectors) {
|
||||
const source = nodeById.get(connector.from.seriesId);
|
||||
const target = nodeById.get(connector.to.seriesId);
|
||||
if (!source || !target || target.column <= source.column) return null;
|
||||
const routes = connectorsByTargetColumn.get(target.column) ?? [];
|
||||
routes.push({ connector, source, target });
|
||||
connectorsByTargetColumn.set(target.column, routes);
|
||||
const route = {
|
||||
connector,
|
||||
key: connectorKey(connector),
|
||||
kind: connectorKind(connector.from.select),
|
||||
targetColumn: target.column,
|
||||
targetNodeY: target.y,
|
||||
sourceX: source.x + source.width,
|
||||
sourceY: connectorAnchorY(source, connector.from.select),
|
||||
targetX: target.x,
|
||||
targetY: targetSlotY(target, connector.to.slot),
|
||||
} satisfies ConnectorRoute;
|
||||
routes.push(route);
|
||||
const columnRoutes = routesByTargetColumn.get(target.column) ?? [];
|
||||
columnRoutes.push(route);
|
||||
routesByTargetColumn.set(target.column, columnRoutes);
|
||||
}
|
||||
|
||||
const verticalXByConnector = new Map<string, number>();
|
||||
for (const routes of connectorsByTargetColumn.values()) {
|
||||
routes.sort(
|
||||
for (const columnRoutes of routesByTargetColumn.values()) {
|
||||
columnRoutes.sort(
|
||||
(left, right) =>
|
||||
connectorAnchorY(right.source, right.connector.from.select) -
|
||||
connectorAnchorY(left.source, left.connector.from.select) ||
|
||||
targetSlotY(right.target, right.connector.to.slot) -
|
||||
targetSlotY(left.target, left.connector.to.slot) ||
|
||||
connectorKey(left.connector).localeCompare(connectorKey(right.connector)),
|
||||
right.sourceY - left.sourceY ||
|
||||
right.targetY - left.targetY ||
|
||||
left.key.localeCompare(right.key),
|
||||
);
|
||||
routes.forEach(({ connector, target }, index) => {
|
||||
columnRoutes.forEach(({ key, targetX }, index) => {
|
||||
verticalXByConnector.set(
|
||||
connectorKey(connector),
|
||||
target.x -
|
||||
key,
|
||||
targetX -
|
||||
geometry.columnGap +
|
||||
(geometry.columnGap * (index + 1)) / (routes.length + 1),
|
||||
(geometry.columnGap * (index + 1)) / (columnRoutes.length + 1),
|
||||
);
|
||||
});
|
||||
}
|
||||
if (!alignWinnerBundleRails(routes, verticalXByConnector)) return null;
|
||||
|
||||
const result: BracketConnectorLayout[] = [];
|
||||
for (const connector of projection.connectors) {
|
||||
const source = nodeById.get(connector.from.seriesId);
|
||||
const target = nodeById.get(connector.to.seriesId);
|
||||
if (!source || !target || target.column <= source.column) return null;
|
||||
|
||||
const sourceX = source.x + source.width;
|
||||
const targetX = target.x;
|
||||
const sourceY = connectorAnchorY(source, connector.from.select);
|
||||
const targetY = targetSlotY(target, connector.to.slot);
|
||||
const verticalX = verticalXByConnector.get(connectorKey(connector));
|
||||
for (const route of routes) {
|
||||
const { connector, key, kind, sourceX, sourceY, targetX, targetY } = route;
|
||||
const verticalX = verticalXByConnector.get(key);
|
||||
if (verticalX === undefined) return null;
|
||||
const kind = connectorKind(connector.from.select);
|
||||
result.push({
|
||||
fromSeriesId: connector.from.seriesId,
|
||||
select: connector.from.select,
|
||||
@@ -570,7 +627,8 @@ function buildConnectors(
|
||||
targetX,
|
||||
targetY,
|
||||
path: `M ${number(sourceX)} ${number(sourceY)} H ${number(verticalX)} V ${number(targetY)} H ${number(targetX)}`,
|
||||
label: connectorLabel(connector, graph),
|
||||
label: connectorLabel(connector, graph, "label"),
|
||||
accessibleLabel: connectorLabel(connector, graph, "accessibleLabel"),
|
||||
});
|
||||
}
|
||||
return result.sort(
|
||||
@@ -589,16 +647,341 @@ function buildConnectors(
|
||||
);
|
||||
}
|
||||
|
||||
function alignWinnerBundleRails(
|
||||
routes: readonly ConnectorRoute[],
|
||||
verticalXByConnector: Map<string, number>,
|
||||
): boolean {
|
||||
const winnersByTarget = new Map<SeriesId, ConnectorRoute[]>();
|
||||
for (const route of routes) {
|
||||
if (route.kind !== "winner") continue;
|
||||
const winners = winnersByTarget.get(route.connector.to.seriesId) ?? [];
|
||||
winners.push(route);
|
||||
winnersByTarget.set(route.connector.to.seriesId, winners);
|
||||
}
|
||||
|
||||
const bundles = [...winnersByTarget.values()]
|
||||
.filter(
|
||||
(winners) =>
|
||||
winners.length === 2 &&
|
||||
winners[0].connector.to.slot !== winners[1].connector.to.slot,
|
||||
)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left[0].targetColumn - right[0].targetColumn ||
|
||||
left[0].targetNodeY - right[0].targetNodeY ||
|
||||
left[0].key.localeCompare(right[0].key),
|
||||
);
|
||||
|
||||
for (const bundle of bundles) {
|
||||
const preferredX =
|
||||
bundle[0].targetX - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
|
||||
if (
|
||||
intervalsOverlap(
|
||||
bundle[0].sourceY,
|
||||
bundle[0].targetY,
|
||||
bundle[1].sourceY,
|
||||
bundle[1].targetY,
|
||||
)
|
||||
) {
|
||||
const assignment = chooseSeparateWinnerRails(
|
||||
bundle,
|
||||
routes,
|
||||
verticalXByConnector,
|
||||
preferredX,
|
||||
);
|
||||
if (!assignment) return false;
|
||||
for (const [key, verticalX] of assignment) {
|
||||
verticalXByConnector.set(key, verticalX);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const verticalX = chooseWinnerBundleRail(
|
||||
bundle,
|
||||
routes,
|
||||
verticalXByConnector,
|
||||
preferredX,
|
||||
);
|
||||
if (verticalX === null) return false;
|
||||
for (const route of bundle) verticalXByConnector.set(route.key, verticalX);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function chooseWinnerBundleRail(
|
||||
bundle: readonly ConnectorRoute[],
|
||||
routes: readonly ConnectorRoute[],
|
||||
verticalXByConnector: Map<string, number>,
|
||||
preferredX: number,
|
||||
): number | null {
|
||||
const previousRails = bundle.map((route) =>
|
||||
verticalXByConnector.get(route.key),
|
||||
);
|
||||
if (previousRails.some((verticalX) => verticalX === undefined)) return null;
|
||||
const previousScore = connectorConflictScore(routes, verticalXByConnector);
|
||||
// Keep the existing crossing budget, then favor stroke-clear rails nearest center.
|
||||
let best:
|
||||
| {
|
||||
verticalX: number;
|
||||
crossings: number;
|
||||
clearanceConflicts: number;
|
||||
distanceFromCenter: number;
|
||||
}
|
||||
| null = null;
|
||||
|
||||
for (const candidateX of winnerRailCandidates(preferredX)) {
|
||||
for (const route of bundle) {
|
||||
verticalXByConnector.set(route.key, candidateX);
|
||||
}
|
||||
const score = connectorConflictScore(routes, verticalXByConnector);
|
||||
if (
|
||||
score.overlaps !== 0 ||
|
||||
score.crossings > previousScore.crossings ||
|
||||
score.clearanceConflicts > previousScore.clearanceConflicts
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const distanceFromCenter = Math.abs(candidateX - preferredX);
|
||||
if (
|
||||
!best ||
|
||||
score.clearanceConflicts < best.clearanceConflicts ||
|
||||
(score.clearanceConflicts === best.clearanceConflicts &&
|
||||
(score.crossings < best.crossings ||
|
||||
(score.crossings === best.crossings &&
|
||||
distanceFromCenter < best.distanceFromCenter)))
|
||||
) {
|
||||
best = {
|
||||
verticalX: candidateX,
|
||||
crossings: score.crossings,
|
||||
clearanceConflicts: score.clearanceConflicts,
|
||||
distanceFromCenter,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (best) return best.verticalX;
|
||||
|
||||
bundle.forEach((route, index) => {
|
||||
const previousX = previousRails[index];
|
||||
if (previousX !== undefined) {
|
||||
verticalXByConnector.set(route.key, previousX);
|
||||
}
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
function winnerRailCandidates(preferredX: number): number[] {
|
||||
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
|
||||
const maximumOffset =
|
||||
geometry.columnGap / 2 - CONNECTOR_RAIL_EDGE_INSET;
|
||||
const candidates = [preferredX];
|
||||
for (let offset = 1; offset <= maximumOffset; offset += 1) {
|
||||
candidates.push(preferredX - offset, preferredX + offset);
|
||||
}
|
||||
return candidates;
|
||||
}
|
||||
|
||||
function chooseSeparateWinnerRails(
|
||||
bundle: readonly ConnectorRoute[],
|
||||
routes: readonly ConnectorRoute[],
|
||||
verticalXByConnector: Map<string, number>,
|
||||
preferredX: number,
|
||||
): Map<string, number> | null {
|
||||
const orderedBundle = [...bundle].sort(
|
||||
(left, right) =>
|
||||
left.sourceY - right.sourceY ||
|
||||
left.targetY - right.targetY ||
|
||||
left.key.localeCompare(right.key),
|
||||
);
|
||||
const previousRails: number[] = [];
|
||||
for (const route of orderedBundle) {
|
||||
const previousX = verticalXByConnector.get(route.key);
|
||||
if (previousX === undefined) return null;
|
||||
previousRails.push(previousX);
|
||||
}
|
||||
|
||||
const previousScore = connectorConflictScore(routes, verticalXByConnector);
|
||||
const bundleKeys = new Set(orderedBundle.map(({ key }) => key));
|
||||
const candidates = [
|
||||
...new Set([...previousRails, ...winnerRailCandidates(preferredX)]),
|
||||
];
|
||||
let best: SeparateWinnerRailChoice | null = null;
|
||||
|
||||
for (const firstX of candidates) {
|
||||
for (const secondX of candidates) {
|
||||
if (firstX === secondX) continue;
|
||||
verticalXByConnector.set(orderedBundle[0].key, firstX);
|
||||
verticalXByConnector.set(orderedBundle[1].key, secondX);
|
||||
|
||||
const bundleScore = connectorConflictScore(
|
||||
routes,
|
||||
verticalXByConnector,
|
||||
bundleKeys,
|
||||
);
|
||||
const score = connectorConflictScore(routes, verticalXByConnector);
|
||||
if (
|
||||
bundleScore.overlaps !== 0 ||
|
||||
bundleScore.clearanceConflicts !== 0 ||
|
||||
score.overlaps !== 0 ||
|
||||
score.crossings > previousScore.crossings
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const distanceFromBaseline =
|
||||
Math.abs(firstX - previousRails[0]) +
|
||||
Math.abs(secondX - previousRails[1]);
|
||||
const distanceFromCenter =
|
||||
Math.abs(firstX - preferredX) + Math.abs(secondX - preferredX);
|
||||
const candidate: SeparateWinnerRailChoice = {
|
||||
verticalXs: [firstX, secondX],
|
||||
crossings: score.crossings,
|
||||
distanceFromBaseline,
|
||||
distanceFromCenter,
|
||||
};
|
||||
if (!best || compareSeparateWinnerRailChoices(candidate, best) < 0) {
|
||||
best = candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
orderedBundle.forEach((route, index) => {
|
||||
verticalXByConnector.set(route.key, previousRails[index]);
|
||||
});
|
||||
if (!best) return null;
|
||||
return new Map(
|
||||
orderedBundle.map((route, index) => [route.key, best.verticalXs[index]]),
|
||||
);
|
||||
}
|
||||
|
||||
function compareSeparateWinnerRailChoices(
|
||||
left: SeparateWinnerRailChoice,
|
||||
right: SeparateWinnerRailChoice,
|
||||
): number {
|
||||
return (
|
||||
left.crossings - right.crossings ||
|
||||
left.distanceFromBaseline - right.distanceFromBaseline ||
|
||||
left.distanceFromCenter - right.distanceFromCenter ||
|
||||
left.verticalXs[0] - right.verticalXs[0] ||
|
||||
left.verticalXs[1] - right.verticalXs[1]
|
||||
);
|
||||
}
|
||||
|
||||
function connectorConflictScore(
|
||||
routes: readonly ConnectorRoute[],
|
||||
verticalXByConnector: ReadonlyMap<string, number>,
|
||||
focusedRouteKeys?: ReadonlySet<string>,
|
||||
): { crossings: number; overlaps: number; clearanceConflicts: number } {
|
||||
let crossings = 0;
|
||||
let overlaps = 0;
|
||||
let clearanceConflicts = 0;
|
||||
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
|
||||
const leftX = verticalXByConnector.get(routes[leftIndex].key);
|
||||
if (leftX === undefined) continue;
|
||||
const leftSegments = connectorRouteSegments(routes[leftIndex], leftX);
|
||||
for (
|
||||
let rightIndex = leftIndex + 1;
|
||||
rightIndex < routes.length;
|
||||
rightIndex += 1
|
||||
) {
|
||||
if (
|
||||
focusedRouteKeys &&
|
||||
!focusedRouteKeys.has(routes[leftIndex].key) &&
|
||||
!focusedRouteKeys.has(routes[rightIndex].key)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const rightX = verticalXByConnector.get(routes[rightIndex].key);
|
||||
if (rightX === undefined) continue;
|
||||
const rightSegments = connectorRouteSegments(routes[rightIndex], rightX);
|
||||
for (const left of leftSegments) {
|
||||
for (const right of rightSegments) {
|
||||
if (left.orientation === right.orientation) {
|
||||
const overlapLength =
|
||||
Math.min(left.end, right.end) - Math.max(left.start, right.start);
|
||||
if (left.fixed === right.fixed && overlapLength > 0) {
|
||||
overlaps += 1;
|
||||
} else if (
|
||||
left.orientation === "vertical" &&
|
||||
overlapLength > 0 &&
|
||||
Math.abs(left.fixed - right.fixed) <
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance
|
||||
) {
|
||||
clearanceConflicts += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const horizontal =
|
||||
left.orientation === "horizontal" ? left : right;
|
||||
const vertical = left.orientation === "vertical" ? left : right;
|
||||
if (
|
||||
vertical.fixed > horizontal.start &&
|
||||
vertical.fixed < horizontal.end &&
|
||||
horizontal.fixed > vertical.start &&
|
||||
horizontal.fixed < vertical.end
|
||||
) {
|
||||
crossings += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return { crossings, overlaps, clearanceConflicts };
|
||||
}
|
||||
|
||||
function connectorRouteSegments(
|
||||
route: ConnectorRoute,
|
||||
verticalX: number,
|
||||
): OrthogonalSegment[] {
|
||||
return [
|
||||
orthogonalSegment("horizontal", route.sourceY, route.sourceX, verticalX),
|
||||
orthogonalSegment("vertical", verticalX, route.sourceY, route.targetY),
|
||||
orthogonalSegment("horizontal", route.targetY, verticalX, route.targetX),
|
||||
];
|
||||
}
|
||||
|
||||
function orthogonalSegment(
|
||||
orientation: OrthogonalSegment["orientation"],
|
||||
fixed: number,
|
||||
first: number,
|
||||
second: number,
|
||||
): OrthogonalSegment {
|
||||
return {
|
||||
orientation,
|
||||
fixed,
|
||||
start: Math.min(first, second),
|
||||
end: Math.max(first, second),
|
||||
};
|
||||
}
|
||||
|
||||
function intervalsOverlap(
|
||||
firstStart: number,
|
||||
firstEnd: number,
|
||||
secondStart: number,
|
||||
secondEnd: number,
|
||||
): boolean {
|
||||
return (
|
||||
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
|
||||
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
|
||||
);
|
||||
}
|
||||
|
||||
function connectorLabel(
|
||||
connector: SeriesConnectorView,
|
||||
graph: ValidatedGraph,
|
||||
labelKey: "label" | "accessibleLabel",
|
||||
): string {
|
||||
const source = graph.seriesById.get(connector.from.seriesId);
|
||||
const target = graph.seriesById.get(connector.to.seriesId);
|
||||
const sourceRound = graph.roundBySeriesId.get(connector.from.seriesId);
|
||||
const targetRound = graph.roundBySeriesId.get(connector.to.seriesId);
|
||||
const sourceName = seriesName(source, sourceRound);
|
||||
const targetName = seriesName(target, targetRound);
|
||||
const sourceName = seriesDisplayName(
|
||||
sourceRound,
|
||||
connector.from.seriesId,
|
||||
sourceRound?.[labelKey],
|
||||
);
|
||||
const targetName = seriesDisplayName(
|
||||
targetRound,
|
||||
connector.to.seriesId,
|
||||
targetRound?.[labelKey],
|
||||
);
|
||||
const selection =
|
||||
connector.from.select === "winner"
|
||||
? "승자"
|
||||
@@ -610,16 +993,16 @@ function connectorLabel(
|
||||
return `${sourceName} ${selection} → ${targetName} ${connector.to.slot} 슬롯`;
|
||||
}
|
||||
|
||||
function seriesName(
|
||||
series: DoubleEliminationCompetitionProjection["series"][number] | undefined,
|
||||
function seriesDisplayName(
|
||||
round: NormalizedRound | undefined,
|
||||
seriesId: SeriesId,
|
||||
roundLabel: string | undefined,
|
||||
): string {
|
||||
if (series?.code) return series.code;
|
||||
if (!series || !round) return "알 수 없는 경기";
|
||||
const index = round.seriesIds.indexOf(series.seriesId);
|
||||
if (!round || !roundLabel) return "알 수 없는 경기";
|
||||
const index = round.seriesIds.indexOf(seriesId);
|
||||
return round.seriesIds.length > 1
|
||||
? `${round.label} ${index + 1}경기`
|
||||
: round.label;
|
||||
? `${roundLabel} · ${index + 1}경기`
|
||||
: roundLabel;
|
||||
}
|
||||
|
||||
function connectorAnchorY(
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,5 +1,80 @@
|
||||
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,
|
||||
@@ -11,3 +86,26 @@ export function isSeriesEntryWinner(
|
||||
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;
|
||||
}
|
||||
|
||||
/* ── 브랜드 원색 ──
|
||||
실제 색상값은 이곳에서만 관리하고, 화면에서는 아래의 의미 토큰을 사용한다. */
|
||||
@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 {
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
@@ -68,6 +77,7 @@ body {
|
||||
--color-content-subtle: var(--lts-content-subtle);
|
||||
--color-content-muted: var(--lts-content-muted);
|
||||
--color-content-disabled: var(--lts-content-disabled);
|
||||
--color-bracket-winner: var(--color-brand-coral);
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
@@ -89,28 +99,24 @@ body {
|
||||
}
|
||||
}
|
||||
|
||||
/* ════════════════════════════════════════════════════════════
|
||||
🎛️ 튜닝 패널 (실험용) — 값만 바꾸면 dev에서 즉시 반영(HMR).
|
||||
확정되면 element로 전환한 뒤 이 블록을 통째로 제거할 것.
|
||||
색은 oklch(밝기% 채도 색상) 형식.
|
||||
════════════════════════════════════════════════════════════ */
|
||||
/* ── 라이트 테마 의미 색상 ── */
|
||||
[data-theme="light"] {
|
||||
/* ── 포인트 4색 (primary 주 액션 / secondary 강조 / accent 하이라이트 / info 정보·보조) ── */
|
||||
|
||||
/* 코랄레드 — primary 117곳 즉시 반영 */
|
||||
--color-primary: oklch(0.708008 0.234375 24);
|
||||
--color-primary: var(--color-brand-coral);
|
||||
--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); /* 흰 글자 */
|
||||
|
||||
/* 골드 — 배경·보더·아이콘만. 텍스트색(text-accent)으론 쓰지 말 것 */
|
||||
--color-accent: oklch(0.853027 0.2 90);
|
||||
--color-accent: var(--color-brand-gold);
|
||||
--color-accent-content: oklch(22% 0.03 80); /* 어두운 글자 */
|
||||
|
||||
/* 시안 — 정보·링크·보조 강조. L70이라 흰배경 텍스트는 약함 → 배경/보더 위주 */
|
||||
--color-info: oklch(70% 0.14523 200);
|
||||
--color-info: var(--color-brand-cyan);
|
||||
--color-info-content: oklch(24% 0.03 215); /* 어두운 글자 */
|
||||
|
||||
/* 텍스트 기본 진하기 (회색 알파의 기준색). 낮출수록 전체가 진해짐 */
|
||||
@@ -122,6 +128,12 @@ body {
|
||||
--color-base-300: oklch(95% 0 0); /* 구분선/보더 */
|
||||
}
|
||||
|
||||
/* 경기 결과 기록의 링크 강조는 양쪽 테마에서 같은 브랜드 코랄을 쓴다.
|
||||
전역 dark primary는 유지해 다른 화면의 기존 색상 의미를 바꾸지 않는다. */
|
||||
.competition-series-history {
|
||||
--color-primary: var(--color-brand-coral);
|
||||
}
|
||||
|
||||
/* ── 실시간 입찰 피드백 모션 ──
|
||||
입찰가 갱신 시 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
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,13 @@ import type {
|
||||
MatchParticipantView,
|
||||
} from "@lolympus/contracts";
|
||||
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 {
|
||||
useAuction,
|
||||
useCollectTournamentResultByRiotMatch,
|
||||
@@ -28,7 +34,14 @@ 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 { 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 { apiFetch, ApiError } from "../lib/api";
|
||||
import { profileIconUrl } from "../lib/ddragon";
|
||||
@@ -1383,6 +1396,7 @@ function formatManualCollectSummary(
|
||||
export default function MatchDetailPage() {
|
||||
const { id } = useParams();
|
||||
const navigate = useNavigate();
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const queryClient = useQueryClient();
|
||||
const authUserId = useAuthUserId();
|
||||
const matchQuery = useMatch(id, DEFAULT_COMMUNITY_ID);
|
||||
@@ -1401,6 +1415,10 @@ export default function MatchDetailPage() {
|
||||
meQuery.data?.memberships.find(
|
||||
(membership) => membership.community?._id === DEFAULT_COMMUNITY_ID,
|
||||
)?.user ?? null;
|
||||
const canManageAuction =
|
||||
currentUser?.role === "owner" || currentUser?.role === "admin";
|
||||
const isCheckingPermissions =
|
||||
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
|
||||
const canUseMemberActions = Boolean(currentUser || authUserId);
|
||||
const auctionQuery = useAuction(id, DEFAULT_COMMUNITY_ID);
|
||||
const [captainSelections, setCaptainSelections] = useState<
|
||||
@@ -1702,6 +1720,33 @@ export default function MatchDetailPage() {
|
||||
return () => window.clearTimeout(timer);
|
||||
}, [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) {
|
||||
return (
|
||||
<main className="max-w-5xl mx-auto px-4 py-20 text-center">
|
||||
@@ -1735,10 +1780,6 @@ export default function MatchDetailPage() {
|
||||
|
||||
const match = mapApiMatchToMatchDetail(matchQuery.data);
|
||||
const si = statusBadge(match.status);
|
||||
const canManageAuction =
|
||||
currentUser?.role === "owner" || currentUser?.role === "admin";
|
||||
const isCheckingPermissions =
|
||||
meQuery.isLoading || (meQuery.isFetching && !meQuery.data);
|
||||
const auctionNotStarted =
|
||||
auctionQuery.error instanceof ApiError && auctionQuery.error.status === 404;
|
||||
const activeAuction = auctionNotStarted ? null : auctionQuery.data;
|
||||
@@ -1792,10 +1833,64 @@ export default function MatchDetailPage() {
|
||||
hasValidCaptainInitialPoints &&
|
||||
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 (
|
||||
<main
|
||||
className={`mx-auto px-4 py-6 sm:px-6 ${
|
||||
matchPageMaxWidthClass(matchQuery.data.gameMode)
|
||||
MATCH_PAGE_MAX_WIDTH_CLASS
|
||||
}`}
|
||||
>
|
||||
<Link
|
||||
@@ -1877,7 +1972,59 @@ export default function MatchDetailPage() {
|
||||
</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
|
||||
className="mb-6 space-y-3 border border-base-content/10 p-4"
|
||||
aria-busy="true"
|
||||
@@ -1888,7 +2035,8 @@ export default function MatchDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{competitionQuery.error &&
|
||||
{showCompetitionState &&
|
||||
competitionQuery.error &&
|
||||
!(
|
||||
competitionQuery.error instanceof ApiError &&
|
||||
competitionQuery.error.status === 404
|
||||
@@ -1898,18 +2046,32 @@ export default function MatchDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{competitionEnabled && competitionQuery.data && (
|
||||
{showCompetitionState && competitionEnabled && competitionQuery.data && (
|
||||
<>
|
||||
<CompetitionResults competition={competitionQuery.data} />
|
||||
<CompetitionAdminControls
|
||||
competition={competitionQuery.data}
|
||||
communityId={DEFAULT_COMMUNITY_ID}
|
||||
canManage={canManageAuction}
|
||||
/>
|
||||
{showCompetitionResults && (
|
||||
<CompetitionResults
|
||||
competition={competitionQuery.data}
|
||||
view={
|
||||
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.status === 404 && (
|
||||
<div
|
||||
@@ -1920,8 +2082,23 @@ export default function MatchDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col lg:flex-row gap-5">
|
||||
<div className="flex-1 min-w-0 space-y-4">
|
||||
{showEmptyOperationsState && (
|
||||
<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" ? (
|
||||
<>
|
||||
<ParticipantTable
|
||||
@@ -2298,6 +2475,16 @@ export default function MatchDetailPage() {
|
||||
</>
|
||||
) : (
|
||||
<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) => (
|
||||
<TeamCard key={team.teamIndex} team={team} />
|
||||
))}
|
||||
@@ -2313,10 +2500,20 @@ export default function MatchDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="w-full lg:w-64 shrink-0 space-y-4">
|
||||
{match.schedule.length > 0 && (
|
||||
<div className={supportingAsideClassName}>
|
||||
{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="일정">
|
||||
<ul className="space-y-2">
|
||||
{match.schedule.map((item, index) => (
|
||||
@@ -2331,7 +2528,8 @@ export default function MatchDetailPage() {
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
{canManageAuction &&
|
||||
{showOperationsPanel &&
|
||||
canManageAuction &&
|
||||
(match.status === "team-built" ||
|
||||
match.status === "in-progress") && (
|
||||
<SideCard title="결과 수집">
|
||||
@@ -2449,7 +2647,7 @@ export default function MatchDetailPage() {
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
{match.prizes.length > 0 && (
|
||||
{showInfoPanel && match.prizes.length > 0 && (
|
||||
<SideCard title="상품">
|
||||
<ul className="space-y-1.5">
|
||||
{match.prizes.map((prize, index) => (
|
||||
@@ -2465,7 +2663,7 @@ export default function MatchDetailPage() {
|
||||
</SideCard>
|
||||
)}
|
||||
|
||||
{match.notices.length > 0 && (
|
||||
{showInfoPanel && match.notices.length > 0 && (
|
||||
<SideCard title="안내사항">
|
||||
<ul className="space-y-1.5">
|
||||
{match.notices.map((notice, index) => (
|
||||
@@ -2482,6 +2680,8 @@ export default function MatchDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
@@ -96,15 +97,15 @@ function resolveBackTarget(
|
||||
return {
|
||||
to: state.backTo,
|
||||
label:
|
||||
typeof state.backLabel === "string"
|
||||
? state.backLabel
|
||||
typeof state.backLabel === "string" && state.backLabel.trim().length > 0
|
||||
? state.backLabel.trim()
|
||||
: "돌아가기",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
to: fallbackTo,
|
||||
label: "경기 결과로 돌아가기",
|
||||
label: "경기 기록으로 돌아가기",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -1,24 +1,46 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Link, useParams } from "react-router";
|
||||
import type {
|
||||
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 { SeriesScoreCard } from "../components/competition/SeriesScoreCard";
|
||||
import { TeamSeriesCard } from "../components/competition/TeamSeriesCard";
|
||||
import { TeamTournamentCodes } from "../components/competition/TeamTournamentCodes";
|
||||
import { DEFAULT_COMMUNITY_ID } from "../config";
|
||||
import { positionLabel } from "../lib/league";
|
||||
import {
|
||||
getTeamProgressErrorContent,
|
||||
isConsistentTeamProgressSnapshot,
|
||||
shouldOfferTeamSelection,
|
||||
type TeamProgressErrorContent,
|
||||
} from "./match-team-progress-state";
|
||||
import {
|
||||
createTeamSeriesGroups,
|
||||
getTeamSeriesDisplayLabel,
|
||||
sortCompletedTeamSeries,
|
||||
sortTeamMembersForRoster,
|
||||
} from "./match-team-progress-view";
|
||||
|
||||
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);
|
||||
const lastAutoRefetchedMismatchRef = useRef<string | null>(null);
|
||||
const contentHeadingRef = useRef<HTMLHeadingElement>(null);
|
||||
const competition = competitionQuery.data;
|
||||
const teamView = teamQuery.data;
|
||||
const teamViewId = teamView?.teamId;
|
||||
const hasQueryError = Boolean(
|
||||
competitionQuery.error || teamQuery.error,
|
||||
);
|
||||
@@ -57,17 +79,35 @@ export default function MatchTeamProgressPage() {
|
||||
revisionMismatchKey,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isSelectingTeam || !teamViewId || !revisionsMatch) return;
|
||||
contentHeadingRef.current?.focus({ preventScroll: true });
|
||||
}, [isSelectingTeam, revisionsMatch, teamViewId]);
|
||||
|
||||
function retryBoth() {
|
||||
void Promise.all([refetchCompetition(), refetchTeam()]).catch(
|
||||
() => undefined,
|
||||
);
|
||||
}
|
||||
|
||||
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(
|
||||
@@ -114,167 +154,245 @@ export default function MatchTeamProgressPage() {
|
||||
competition.teams.map((team) => [team.teamId, team]),
|
||||
);
|
||||
const team = teamById.get(teamView.teamId);
|
||||
const completedSeries = competition.projection.series.filter(
|
||||
(series) =>
|
||||
series.status === "completed" &&
|
||||
series.entries.some((entry) => entry.teamId === teamView.teamId),
|
||||
const activeSeriesGroups = createTeamSeriesGroups(
|
||||
teamView.activeSeries,
|
||||
teamView.tournamentCodes,
|
||||
);
|
||||
|
||||
async function copyCode(gameSlotId: string, code: string | null) {
|
||||
if (!code) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(code);
|
||||
setCopiedSlotId(gameSlotId);
|
||||
window.setTimeout(() => setCopiedSlotId(null), 1500);
|
||||
} catch {
|
||||
setCopiedSlotId(null);
|
||||
}
|
||||
}
|
||||
const completedSeries = sortCompletedTeamSeries(
|
||||
competition.projection.series.filter(
|
||||
(
|
||||
series,
|
||||
): series is Extract<SeriesProjection, { status: "completed" }> =>
|
||||
series.status === "completed" &&
|
||||
series.entries.some((entry) => entry.teamId === teamView.teamId),
|
||||
),
|
||||
);
|
||||
const recentSeries = completedSeries.slice(0, 2);
|
||||
const olderSeries = completedSeries.slice(2);
|
||||
const rounds = competition.projection.rounds;
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-6 sm:px-6">
|
||||
<Link
|
||||
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>
|
||||
|
||||
<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
|
||||
</p>
|
||||
<h1 className="mt-1 text-2xl font-black">{team?.name ?? "내 팀"}</h1>
|
||||
<p className="mt-1 text-sm text-base-content/45">
|
||||
우리 팀의 공식 대진과 토너먼트 코드는 이 페이지에서만 표시됩니다.
|
||||
</p>
|
||||
<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">
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs font-bold text-content-muted">팀 경기 현황</p>
|
||||
<h1
|
||||
ref={contentHeadingRef}
|
||||
className="mt-1 min-w-0 break-words text-2xl font-black sm:text-3xl"
|
||||
tabIndex={-1}
|
||||
>
|
||||
{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>
|
||||
|
||||
<section className="mb-6" aria-labelledby="active-series-heading">
|
||||
<h2
|
||||
<section className="mb-8" aria-labelledby="active-series-heading">
|
||||
<SectionHeading
|
||||
id="active-series-heading"
|
||||
className="mb-3 text-xs font-bold uppercase tracking-wider text-base-content/40"
|
||||
>
|
||||
진행할 Series
|
||||
</h2>
|
||||
{teamView.activeSeries.length > 0 ? (
|
||||
<div className="grid gap-3 md:grid-cols-2">
|
||||
{teamView.activeSeries.map((series) => (
|
||||
<SeriesScoreCard
|
||||
key={series.seriesId}
|
||||
series={series}
|
||||
teamById={teamById}
|
||||
/>
|
||||
))}
|
||||
title="다음 경기"
|
||||
description="현재 팀이 준비하거나 진행해야 하는 공식 대진입니다."
|
||||
/>
|
||||
{activeSeriesGroups.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
{activeSeriesGroups.map(({ series, codes }) => {
|
||||
const displayLabel = getTeamSeriesDisplayLabel(series, rounds);
|
||||
return (
|
||||
<TeamSeriesCard
|
||||
key={series.seriesId}
|
||||
series={series}
|
||||
displayLabel={displayLabel}
|
||||
teamById={teamById}
|
||||
highlightedTeamId={teamView.teamId}
|
||||
emphasized
|
||||
>
|
||||
<TeamTournamentCodes
|
||||
assignments={codes}
|
||||
seriesLabel={displayLabel}
|
||||
/>
|
||||
</TeamSeriesCard>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<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="아직 종료된 대진이 없습니다." />
|
||||
<EmptyState message="현재 준비하거나 진행할 대진이 없습니다." />
|
||||
)}
|
||||
</section>
|
||||
|
||||
{team && (
|
||||
<section className="border border-base-content/10 bg-base-100">
|
||||
<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">
|
||||
팀 구성
|
||||
</h2>
|
||||
<ul className="divide-y divide-base-content/8">
|
||||
{team.members.map((member) => (
|
||||
<section className="mb-8" aria-labelledby="roster-heading">
|
||||
<SectionHeading
|
||||
id="roster-heading"
|
||||
title="팀 구성"
|
||||
description={`${team.members.length}명의 라인업을 포지션 순서로 보여줍니다.`}
|
||||
/>
|
||||
<ul className="divide-y divide-base-content/10 border border-base-content/10 bg-base-100">
|
||||
{sortTeamMembersForRoster(team.members).map((member) => (
|
||||
<li
|
||||
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">
|
||||
<p className="truncate text-sm font-bold">
|
||||
<span className="text-xs font-bold text-content-muted">
|
||||
{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}
|
||||
</p>
|
||||
{member.assignedPosition && (
|
||||
<p className="mt-0.5 text-xs text-base-content/35">
|
||||
{member.assignedPosition}
|
||||
</p>
|
||||
</span>
|
||||
{member.userId === team.captainUserId && (
|
||||
<span className="border-l-2 border-warning bg-warning/15 px-1.5 py-0.5 text-[11px] font-bold text-base-content">
|
||||
팀장
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{member.userId === team.captainUserId && (
|
||||
<span className="text-xs font-bold text-warning">팀장</span>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</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>
|
||||
);
|
||||
}
|
||||
@@ -285,9 +403,11 @@ function TeamProgressLoadingState() {
|
||||
className="mx-auto max-w-5xl space-y-3 px-4 py-12 sm:px-6"
|
||||
aria-busy="true"
|
||||
aria-label="팀 진행 정보를 불러오는 중"
|
||||
role="status"
|
||||
>
|
||||
<div className="h-7 w-48 animate-pulse bg-base-200" />
|
||||
<div className="h-32 animate-pulse bg-base-200/70" />
|
||||
<span className="sr-only">팀 진행 정보를 불러오는 중입니다.</span>
|
||||
<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>
|
||||
);
|
||||
}
|
||||
@@ -303,6 +423,12 @@ function TeamProgressProblemState({
|
||||
matchId: string | undefined;
|
||||
onRetry: () => void;
|
||||
}) {
|
||||
const headingRef = useRef<HTMLHeadingElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
headingRef.current?.focus({ preventScroll: true });
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<main className="mx-auto max-w-5xl px-4 py-20 sm:px-6">
|
||||
<section
|
||||
@@ -310,20 +436,25 @@ function TeamProgressProblemState({
|
||||
aria-busy={isRetrying}
|
||||
className="border border-base-content/10 bg-base-100 px-5 py-8 text-center"
|
||||
>
|
||||
<h1 className="text-lg font-bold">{content.title}</h1>
|
||||
<p className="mt-2 text-sm text-base-content/45">
|
||||
<h1 ref={headingRef} className="text-lg font-bold" tabIndex={-1}>
|
||||
{content.title}
|
||||
</h1>
|
||||
<p className="mt-2 text-sm text-content-muted">
|
||||
{content.description}
|
||||
</p>
|
||||
<div className="mt-5 flex flex-wrap justify-center gap-2">
|
||||
<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}
|
||||
onClick={onRetry}
|
||||
>
|
||||
{isRetrying ? "다시 불러오는 중..." : "다시 시도"}
|
||||
</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>
|
||||
</div>
|
||||
@@ -336,7 +467,7 @@ function EmptyState({ message }: { message: string }) {
|
||||
return (
|
||||
<p
|
||||
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}
|
||||
</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(
|
||||
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 ||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -9,10 +9,19 @@ import type {
|
||||
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");
|
||||
@@ -66,6 +75,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",
|
||||
@@ -98,7 +141,7 @@ test("groups and orders Series by the Asia/Seoul calendar day", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("includes recorded in-progress Series and game-less completed decisions only", () => {
|
||||
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);
|
||||
@@ -131,9 +174,6 @@ test("includes recorded in-progress Series and game-less completed decisions onl
|
||||
|
||||
const history = createCompetitionSeriesHistory({
|
||||
series: [
|
||||
readySeries("ready", teamA, teamB),
|
||||
waitingSeries("waiting"),
|
||||
inactiveSeries("inactive"),
|
||||
unrecordedRunning,
|
||||
administrative,
|
||||
running,
|
||||
@@ -151,6 +191,231 @@ test("includes recorded in-progress Series and game-less completed decisions onl
|
||||
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");
|
||||
@@ -195,52 +460,207 @@ test("sorts tied timestamps deterministically and ignores orphan Games", () => {
|
||||
assert.equal(rows.every(({ games }) => games.length === 0), true);
|
||||
});
|
||||
|
||||
test("returns explicit status labels for played and adjudicated outcomes", () => {
|
||||
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(
|
||||
getSeriesHistoryStatusLabel(
|
||||
inProgressSeries("running", teamA, teamB, 1, 0),
|
||||
shouldDisplaySeriesHistoryScore(
|
||||
inProgressSeries("running-score", teamA, teamB, 1, 0),
|
||||
),
|
||||
"진행 중",
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
getSeriesHistoryStatusLabel(
|
||||
completedSeries({ id: "played", teamA, teamB, scoreA: 2, scoreB: 1 }),
|
||||
),
|
||||
"종료",
|
||||
);
|
||||
assert.equal(
|
||||
getSeriesHistoryStatusLabel(
|
||||
shouldDisplaySeriesHistoryScore(
|
||||
completedSeries({
|
||||
id: "draw",
|
||||
id: "played-score",
|
||||
teamA,
|
||||
teamB,
|
||||
scoreA: 1,
|
||||
scoreA: 2,
|
||||
scoreB: 1,
|
||||
outcome: "draw",
|
||||
}),
|
||||
),
|
||||
"무승부",
|
||||
true,
|
||||
);
|
||||
assert.equal(shouldDisplaySeriesHistoryScore(playedDraw), true);
|
||||
assert.equal(shouldDisplaySeriesHistoryScore(administrativeDraw), false);
|
||||
assert.equal(
|
||||
getSeriesHistoryStatusLabel(
|
||||
shouldDisplaySeriesHistoryScore(
|
||||
completedSeries({
|
||||
id: "walkover",
|
||||
teamA,
|
||||
teamB,
|
||||
scoreA: 0,
|
||||
scoreB: 0,
|
||||
outcome: "walkover",
|
||||
}),
|
||||
),
|
||||
"부전승",
|
||||
);
|
||||
assert.equal(
|
||||
getSeriesHistoryStatusLabel(
|
||||
completedSeries({
|
||||
id: "forfeit",
|
||||
id: "forfeit-score",
|
||||
teamA,
|
||||
teamB,
|
||||
scoreA: 1,
|
||||
@@ -248,23 +668,26 @@ test("returns explicit status labels for played and adjudicated outcomes", () =>
|
||||
outcome: "forfeit",
|
||||
}),
|
||||
),
|
||||
"기권승",
|
||||
);
|
||||
assert.equal(
|
||||
getSeriesHistoryStatusLabel(
|
||||
completedSeries({
|
||||
id: "administrative",
|
||||
teamA,
|
||||
teamB,
|
||||
scoreA: 0,
|
||||
scoreB: 0,
|
||||
outcome: "administrative",
|
||||
}),
|
||||
),
|
||||
"판정",
|
||||
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 +695,23 @@ 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-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,
|
||||
@@ -475,3 +915,14 @@ function seriesId(value: string): 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;
|
||||
}
|
||||
@@ -10,10 +10,13 @@ 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 {
|
||||
bracketRoundAccessibleLabel,
|
||||
bracketRoundLabel,
|
||||
createDoubleEliminationBracketLayout,
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY,
|
||||
} from "../src/components/competition/double-elimination-bracket-layout.ts";
|
||||
@@ -83,10 +86,68 @@ 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("uses compact bracket vocabulary with expanded accessible round names", () => {
|
||||
assert.equal(bracketRoundLabel("upper", 1), "브래킷 1R");
|
||||
assert.equal(bracketRoundLabel("upper", 2), "브래킷 상위 2R");
|
||||
assert.equal(bracketRoundLabel("lower", 1), "브래킷 하위 1R");
|
||||
assert.equal(bracketRoundLabel("lower", 4), "브래킷 하위 4R");
|
||||
assert.equal(bracketRoundLabel("grand-final", 1), "그랜드 파이널");
|
||||
assert.equal(bracketRoundLabel("reset-final", 1), "리셋 파이널");
|
||||
assert.equal(bracketRoundLabel("round-robin", 3), "3라운드");
|
||||
|
||||
assert.equal(
|
||||
bracketRoundAccessibleLabel("upper", 1),
|
||||
"브래킷 1라운드",
|
||||
);
|
||||
assert.equal(
|
||||
bracketRoundAccessibleLabel("upper", 2),
|
||||
"브래킷 상위 2라운드",
|
||||
);
|
||||
assert.equal(
|
||||
bracketRoundAccessibleLabel("lower", 1),
|
||||
"브래킷 하위 1라운드",
|
||||
);
|
||||
assert.equal(
|
||||
bracketRoundAccessibleLabel("grand-final", 1),
|
||||
"그랜드 파이널",
|
||||
);
|
||||
assert.equal(
|
||||
bracketRoundAccessibleLabel("round-robin", 3),
|
||||
"3라운드",
|
||||
);
|
||||
|
||||
const { projection } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
const upperOpening = layout.rounds.find(
|
||||
({ stage, roundNumber }) => stage === "upper" && roundNumber === 1,
|
||||
);
|
||||
const lowerOpening = layout.mobileGroups.find(
|
||||
({ stage, roundNumber }) => stage === "lower" && roundNumber === 1,
|
||||
);
|
||||
assert.ok(upperOpening);
|
||||
assert.ok(lowerOpening);
|
||||
assert.equal(upperOpening.label, "브래킷 1R");
|
||||
assert.equal(upperOpening.accessibleLabel, "브래킷 1라운드");
|
||||
assert.equal(lowerOpening.label, "브래킷 하위 1R");
|
||||
assert.equal(lowerOpening.accessibleLabel, "브래킷 하위 1라운드");
|
||||
});
|
||||
|
||||
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("uses a 40px routing gap while keeping the canonical bracket inside its viewport", () => {
|
||||
const { projection } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
|
||||
assert.equal(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap, 40);
|
||||
assert.equal(layout.columnCount, 6);
|
||||
assert.equal(layout.width, 1592);
|
||||
});
|
||||
|
||||
test("selects the bracket only for a coherent double-elimination snapshot", () => {
|
||||
@@ -196,6 +257,40 @@ test("places every code-less eight-team Series once regardless of input order",
|
||||
);
|
||||
});
|
||||
|
||||
test("uses human-readable match names while preserving technical Series codes", () => {
|
||||
const ordered = eightTeamProjection();
|
||||
const shuffled = eightTeamProjection({ shuffled: true });
|
||||
for (const fixture of [ordered, shuffled]) {
|
||||
for (const series of fixture.projection.series) {
|
||||
series.code = `CODE-${series.seriesId}`;
|
||||
}
|
||||
}
|
||||
const codedSeries = shuffled.projection.series.find(
|
||||
(series) => series.seriesId === shuffled.ids.WB_R2_M2,
|
||||
);
|
||||
assert.ok(codedSeries);
|
||||
codedSeries.code = "WB_R2_M2";
|
||||
|
||||
const orderedLayout = requireLayout(ordered.projection, EIGHT_TEAM_LAYOUT);
|
||||
const shuffledLayout = requireLayout(shuffled.projection, EIGHT_TEAM_LAYOUT);
|
||||
const node = nodeFor(shuffledLayout, shuffled.ids.WB_R2_M2);
|
||||
const winnerRoute = shuffledLayout.connectors.find(
|
||||
(route) =>
|
||||
route.fromSeriesId === shuffled.ids.WB_R2_M2 && route.select === "winner",
|
||||
);
|
||||
assert.ok(winnerRoute);
|
||||
|
||||
assert.equal(node.label, "브래킷 상위 2R · 2경기");
|
||||
assert.equal(node.accessibleLabel, "브래킷 상위 2라운드 · 2경기");
|
||||
assert.deepEqual(labelsBySeriesId(shuffledLayout), labelsBySeriesId(orderedLayout));
|
||||
assert.match(winnerRoute.label, /^브래킷 상위 2R · 2경기 승자 →/);
|
||||
assert.match(
|
||||
winnerRoute.accessibleLabel,
|
||||
/^브래킷 상위 2라운드 · 2경기 승자 →/,
|
||||
);
|
||||
assert.doesNotMatch(winnerRoute.label, /WB_R2_M2/);
|
||||
});
|
||||
|
||||
test("keeps the known WB_R2_M2 winner and loser routes keyed by opaque Series identity", () => {
|
||||
const { projection, ids } = eightTeamProjection({ shuffled: true });
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
@@ -272,6 +367,7 @@ test("orders mobile groups as winners, losers, grand final, then reset final", (
|
||||
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
|
||||
orderedLayout.mobileGroups.map((group) => group.seriesIds),
|
||||
);
|
||||
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
|
||||
assert.deepEqual(
|
||||
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
|
||||
shuffled.projection.series.map((series) => series.seriesId).sort(),
|
||||
@@ -379,11 +475,10 @@ test("returns null instead of throwing for an unknown connector discriminator",
|
||||
);
|
||||
});
|
||||
|
||||
test("keeps connector rails distinct and outside intervening card rectangles", () => {
|
||||
test("keeps connector rails finite and outside intervening card rectangles", () => {
|
||||
const { projection } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||
const routesByTargetColumn = new Map<number, number[]>();
|
||||
|
||||
for (const route of layout.connectors) {
|
||||
const source = nodes.get(route.fromSeriesId);
|
||||
@@ -397,7 +492,10 @@ test("keeps connector rails distinct and outside intervening card rectangles", (
|
||||
assert.equal(route.path.includes("Infinity"), false);
|
||||
assert.notEqual(route.label.trim(), "");
|
||||
assert.ok(target.column > source.column);
|
||||
assert.ok(route.verticalX > target.x - 32);
|
||||
assert.ok(
|
||||
route.verticalX >
|
||||
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap,
|
||||
);
|
||||
assert.ok(route.verticalX < target.x);
|
||||
|
||||
for (const intermediate of layout.nodes) {
|
||||
@@ -413,23 +511,256 @@ test("keeps connector rails distinct and outside intervening card rectangles", (
|
||||
false,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const rails = routesByTargetColumn.get(target.column) ?? [];
|
||||
rails.push(route.verticalX);
|
||||
routesByTargetColumn.set(target.column, rails);
|
||||
test("aligns paired winner bends on one shared rail", () => {
|
||||
const fourTeam = fourTeamProjection();
|
||||
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
|
||||
for (const targetSeriesId of [fourTeam.ids.WB_FINAL, fourTeam.ids.GF]) {
|
||||
const routes = winnerRoutesTo(fourTeamLayout, targetSeriesId);
|
||||
assert.equal(routes.length, 2);
|
||||
assert.equal(routes[0].verticalX, routes[1].verticalX);
|
||||
}
|
||||
|
||||
for (const rails of routesByTargetColumn.values()) {
|
||||
assert.equal(new Set(rails).size, rails.length);
|
||||
const { projection, ids } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
|
||||
for (const targetSeriesId of [
|
||||
ids.WB_R2_M1,
|
||||
ids.WB_R2_M2,
|
||||
ids.WB_FINAL,
|
||||
ids.LB_R3_M1,
|
||||
ids.GF,
|
||||
]) {
|
||||
const routes = winnerRoutesTo(layout, targetSeriesId);
|
||||
assert.equal(routes.length, 2);
|
||||
assert.equal(
|
||||
routes[0].verticalX,
|
||||
routes[1].verticalX,
|
||||
`${targetSeriesId} winner routes must share one bend rail`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps reversed winner slots on deterministic non-overlapping rails", () => {
|
||||
const { projection, ids } = fourTeamProjection();
|
||||
const reversed = cloneProjection(projection);
|
||||
const firstWinner = reversed.connectors.find(
|
||||
({ from, to }) =>
|
||||
from.seriesId === ids.WB_R1_M1 &&
|
||||
from.select === "winner" &&
|
||||
to.seriesId === ids.WB_FINAL,
|
||||
);
|
||||
const secondWinner = reversed.connectors.find(
|
||||
({ from, to }) =>
|
||||
from.seriesId === ids.WB_R1_M2 &&
|
||||
from.select === "winner" &&
|
||||
to.seriesId === ids.WB_FINAL,
|
||||
);
|
||||
assert.ok(firstWinner);
|
||||
assert.ok(secondWinner);
|
||||
firstWinner.to = { seriesId: ids.WB_FINAL, slot: "B" };
|
||||
secondWinner.to = { seriesId: ids.WB_FINAL, slot: "A" };
|
||||
|
||||
const orderedLayout = requireLayout(reversed, FOUR_TEAM_LAYOUT);
|
||||
const shuffled = cloneProjection(reversed);
|
||||
shuffled.connectors = shuffledCopy(shuffled.connectors);
|
||||
const shuffledLayout = requireLayout(shuffled, FOUR_TEAM_LAYOUT);
|
||||
const routes = winnerRoutesTo(orderedLayout, ids.WB_FINAL);
|
||||
|
||||
assert.equal(routes.length, 2);
|
||||
assert.equal(new Set(routes.map(({ verticalX }) => verticalX)).size, 2);
|
||||
assert.equal(countCollinearConnectorOverlaps(orderedLayout.connectors), 0);
|
||||
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
|
||||
});
|
||||
|
||||
test("moves reversed winner rails clear of overlapping connector underlays", () => {
|
||||
const { projection, ids } = eightTeamProjection();
|
||||
const reversed = cloneProjection(projection);
|
||||
const firstWinner = reversed.connectors.find(
|
||||
({ from, to }) =>
|
||||
from.seriesId === ids.WB_R1_M1 &&
|
||||
from.select === "winner" &&
|
||||
to.seriesId === ids.WB_R2_M1,
|
||||
);
|
||||
const secondWinner = reversed.connectors.find(
|
||||
({ from, to }) =>
|
||||
from.seriesId === ids.WB_R1_M2 &&
|
||||
from.select === "winner" &&
|
||||
to.seriesId === ids.WB_R2_M1,
|
||||
);
|
||||
assert.ok(firstWinner);
|
||||
assert.ok(secondWinner);
|
||||
firstWinner.to = { seriesId: ids.WB_R2_M1, slot: "B" };
|
||||
secondWinner.to = { seriesId: ids.WB_R2_M1, slot: "A" };
|
||||
|
||||
const layout = requireLayout(reversed, EIGHT_TEAM_LAYOUT);
|
||||
const shuffled = cloneProjection(reversed);
|
||||
shuffled.connectors = shuffledCopy(shuffled.connectors);
|
||||
const shuffledLayout = requireLayout(shuffled, EIGHT_TEAM_LAYOUT);
|
||||
const winners = winnerRoutesTo(layout, ids.WB_R2_M1);
|
||||
|
||||
assert.equal(winners.length, 2);
|
||||
for (const winner of winners) {
|
||||
for (const route of layout.connectors) {
|
||||
if (
|
||||
route === winner ||
|
||||
!intervalsStrictlyOverlap(
|
||||
winner.sourceY,
|
||||
winner.targetY,
|
||||
route.sourceY,
|
||||
route.targetY,
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
assert.ok(
|
||||
Math.abs(winner.verticalX - route.verticalX) >=
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
|
||||
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${route.fromSeriesId} ${route.kind} rail ${route.verticalX}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(shuffledLayout.connectors, layout.connectors);
|
||||
});
|
||||
|
||||
test("centers conflict-free paired winner bends in the routing gap", () => {
|
||||
const fourTeam = fourTeamProjection();
|
||||
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
|
||||
const fourTeamGrandFinal = nodeFor(fourTeamLayout, fourTeam.ids.GF);
|
||||
assert.deepEqual(
|
||||
winnerRoutesTo(fourTeamLayout, fourTeam.ids.GF).map(
|
||||
({ verticalX }) => verticalX,
|
||||
),
|
||||
[
|
||||
fourTeamGrandFinal.x -
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
|
||||
fourTeamGrandFinal.x -
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
|
||||
],
|
||||
);
|
||||
|
||||
const { projection, ids } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
|
||||
for (const targetSeriesId of [ids.LB_R3_M1, ids.GF]) {
|
||||
const target = nodeFor(layout, targetSeriesId);
|
||||
const expectedVerticalX =
|
||||
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
|
||||
const routes = winnerRoutesTo(layout, targetSeriesId);
|
||||
|
||||
assert.equal(routes.length, 2);
|
||||
assert.deepEqual(
|
||||
routes.map(({ verticalX }) => verticalX),
|
||||
[expectedVerticalX, expectedVerticalX],
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("preserves baseline rails for loser and reset paths", () => {
|
||||
const { projection } = eightTeamProjection({ resetFinal: true });
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
|
||||
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
|
||||
const routesByTargetColumn = new Map<number, ConnectorLayout[]>();
|
||||
|
||||
for (const route of layout.connectors) {
|
||||
const target = nodes.get(route.toSeriesId);
|
||||
assert.ok(target);
|
||||
const routes = routesByTargetColumn.get(target.column) ?? [];
|
||||
routes.push(route);
|
||||
routesByTargetColumn.set(target.column, routes);
|
||||
}
|
||||
|
||||
for (const routes of routesByTargetColumn.values()) {
|
||||
routes.sort(
|
||||
(left, right) =>
|
||||
right.sourceY - left.sourceY ||
|
||||
right.targetY - left.targetY ||
|
||||
connectorLayoutKey(left).localeCompare(connectorLayoutKey(right)),
|
||||
);
|
||||
routes.forEach((route, index) => {
|
||||
if (route.kind === "winner") return;
|
||||
assert.equal(
|
||||
route.verticalX,
|
||||
route.targetX -
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap +
|
||||
(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap * (index + 1)) /
|
||||
(routes.length + 1),
|
||||
);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps paired winner rails clear of overlapping loser paths", () => {
|
||||
const fourTeam = fourTeamProjection();
|
||||
const eightTeam = eightTeamProjection();
|
||||
const fixtures = [
|
||||
{
|
||||
layout: requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
|
||||
pairedWinnerTargets: new Set<SeriesId>([
|
||||
fourTeam.ids.WB_FINAL,
|
||||
fourTeam.ids.GF,
|
||||
]),
|
||||
},
|
||||
{
|
||||
layout: requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
|
||||
pairedWinnerTargets: new Set<SeriesId>([
|
||||
eightTeam.ids.WB_R2_M1,
|
||||
eightTeam.ids.WB_R2_M2,
|
||||
eightTeam.ids.WB_FINAL,
|
||||
eightTeam.ids.LB_R3_M1,
|
||||
eightTeam.ids.GF,
|
||||
]),
|
||||
},
|
||||
];
|
||||
|
||||
for (const { layout, pairedWinnerTargets } of fixtures) {
|
||||
for (const winner of layout.connectors) {
|
||||
if (
|
||||
winner.kind !== "winner" ||
|
||||
!pairedWinnerTargets.has(winner.toSeriesId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
for (const loser of layout.connectors) {
|
||||
if (
|
||||
loser.kind !== "loser" ||
|
||||
!intervalsStrictlyOverlap(
|
||||
winner.sourceY,
|
||||
winner.targetY,
|
||||
loser.sourceY,
|
||||
loser.targetY,
|
||||
)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
assert.ok(
|
||||
Math.abs(winner.verticalX - loser.verticalX) >=
|
||||
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
|
||||
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${loser.fromSeriesId} loser rail ${loser.verticalX}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("minimizes connector crossings without introducing segment overlaps", () => {
|
||||
const { projection } = eightTeamProjection();
|
||||
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
|
||||
const fourTeam = fourTeamProjection();
|
||||
const fourTeamReset = fourTeamProjection({ resetFinal: true });
|
||||
const eightTeam = eightTeamProjection();
|
||||
const eightTeamReset = eightTeamProjection({ resetFinal: true });
|
||||
const layouts = [
|
||||
requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
|
||||
requireLayout(fourTeamReset.projection, FOUR_TEAM_RESET_LAYOUT),
|
||||
requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
|
||||
requireLayout(eightTeamReset.projection, EIGHT_TEAM_RESET_LAYOUT),
|
||||
];
|
||||
|
||||
assert.equal(countStrictConnectorCrossings(layout.connectors), 12);
|
||||
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
|
||||
assert.ok(countStrictConnectorCrossings(layouts[2].connectors) <= 12);
|
||||
for (const layout of layouts) {
|
||||
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
|
||||
}
|
||||
});
|
||||
|
||||
test("aligns connector endpoints with the A and B entry row centers", () => {
|
||||
@@ -823,6 +1154,18 @@ function segment(
|
||||
};
|
||||
}
|
||||
|
||||
function intervalsStrictlyOverlap(
|
||||
firstStart: number,
|
||||
firstEnd: number,
|
||||
secondStart: number,
|
||||
secondEnd: number,
|
||||
): boolean {
|
||||
return (
|
||||
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
|
||||
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
|
||||
);
|
||||
}
|
||||
|
||||
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
|
||||
let crossings = 0;
|
||||
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
|
||||
@@ -892,6 +1235,16 @@ function columnsBySeriesId(
|
||||
);
|
||||
}
|
||||
|
||||
function labelsBySeriesId(
|
||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||
) {
|
||||
return Object.fromEntries(
|
||||
layout.nodes
|
||||
.map((node) => [node.seriesId, node.label] as const)
|
||||
.sort(([left], [right]) => left.localeCompare(right)),
|
||||
);
|
||||
}
|
||||
|
||||
function nodeFor(
|
||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||
id: SeriesId,
|
||||
@@ -901,6 +1254,16 @@ function nodeFor(
|
||||
return node;
|
||||
}
|
||||
|
||||
function winnerRoutesTo(
|
||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||
targetSeriesId: SeriesId,
|
||||
) {
|
||||
return layout.connectors.filter(
|
||||
(route) =>
|
||||
route.kind === "winner" && route.toSeriesId === targetSeriesId,
|
||||
);
|
||||
}
|
||||
|
||||
function routeFrom(
|
||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||
id: SeriesId,
|
||||
@@ -928,6 +1291,10 @@ function connectorIdentity(
|
||||
};
|
||||
}
|
||||
|
||||
function connectorLayoutKey(connector: ConnectorLayout): string {
|
||||
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
|
||||
}
|
||||
|
||||
function mobileGroupKeys(
|
||||
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
|
||||
) {
|
||||
|
||||
@@ -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,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 {
|
||||
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 }),
|
||||
|
||||
@@ -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",
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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,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.
|
||||
@@ -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.
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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.
|
||||
@@ -68,12 +68,19 @@ export interface GrandFinalResetActivationRule {
|
||||
|
||||
export type SeriesActivationRule = GrandFinalResetActivationRule;
|
||||
|
||||
export interface SeriesSchedule {
|
||||
date: string;
|
||||
time: string | null;
|
||||
timeZone: "Asia/Seoul";
|
||||
}
|
||||
|
||||
export interface SeriesDefinition {
|
||||
id: SeriesId;
|
||||
code?: string;
|
||||
stage: SeriesStage;
|
||||
slots: [SeriesSlotDefinition, SeriesSlotDefinition];
|
||||
rule: SeriesRule;
|
||||
schedule?: SeriesSchedule;
|
||||
activation?: SeriesActivationRule;
|
||||
gameSlots: GameSlotDefinition[];
|
||||
}
|
||||
@@ -106,6 +113,7 @@ interface SeriesProjectionBase {
|
||||
code?: string;
|
||||
stage: SeriesStage;
|
||||
rule: SeriesRule;
|
||||
schedule?: SeriesSchedule;
|
||||
}
|
||||
|
||||
export interface PlayedSeriesOutcome {
|
||||
|
||||
Reference in new issue
Block a user