feat: render double-elimination bracket

This commit is contained in:
dahyeon committed 2026-07-13 08:37:52 +00:00
1 parent 738d274095
commit 075fb52848
10 files changed
+2379 -65

No files matched your search

@@ -5,6 +5,9 @@ import type {
TeamId,
} from "@lolympus/contracts";
import { Link } from "react-router";
import { DoubleEliminationBracket } from "./DoubleEliminationBracket";
import { createCompetitionBracketLayout } from "./competition-display-layout";
import { bracketRoundLabel } from "./double-elimination-bracket-layout";
import { RoundRobinTable } from "./RoundRobinTable";
import { SeriesScoreCard } from "./SeriesScoreCard";
@@ -20,6 +23,7 @@ export function CompetitionResults({
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const doubleEliminationLayout = createCompetitionBracketLayout(competition);
return (
<section className="mb-6 space-y-4" aria-labelledby="competition-heading">
@@ -54,18 +58,20 @@ export function CompetitionResults({
)}
{projection.rounds.length > 0 ? (
<div className="overflow-x-auto pb-2">
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
{projection.rounds.map((round) => (
<RoundColumn
key={`${round.stage}:${round.roundNumber ?? 0}`}
round={round}
seriesById={seriesById}
teamById={teamById}
/>
))}
</div>
</div>
projection.formatType === "double-elimination" &&
doubleEliminationLayout ? (
<DoubleEliminationBracket
projection={projection}
layout={doubleEliminationLayout}
teamById={teamById}
/>
) : (
<GenericRoundGrid
rounds={projection.rounds}
seriesById={seriesById}
teamById={teamById}
/>
)
) : (
<p
className="border border-dashed border-base-content/15 px-4 py-5 text-sm text-base-content/45"
@@ -101,6 +107,34 @@ export function CompetitionResults({
);
}
function GenericRoundGrid({
rounds,
seriesById,
teamById,
}: {
rounds: BracketRoundView[];
seriesById: Map<
string,
CompetitionDetailResponse["projection"]["series"][number]
>;
teamById: Map<TeamId, CompetitionDetailResponse["teams"][number]>;
}) {
return (
<div className="overflow-x-auto pb-2">
<div className="grid min-w-max auto-cols-[17rem] grid-flow-col gap-4">
{rounds.map((round) => (
<RoundColumn
key={`${round.stage}:${round.roundNumber ?? 0}`}
round={round}
seriesById={seriesById}
teamById={teamById}
/>
))}
</div>
</div>
);
}
function RoundColumn({
round,
seriesById,
@@ -116,7 +150,7 @@ function RoundColumn({
return (
<section aria-label={round.label} className="space-y-2">
<h3 className="px-1 text-xs font-bold text-base-content/45">
{stageLabel(round.stage, round.roundNumber)}
{bracketRoundLabel(round.stage, round.roundNumber)}
</h3>
<div className="space-y-3">
{round.seriesIds.map((seriesId) => {
@@ -166,20 +200,3 @@ function OutcomeSummary({
</p>
);
}
function stageLabel(stage: BracketRoundView["stage"], round?: number) {
switch (stage) {
case "pair":
return "대진";
case "round-robin":
return `${round ?? 1}라운드`;
case "upper":
return `승자조 ${round ?? 1}라운드`;
case "lower":
return `패자조 ${round ?? 1}라운드`;
case "grand-final":
return "그랜드 파이널";
case "reset-final":
return "리셋 파이널";
}
}
@@ -0,0 +1,282 @@
import type {
CompetitionTeamView,
DoubleEliminationCompetitionProjection,
TeamId,
} from "@lolympus/contracts";
import type {
BracketConnectorKind,
DoubleEliminationBracketLayout,
} from "./double-elimination-bracket-layout";
import { DOUBLE_ELIMINATION_BRACKET_GEOMETRY } from "./double-elimination-bracket-layout";
import { DoubleEliminationMobileBracket } from "./DoubleEliminationMobileBracket";
import { SeriesScoreCard } from "./SeriesScoreCard";
export function DoubleEliminationBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
return (
<>
<DesktopBracket
projection={projection}
layout={layout}
teamById={teamById}
/>
<DoubleEliminationMobileBracket
projection={projection}
layout={layout}
teamById={teamById}
/>
</>
);
}
function DesktopBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const finalNodes = layout.nodes.filter(({ lane }) => lane === "final");
const hasResetRoute = layout.connectors.some(({ kind }) => kind === "reset");
const finalZoneLeft = Math.max(
0,
Math.min(...finalNodes.map(({ x }) => x), layout.width) - 16,
);
return (
<div className="hidden xl:block">
<div className="mb-2 flex flex-wrap items-center justify-between gap-3 text-xs text-content-muted">
<p>
승자조와 패자조는 같은 시간축을 공유하며 오른쪽 결승에서 합류합니다.
<span className="ml-2 text-content-subtle">
화면에 모두 보이지 않으면 가로로 스크롤하세요.
</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"
style={{ width: layout.width, height: layout.height }}
>
<LaneBand
label="승자조"
description="패배 시 패자조 이동"
top={layout.upperLane.top}
height={layout.upperLane.height}
width={layout.width}
/>
<LaneBand
label="패자조"
description="패배 시 탈락"
top={layout.lowerLane.top}
height={layout.lowerLane.height}
width={layout.width}
/>
{finalNodes.length > 0 && (
<div
className="absolute border-l border-primary/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"
>
{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"
style={{
left: round.x,
top: round.labelY,
width: DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnWidth,
}}
>
{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,
);
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>
)}
</div>
);
})}
</section>
))}
</div>
</div>
</div>
);
}
function LaneBand({
label,
description,
top,
height,
width,
}: {
label: string;
description: string;
top: number;
height: number;
width: number;
}) {
return (
<>
<div
className="absolute border-y border-base-content/8 bg-base-content/[0.018]"
style={{ top: top - 6, width, height: height + 12 }}
aria-hidden="true"
/>
<p
className="absolute z-[2] flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-content-muted"
style={{ left: 12, top: top - 57 }}
>
<span>{label}</span>
<span className="font-normal normal-case tracking-normal text-content-subtle">
{description}
</span>
</p>
</>
);
}
function ConnectorLegend({ showReset }: { showReset: boolean }) {
return (
<div className="flex flex-wrap items-center gap-4" aria-label="연결선 범례">
<LegendItem label="승자 진출" kind="winner" />
<LegendItem label="패자조 이동" kind="loser" />
{showReset && <LegendItem label="리셋 대진 유지" kind="reset" />}
</div>
);
}
function LegendItem({
label,
kind,
}: {
label: string;
kind: BracketConnectorKind;
}) {
return (
<span className="inline-flex items-center gap-1.5">
<svg width="24" height="6" aria-hidden="true">
<path
d="M 0 3 H 24"
fill="none"
stroke="currentColor"
strokeWidth="1.25"
strokeDasharray={connectorDash(kind)}
className={connectorClass(kind)}
/>
</svg>
{label}
</span>
);
}
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";
return undefined;
}
@@ -0,0 +1,121 @@
import type {
CompetitionTeamView,
DoubleEliminationCompetitionProjection,
SeriesId,
TeamId,
} from "@lolympus/contracts";
import type { DoubleEliminationBracketLayout } from "./double-elimination-bracket-layout";
import { SeriesScoreCard } from "./SeriesScoreCard";
export function DoubleEliminationMobileBracket({
projection,
layout,
teamById,
}: {
projection: DoubleEliminationCompetitionProjection;
layout: DoubleEliminationBracketLayout;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
}) {
const seriesById = new Map(
projection.series.map((series) => [series.seriesId, series]),
);
const nodeById = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const sections = [
{
key: "upper",
title: "승자조",
description: "승리하면 승자조에 남고, 패배하면 패자조로 이동합니다.",
stages: new Set(["upper"]),
},
{
key: "lower",
title: "패자조",
description: "승리하면 다음 라운드로 진출하고, 패배하면 탈락합니다.",
stages: new Set(["lower"]),
},
{
key: "final",
title: "결승",
description: "승자조 우승 팀과 패자조 우승 팀이 최종 우승을 결정합니다.",
stages: new Set(["grand-final", "reset-final"]),
},
];
return (
<div
className="space-y-7 xl:hidden"
role="region"
aria-label="더블 엘리미네이션 대진표"
>
{sections.map((section) => {
const groups = layout.mobileGroups.filter((group) =>
section.stages.has(group.stage),
);
if (groups.length === 0) return null;
return (
<section key={section.key} aria-labelledby={`bracket-${section.key}`}>
<div className="mb-3 border-b border-base-content/10 pb-2">
<h3 id={`bracket-${section.key}`} className="text-sm font-bold">
{section.title}
</h3>
<p className="mt-0.5 text-xs text-content-muted">
{section.description}
</p>
</div>
<div className="space-y-5">
{groups.map((group) => (
<section
key={`${group.stage}:${group.roundNumber}`}
aria-label={group.label}
>
<h4 className="mb-2 text-xs font-bold text-content-muted">
{group.label}
</h4>
<div className="space-y-3">
{group.seriesIds.map((seriesId) => {
const series = seriesById.get(seriesId);
if (!series) return null;
return (
<div key={seriesId}>
<SeriesScoreCard
series={series}
displayLabel={nodeById.get(seriesId)?.label}
teamById={teamById}
variant="bracket"
/>
<MobileRoutes layout={layout} seriesId={seriesId} />
</div>
);
})}
</div>
</section>
))}
</div>
</section>
);
})}
</div>
);
}
function MobileRoutes({
layout,
seriesId,
}: {
layout: DoubleEliminationBracketLayout;
seriesId: SeriesId;
}) {
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">
{routes.map((route) => (
<li key={`${route.select}:${route.toSeriesId}:${route.toSlot}`}>
{route.label}
</li>
))}
</ul>
);
}
@@ -3,6 +3,8 @@ import type {
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry";
import { isSeriesEntryWinner } from "./series-score-card-model";
const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
inactive: "비활성",
@@ -14,24 +16,41 @@ const STATUS_LABEL: Record<SeriesProjection["status"], string> = {
export function SeriesScoreCard({
series,
displayLabel,
teamById,
variant = "default",
}: {
series: SeriesProjection;
displayLabel?: string;
teamById: ReadonlyMap<TeamId, CompetitionTeamView>;
variant?: "default" | "bracket";
}) {
const winnerTeamId =
series.status === "completed" && series.outcome.type !== "draw"
? series.outcome.winnerTeamId
: null;
const isBracket = variant === "bracket";
const seriesLabel = series.code ?? displayLabel;
return (
<article
className="border border-base-content/10 bg-base-100"
aria-label={`${series.code ?? "경기"} ${STATUS_LABEL[series.status]}`}
aria-label={`${seriesLabel ?? "경기"} ${STATUS_LABEL[series.status]}`}
style={
isBracket ? { height: SERIES_SCORE_CARD_GEOMETRY.height } : undefined
}
>
<header className="flex items-center justify-between gap-3 border-b border-base-content/8 px-3 py-2">
<span className="truncate text-xs font-bold text-base-content/65">
{series.code ?? "Series"}
<header
className={`flex items-center justify-between gap-3 border-b border-base-content/8 ${
isBracket ? "px-2" : "px-3 py-2"
}`}
style={
isBracket
? { height: SERIES_SCORE_CARD_GEOMETRY.headerHeight }
: undefined
}
>
<span
className="truncate text-xs font-bold text-base-content/65"
title={seriesLabel ?? "Series"}
>
{seriesLabel ?? "Series"}
</span>
<span className="shrink-0 text-[11px] text-base-content/40">
{STATUS_LABEL[series.status]}
@@ -40,36 +59,96 @@ export function SeriesScoreCard({
<div className="divide-y divide-base-content/8">
{series.entries.map((entry) => {
const team = entry.teamId ? teamById.get(entry.teamId) : undefined;
const isWinner = entry.teamId === winnerTeamId;
return (
<div
const isWinner = isSeriesEntryWinner(series, entry.teamId);
const teamName =
team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중");
return isBracket ? (
<BracketEntryRow
key={entry.slot}
className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5"
>
<span className="text-[10px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`truncate text-sm ${
isWinner
? "font-bold text-base-content"
: "text-base-content/60"
}`}
>
{team?.name ?? (entry.teamId ? "알 수 없는 팀" : "대기 중")}
{isWinner && (
<span className="ml-2 text-[10px] font-bold text-success">
승리
</span>
)}
</span>
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
{entry.gameWins}
</span>
</div>
entry={entry}
isWinner={isWinner}
teamName={teamName}
/>
) : (
<DefaultEntryRow
key={entry.slot}
entry={entry}
isWinner={isWinner}
teamName={teamName}
/>
);
})}
</div>
</article>
);
}
function DefaultEntryRow({
entry,
isWinner,
teamName,
}: {
entry: SeriesProjection["entries"][number];
isWinner: boolean;
teamName: string;
}) {
return (
<div className="grid grid-cols-[1.5rem_minmax(0,1fr)_2rem] items-center gap-2 px-3 py-2.5">
<span className="text-[10px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`truncate text-sm ${
isWinner ? "font-bold text-base-content" : "text-base-content/60"
}`}
>
{teamName}
{isWinner && (
<span className="ml-2 text-[10px] font-bold text-success">승리</span>
)}
</span>
<Score gameWins={entry.gameWins} />
</div>
);
}
function BracketEntryRow({
entry,
isWinner,
teamName,
}: {
entry: SeriesProjection["entries"][number];
isWinner: boolean;
teamName: string;
}) {
return (
<div
className="grid grid-cols-[0.75rem_minmax(0,1fr)_1.5rem_1.25rem] items-center gap-1 px-2"
style={{ height: SERIES_SCORE_CARD_GEOMETRY.entryHeight }}
>
<span className="text-[9px] font-bold text-base-content/30">
{entry.slot}
</span>
<span
className={`line-clamp-2 break-words text-[13px] leading-4 ${
isWinner ? "font-bold text-base-content" : "text-base-content/60"
}`}
title={teamName}
>
{teamName}
</span>
<span className="text-center text-[10px] font-bold text-success">
{isWinner ? "승리" : null}
</span>
<Score gameWins={entry.gameWins} />
</div>
);
}
function Score({ gameWins }: { gameWins: number }) {
return (
<span className="text-right font-mono text-base font-bold tabular-nums text-base-content/75">
{gameWins}
</span>
);
}
@@ -0,0 +1,32 @@
import type {
CompetitionDetailResponse,
MatchGameMode,
} 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 function createCompetitionBracketLayout(
competition: CompetitionDetailResponse,
) {
const { format, projection, teams } = competition;
if (
format.type !== "double-elimination" ||
projection.formatType !== "double-elimination" ||
format.teamCount !== teams.length
) {
return null;
}
const hasResetFinal = projection.series.some(
({ stage }) => stage.type === "reset-final",
);
if (format.resetFinalEnabled !== hasResetFinal) return null;
return createDoubleEliminationBracketLayout(projection, {
teamCount: format.teamCount,
resetFinalEnabled: format.resetFinalEnabled,
});
}
@@ -0,0 +1,822 @@
import type {
BracketRoundView,
DoubleEliminationCompetitionProjection,
SeriesConnectorView,
SeriesId,
SeriesSlot,
SeriesStageType,
} from "@lolympus/contracts";
import { SERIES_SCORE_CARD_GEOMETRY } from "./series-score-card-geometry.ts";
type BracketStage = "upper" | "lower" | "grand-final" | "reset-final";
export type BracketLane = "upper" | "lower" | "final";
export type BracketConnectorKind = "winner" | "loser" | "reset";
export const DOUBLE_ELIMINATION_BRACKET_GEOMETRY = {
boardPadding: 12,
columnWidth: 228,
columnGap: 32,
cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth,
cardHeight: SERIES_SCORE_CARD_GEOMETRY.height,
cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight,
cardEntryHeight: SERIES_SCORE_CARD_GEOMETRY.entryHeight,
cardGap: 20,
upperTop: 64,
laneGap: 152,
} as const;
export interface BracketNodeLayout {
seriesId: SeriesId;
label: string;
stage: BracketStage;
roundNumber: number;
lane: BracketLane;
column: number;
x: number;
y: number;
width: number;
height: number;
}
export interface BracketConnectorLayout {
fromSeriesId: SeriesId;
select: SeriesConnectorView["from"]["select"];
toSeriesId: SeriesId;
toSlot: SeriesSlot;
kind: BracketConnectorKind;
sourceX: number;
sourceY: number;
verticalX: number;
targetX: number;
targetY: number;
path: string;
label: string;
}
export interface DoubleEliminationBracketConfiguration {
teamCount: 4 | 8;
resetFinalEnabled: boolean;
}
export interface BracketRoundLayout {
stage: BracketStage;
roundNumber: number;
label: string;
lane: BracketLane;
column: number;
x: number;
labelY: number;
seriesIds: SeriesId[];
}
export interface MobileBracketGroup {
stage: BracketStage;
roundNumber: number;
label: string;
seriesIds: SeriesId[];
}
export interface DoubleEliminationBracketLayout {
width: number;
height: number;
columnCount: number;
upperLane: { top: number; height: number };
lowerLane: { top: number; height: number };
finalCenterY: number;
nodes: BracketNodeLayout[];
rounds: BracketRoundLayout[];
connectors: BracketConnectorLayout[];
mobileGroups: MobileBracketGroup[];
}
interface ValidatedGraph {
seriesById: Map<SeriesId, DoubleEliminationCompetitionProjection["series"][number]>;
roundBySeriesId: Map<SeriesId, NormalizedRound>;
rounds: NormalizedRound[];
rankBySeriesId: Map<SeriesId, number>;
}
interface NormalizedRound {
stage: BracketStage;
roundNumber: number;
label: string;
seriesIds: SeriesId[];
}
const STAGE_ORDER: Record<BracketStage, number> = {
upper: 0,
lower: 1,
"grand-final": 2,
"reset-final": 3,
};
const CONNECTOR_SELECTION_ORDER: Record<
SeriesConnectorView["from"]["select"],
number
> = {
winner: 0,
loser: 1,
"slot-a": 2,
"slot-b": 3,
};
export function createDoubleEliminationBracketLayout(
projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration,
): DoubleEliminationBracketLayout | null {
const graph = validateGraph(projection, configuration);
if (!graph) return null;
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const upperRounds = graph.rounds.filter(({ stage }) => stage === "upper");
const lowerRounds = graph.rounds.filter(({ stage }) => stage === "lower");
const upperHeight = laneHeight(upperRounds);
const lowerHeight = laneHeight(lowerRounds);
const upperLane = { top: geometry.upperTop, height: upperHeight };
const lowerLane = {
top: upperLane.top + upperLane.height + geometry.laneGap,
height: lowerHeight,
};
const finalCenterY = upperLane.top + upperLane.height + geometry.laneGap / 2;
const columnCount =
Math.max(...graph.rankBySeriesId.values(), 0) + 1;
const width =
geometry.boardPadding * 2 +
columnCount * geometry.columnWidth +
Math.max(0, columnCount - 1) * geometry.columnGap;
const height = lowerLane.top + lowerLane.height + geometry.boardPadding;
const nodes = buildNodes(graph, upperLane, lowerLane, finalCenterY);
const nodeById = new Map(nodes.map((node) => [node.seriesId, node]));
const connectors = buildConnectors(projection, graph, nodeById);
if (!connectors) return null;
return {
width,
height,
columnCount,
upperLane,
lowerLane,
finalCenterY,
nodes,
rounds: buildRoundLayouts(graph, nodeById, upperLane, lowerLane),
connectors,
mobileGroups: graph.rounds.map((round) => ({ ...round })),
};
}
export function bracketRoundLabel(
stage: SeriesStageType,
roundNumber?: number,
): string {
switch (stage) {
case "upper":
return `승자조 ${roundNumber ?? 1}라운드`;
case "lower":
return `패자조 ${roundNumber ?? 1}라운드`;
case "grand-final":
return "그랜드 파이널";
case "reset-final":
return "리셋 파이널";
case "pair":
return "대진";
case "round-robin":
return `${roundNumber ?? 1}라운드`;
}
}
function validateGraph(
projection: DoubleEliminationCompetitionProjection,
configuration: DoubleEliminationBracketConfiguration,
): ValidatedGraph | null {
if (projection.formatType !== "double-elimination") return null;
if (projection.series.length === 0) return null;
if (configuration.teamCount !== 4 && configuration.teamCount !== 8) {
return null;
}
const seriesById = new Map<
SeriesId,
DoubleEliminationCompetitionProjection["series"][number]
>();
const displayOrders = new Set<number>();
for (const series of projection.series) {
if (seriesById.has(series.seriesId)) return null;
if (!isBracketStage(series.stage.type)) return null;
if (!isRoundNumber(series.stage.roundNumber)) return null;
if (
!Number.isInteger(series.stage.displayOrder) ||
series.stage.displayOrder <= 0 ||
displayOrders.has(series.stage.displayOrder)
) {
return null;
}
displayOrders.add(series.stage.displayOrder);
seriesById.set(series.seriesId, series);
}
const normalizedRounds = normalizeRounds(projection.rounds, seriesById);
if (!normalizedRounds) return null;
const roundBySeriesId = new Map<SeriesId, NormalizedRound>();
for (const round of normalizedRounds) {
for (const seriesId of round.seriesIds) {
if (roundBySeriesId.has(seriesId)) return null;
roundBySeriesId.set(seriesId, round);
}
}
if (roundBySeriesId.size !== seriesById.size) return null;
const grandFinals = projection.series.filter(
({ stage }) => stage.type === "grand-final",
);
const resetFinals = projection.series.filter(
({ stage }) => stage.type === "reset-final",
);
if (
!matchesCanonicalShape(
projection,
normalizedRounds,
configuration,
grandFinals.length,
resetFinals.length,
)
) {
return null;
}
if (!hasContiguousRounds(normalizedRounds, "upper")) return null;
if (!hasContiguousRounds(normalizedRounds, "lower")) return null;
if (!connectorsHaveSupportedDiscriminators(projection.connectors)) return null;
const rankBySeriesId = rankConnectorDag(
projection.series.map(({ seriesId }) => seriesId),
projection.connectors,
seriesById,
);
if (!rankBySeriesId) return null;
if (!validateTopology(projection, seriesById, configuration)) {
return null;
}
for (const round of normalizedRounds) {
const ranks = new Set(
round.seriesIds.map((seriesId) => rankBySeriesId.get(seriesId)),
);
if (ranks.size !== 1 || ranks.has(undefined)) return null;
}
return {
seriesById,
roundBySeriesId,
rounds: normalizedRounds,
rankBySeriesId,
};
}
function normalizeRounds(
rounds: readonly BracketRoundView[],
seriesById: ValidatedGraph["seriesById"],
): NormalizedRound[] | null {
const keys = new Set<string>();
const result: NormalizedRound[] = [];
for (const round of rounds) {
if (!isBracketStage(round.stage) || !isRoundNumber(round.roundNumber)) {
return null;
}
const key = `${round.stage}:${round.roundNumber}`;
if (keys.has(key) || round.seriesIds.length === 0) return null;
keys.add(key);
const ids = [...round.seriesIds].sort((left, right) => {
const leftSeries = seriesById.get(left);
const rightSeries = seriesById.get(right);
return (
(leftSeries?.stage.displayOrder ?? 0) -
(rightSeries?.stage.displayOrder ?? 0)
);
});
for (const seriesId of ids) {
const series = seriesById.get(seriesId);
if (
!series ||
series.stage.type !== round.stage ||
series.stage.roundNumber !== round.roundNumber
) {
return null;
}
}
result.push({
stage: round.stage,
roundNumber: round.roundNumber,
label: bracketRoundLabel(round.stage, round.roundNumber),
seriesIds: ids,
});
}
return result.sort(
(left, right) =>
STAGE_ORDER[left.stage] - STAGE_ORDER[right.stage] ||
left.roundNumber - right.roundNumber,
);
}
function rankConnectorDag(
seriesIds: readonly SeriesId[],
connectors: readonly SeriesConnectorView[],
seriesById: ValidatedGraph["seriesById"],
): Map<SeriesId, number> | null {
const indegree = new Map(seriesIds.map((seriesId) => [seriesId, 0]));
const outgoing = new Map(seriesIds.map((seriesId) => [seriesId, [] as SeriesId[]]));
const targetedSlots = new Set<string>();
for (const connector of connectors) {
const source = seriesById.get(connector.from.seriesId);
const target = seriesById.get(connector.to.seriesId);
if (!source || !target || source.seriesId === target.seriesId) return null;
const targetSlotKey = `${target.seriesId}:${connector.to.slot}`;
if (targetedSlots.has(targetSlotKey)) return null;
targetedSlots.add(targetSlotKey);
indegree.set(target.seriesId, (indegree.get(target.seriesId) ?? 0) + 1);
outgoing.get(source.seriesId)?.push(target.seriesId);
}
const rank = new Map(seriesIds.map((seriesId) => [seriesId, 0]));
const queue = seriesIds
.filter((seriesId) => indegree.get(seriesId) === 0)
.sort((left, right) =>
compareSeriesDisplayOrder(seriesById.get(left), seriesById.get(right)),
);
let processed = 0;
while (queue.length > 0) {
const sourceId = queue.shift();
if (!sourceId) break;
processed += 1;
for (const targetId of outgoing.get(sourceId) ?? []) {
rank.set(
targetId,
Math.max(rank.get(targetId) ?? 0, (rank.get(sourceId) ?? 0) + 1),
);
const remaining = (indegree.get(targetId) ?? 0) - 1;
indegree.set(targetId, remaining);
if (remaining === 0) {
queue.push(targetId);
queue.sort((left, right) =>
compareSeriesDisplayOrder(seriesById.get(left), seriesById.get(right)),
);
}
}
}
return processed === seriesIds.length ? rank : null;
}
function validateTopology(
projection: DoubleEliminationCompetitionProjection,
seriesById: ValidatedGraph["seriesById"],
configuration: DoubleEliminationBracketConfiguration,
): boolean {
const incoming = new Map<SeriesId, SeriesConnectorView[]>();
const sourceSelections = new Set<string>();
for (const connector of projection.connectors) {
const source = seriesById.get(connector.from.seriesId);
const target = seriesById.get(connector.to.seriesId);
if (
!source ||
!target ||
!isBracketStage(source.stage.type) ||
!isBracketStage(target.stage.type) ||
!isRoundNumber(source.stage.roundNumber) ||
!isRoundNumber(target.stage.roundNumber)
) {
return false;
}
const sourceSelectionKey = `${source.seriesId}:${connector.from.select}`;
if (sourceSelections.has(sourceSelectionKey)) return false;
sourceSelections.add(sourceSelectionKey);
if (
!isCanonicalTransition(
source.stage.type,
source.stage.roundNumber,
target.stage.type,
target.stage.roundNumber,
connector.from.select,
configuration,
)
) {
return false;
}
const list = incoming.get(connector.to.seriesId) ?? [];
list.push(connector);
incoming.set(connector.to.seriesId, list);
if (
connector.from.select === "slot-a" ||
connector.from.select === "slot-b"
) {
const expectedSlot = connector.from.select === "slot-a" ? "A" : "B";
if (connector.to.slot !== expectedSlot) return false;
}
}
for (const series of projection.series) {
const edges = incoming.get(series.seriesId) ?? [];
const isRoot = series.stage.type === "upper" && series.stage.roundNumber === 1;
if (isRoot) {
if (edges.length !== 0) return false;
continue;
}
if (
edges.length !== 2 ||
!edges.some(({ to }) => to.slot === "A") ||
!edges.some(({ to }) => to.slot === "B")
) {
return false;
}
}
return true;
}
function buildNodes(
graph: ValidatedGraph,
upperLane: DoubleEliminationBracketLayout["upperLane"],
lowerLane: DoubleEliminationBracketLayout["lowerLane"],
finalCenterY: number,
): BracketNodeLayout[] {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const result: BracketNodeLayout[] = [];
for (const round of graph.rounds) {
const lane = laneForStage(round.stage);
const laneGeometry = lane === "upper" ? upperLane : lowerLane;
round.seriesIds.forEach((seriesId, index) => {
const column = graph.rankBySeriesId.get(seriesId) ?? 0;
const centerY =
lane === "final"
? finalCenterY
: laneGeometry.top +
(laneGeometry.height * (index + 0.5)) / round.seriesIds.length;
result.push({
seriesId,
label: seriesName(graph.seriesById.get(seriesId), round),
stage: round.stage,
roundNumber: round.roundNumber,
lane,
column,
x:
geometry.boardPadding +
column * (geometry.columnWidth + geometry.columnGap),
y: centerY - geometry.cardHeight / 2,
width: geometry.columnWidth,
height: geometry.cardHeight,
});
});
}
return result;
}
function buildRoundLayouts(
graph: ValidatedGraph,
nodeById: Map<SeriesId, BracketNodeLayout>,
upperLane: DoubleEliminationBracketLayout["upperLane"],
lowerLane: DoubleEliminationBracketLayout["lowerLane"],
): BracketRoundLayout[] {
return graph.rounds.map((round) => {
const node = nodeById.get(round.seriesIds[0]);
const lane = laneForStage(round.stage);
const labelY =
lane === "upper"
? upperLane.top - 28
: lane === "lower"
? lowerLane.top - 28
: (node?.y ?? 0) - 28;
return {
...round,
lane,
column: node?.column ?? 0,
x: node?.x ?? 0,
labelY,
};
});
}
function buildConnectors(
projection: DoubleEliminationCompetitionProjection,
graph: ValidatedGraph,
nodeById: Map<SeriesId, BracketNodeLayout>,
): BracketConnectorLayout[] | null {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const connectorsByTargetColumn = new Map<
number,
Array<{
connector: SeriesConnectorView;
source: BracketNodeLayout;
target: BracketNodeLayout;
}>
>();
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 verticalXByConnector = new Map<string, number>();
for (const routes of connectorsByTargetColumn.values()) {
routes.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)),
);
routes.forEach(({ connector, target }, index) => {
verticalXByConnector.set(
connectorKey(connector),
target.x -
geometry.columnGap +
(geometry.columnGap * (index + 1)) / (routes.length + 1),
);
});
}
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));
if (verticalX === undefined) return null;
const kind = connectorKind(connector.from.select);
result.push({
fromSeriesId: connector.from.seriesId,
select: connector.from.select,
toSeriesId: connector.to.seriesId,
toSlot: connector.to.slot,
kind,
sourceX,
sourceY,
verticalX,
targetX,
targetY,
path: `M ${number(sourceX)} ${number(sourceY)} H ${number(verticalX)} V ${number(targetY)} H ${number(targetX)}`,
label: connectorLabel(connector, graph),
});
}
return result.sort(
(left, right) =>
compareSeriesDisplayOrder(
graph.seriesById.get(left.fromSeriesId),
graph.seriesById.get(right.fromSeriesId),
) ||
CONNECTOR_SELECTION_ORDER[left.select] -
CONNECTOR_SELECTION_ORDER[right.select] ||
compareSeriesDisplayOrder(
graph.seriesById.get(left.toSeriesId),
graph.seriesById.get(right.toSeriesId),
) ||
left.toSlot.localeCompare(right.toSlot),
);
}
function connectorLabel(
connector: SeriesConnectorView,
graph: ValidatedGraph,
): 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 selection =
connector.from.select === "winner"
? "승자"
: connector.from.select === "loser"
? "패자"
: connector.from.select === "slot-a"
? "A팀"
: "B팀";
return `${sourceName} ${selection} → ${targetName} ${connector.to.slot} 슬롯`;
}
function seriesName(
series: DoubleEliminationCompetitionProjection["series"][number] | undefined,
round: NormalizedRound | undefined,
): string {
if (series?.code) return series.code;
if (!series || !round) return "알 수 없는 경기";
const index = round.seriesIds.indexOf(series.seriesId);
return round.seriesIds.length > 1
? `${round.label} ${index + 1}경기`
: round.label;
}
function connectorAnchorY(
node: BracketNodeLayout,
select: SeriesConnectorView["from"]["select"],
): number {
const center = node.y + node.height / 2;
switch (select) {
case "winner":
return center - 7;
case "loser":
return center + 7;
case "slot-a":
return targetSlotY(node, "A");
case "slot-b":
return targetSlotY(node, "B");
}
}
function targetSlotY(node: BracketNodeLayout, slot: SeriesSlot): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const rowIndex = slot === "A" ? 0 : 1;
return (
node.y +
geometry.cardBorderWidth +
geometry.cardHeaderHeight +
geometry.cardEntryHeight * (rowIndex + 0.5)
);
}
function connectorKind(
select: SeriesConnectorView["from"]["select"],
): BracketConnectorKind {
if (select === "winner") return "winner";
if (select === "loser") return "loser";
return "reset";
}
function connectorKey(connector: SeriesConnectorView): string {
return `${connector.from.seriesId}:${connector.from.select}:${connector.to.seriesId}:${connector.to.slot}`;
}
function matchesCanonicalShape(
projection: DoubleEliminationCompetitionProjection,
rounds: readonly NormalizedRound[],
configuration: DoubleEliminationBracketConfiguration,
grandFinalCount: number,
resetFinalCount: number,
): boolean {
const expectedUpper =
configuration.teamCount === 4 ? [2, 1] : [4, 2, 1];
const expectedLower =
configuration.teamCount === 4 ? [1, 1] : [2, 2, 1, 1];
const resetCount = configuration.resetFinalEnabled ? 1 : 0;
const expectedSeriesCount = configuration.teamCount * 2 - 2 + resetCount;
const expectedConnectorCount =
configuration.teamCount * 3 - 4 + resetCount * 2;
return (
projection.series.length === expectedSeriesCount &&
projection.connectors.length === expectedConnectorCount &&
grandFinalCount === 1 &&
resetFinalCount === resetCount &&
roundSizes(rounds, "upper").every(
(size, index) => size === expectedUpper[index],
) &&
roundSizes(rounds, "upper").length === expectedUpper.length &&
roundSizes(rounds, "lower").every(
(size, index) => size === expectedLower[index],
) &&
roundSizes(rounds, "lower").length === expectedLower.length &&
rounds.filter(({ stage }) => stage === "grand-final").length === 1 &&
rounds
.filter(({ stage }) => stage === "grand-final")
.every(({ roundNumber, seriesIds }) => roundNumber === 1 && seriesIds.length === 1) &&
rounds.filter(({ stage }) => stage === "reset-final").length === resetCount &&
rounds
.filter(({ stage }) => stage === "reset-final")
.every(({ roundNumber, seriesIds }) => roundNumber === 1 && seriesIds.length === 1)
);
}
function roundSizes(
rounds: readonly NormalizedRound[],
stage: "upper" | "lower",
): number[] {
return rounds
.filter((round) => round.stage === stage)
.sort((left, right) => left.roundNumber - right.roundNumber)
.map(({ seriesIds }) => seriesIds.length);
}
function connectorsHaveSupportedDiscriminators(
connectors: readonly SeriesConnectorView[],
): boolean {
return connectors.every(
(connector) =>
isConnectorSelection(connector.from.select) &&
isSeriesSlot(connector.to.slot),
);
}
function isCanonicalTransition(
sourceStage: BracketStage,
sourceRound: number,
targetStage: BracketStage,
targetRound: number,
select: SeriesConnectorView["from"]["select"],
configuration: DoubleEliminationBracketConfiguration,
): boolean {
const upperFinalRound = configuration.teamCount === 4 ? 2 : 3;
const lowerFinalRound = configuration.teamCount === 4 ? 2 : 4;
if (select === "winner") {
if (sourceStage === "upper") {
return sourceRound < upperFinalRound
? targetStage === "upper" && targetRound === sourceRound + 1
: sourceRound === upperFinalRound && targetStage === "grand-final";
}
if (sourceStage === "lower") {
return sourceRound < lowerFinalRound
? targetStage === "lower" && targetRound === sourceRound + 1
: sourceRound === lowerFinalRound && targetStage === "grand-final";
}
return false;
}
if (select === "loser") {
return (
sourceStage === "upper" &&
targetStage === "lower" &&
targetRound ===
(sourceRound === upperFinalRound ? lowerFinalRound : sourceRound)
);
}
return sourceStage === "grand-final" && targetStage === "reset-final";
}
function laneHeight(rounds: readonly NormalizedRound[]): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const maxSeries = Math.max(...rounds.map(({ seriesIds }) => seriesIds.length), 1);
return maxSeries * (geometry.cardHeight + geometry.cardGap);
}
function laneForStage(stage: BracketStage): BracketLane {
if (stage === "upper") return "upper";
if (stage === "lower") return "lower";
return "final";
}
function hasContiguousRounds(
rounds: readonly NormalizedRound[],
stage: "upper" | "lower",
): boolean {
const numbers = rounds
.filter((round) => round.stage === stage)
.map(({ roundNumber }) => roundNumber)
.sort((left, right) => left - right);
return (
numbers.length > 0 && numbers.every((roundNumber, index) => roundNumber === index + 1)
);
}
function isBracketStage(stage: SeriesStageType): stage is BracketStage {
return (
stage === "upper" ||
stage === "lower" ||
stage === "grand-final" ||
stage === "reset-final"
);
}
function isRoundNumber(value: number | undefined): value is number {
return Number.isInteger(value) && (value ?? 0) > 0;
}
function isConnectorSelection(
value: unknown,
): value is SeriesConnectorView["from"]["select"] {
return (
value === "winner" ||
value === "loser" ||
value === "slot-a" ||
value === "slot-b"
);
}
function isSeriesSlot(value: unknown): value is SeriesSlot {
return value === "A" || value === "B";
}
function compareSeriesDisplayOrder(
left: DoubleEliminationCompetitionProjection["series"][number] | undefined,
right: DoubleEliminationCompetitionProjection["series"][number] | undefined,
): number {
return (left?.stage.displayOrder ?? 0) - (right?.stage.displayOrder ?? 0);
}
function number(value: number): string {
return Number.isInteger(value) ? String(value) : value.toFixed(1);
}
@@ -0,0 +1,6 @@
export const SERIES_SCORE_CARD_GEOMETRY = {
borderWidth: 1,
height: 116,
headerHeight: 32,
entryHeight: 41,
} as const;
@@ -0,0 +1,13 @@
import type { SeriesProjection, TeamId } from "@lolympus/contracts";
export function isSeriesEntryWinner(
series: SeriesProjection,
teamId: TeamId | null,
): boolean {
return (
teamId !== null &&
series.status === "completed" &&
series.outcome.type !== "draw" &&
series.outcome.winnerTeamId === teamId
);
}