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
);
}
+6 -1
View File
@@ -28,6 +28,7 @@ import {
import { RankBadge } from "../components/RankBadge";
import { CompetitionAdminControls } from "../components/competition/CompetitionAdminControls";
import { CompetitionResults } from "../components/competition/CompetitionResults";
import { matchPageMaxWidthClass } from "../components/competition/competition-display-layout";
import { DEFAULT_COMMUNITY_ID, useAuthUserId } from "../config";
import { apiFetch, ApiError } from "../lib/api";
import { profileIconUrl } from "../lib/ddragon";
@@ -1792,7 +1793,11 @@ export default function MatchDetailPage() {
hasValidAuctionTimerSettings;
return (
<main className="max-w-5xl mx-auto px-4 sm:px-6 py-6">
<main
className={`mx-auto px-4 py-6 sm:px-6 ${
matchPageMaxWidthClass(matchQuery.data.gameMode)
}`}
>
<Link
to="/"
className="inline-flex items-center gap-1 text-xs text-base-content/40 hover:text-base-content transition-colors mb-5"
@@ -0,0 +1,937 @@
import assert from "node:assert/strict";
import test from "node:test";
import type {
BracketRoundView,
CompetitionDetailResponse,
DoubleEliminationCompetitionProjection,
SeriesConnectorView,
SeriesId,
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import {
createCompetitionBracketLayout,
matchPageMaxWidthClass,
} from "../src/components/competition/competition-display-layout.ts";
import {
createDoubleEliminationBracketLayout,
DOUBLE_ELIMINATION_BRACKET_GEOMETRY,
} from "../src/components/competition/double-elimination-bracket-layout.ts";
import { isSeriesEntryWinner } from "../src/components/competition/series-score-card-model.ts";
type BracketStage = "upper" | "lower" | "grand-final" | "reset-final";
const FOUR_TEAM_IDS = {
WB_R1_M1: seriesId("four-upper-opening-1"),
WB_R1_M2: seriesId("four-upper-opening-2"),
WB_FINAL: seriesId("four-upper-final"),
LB_R1_M1: seriesId("four-lower-opening"),
LB_FINAL: seriesId("four-lower-final"),
GF: seriesId("four-grand-final"),
GF_RESET: seriesId("four-reset-final"),
};
const EIGHT_TEAM_IDS = {
WB_R1_M1: seriesId("eight-upper-opening-1"),
WB_R1_M2: seriesId("eight-upper-opening-2"),
WB_R1_M3: seriesId("eight-upper-opening-3"),
WB_R1_M4: seriesId("eight-upper-opening-4"),
WB_R2_M1: seriesId("eight-upper-semifinal-1"),
WB_R2_M2: seriesId("eight-upper-semifinal-2"),
WB_FINAL: seriesId("eight-upper-final"),
LB_R1_M1: seriesId("eight-lower-opening-1"),
LB_R1_M2: seriesId("eight-lower-opening-2"),
LB_R2_M1: seriesId("eight-lower-round-2-match-1"),
LB_R2_M2: seriesId("eight-lower-round-2-match-2"),
LB_R3_M1: seriesId("eight-lower-semifinal"),
LB_FINAL: seriesId("eight-lower-final"),
GF: seriesId("eight-grand-final"),
GF_RESET: seriesId("eight-reset-final"),
};
const FOUR_TEAM_LAYOUT = {
teamCount: 4,
resetFinalEnabled: false,
} as const;
const FOUR_TEAM_RESET_LAYOUT = {
teamCount: 4,
resetFinalEnabled: true,
} as const;
const EIGHT_TEAM_LAYOUT = {
teamCount: 8,
resetFinalEnabled: false,
} as const;
const EIGHT_TEAM_RESET_LAYOUT = {
teamCount: 8,
resetFinalEnabled: true,
} as const;
test("places the canonical four-team DAG in shared time columns", () => {
const { projection, ids } = fourTeamProjection();
const layout = requireLayout(projection, FOUR_TEAM_LAYOUT);
assert.deepEqual(columnsBySeriesId(layout), {
[ids.WB_R1_M1]: 0,
[ids.WB_R1_M2]: 0,
[ids.WB_FINAL]: 1,
[ids.LB_R1_M1]: 1,
[ids.LB_FINAL]: 2,
[ids.GF]: 3,
});
assert.equal(nodeFor(layout, ids.WB_FINAL).lane, "upper");
assert.equal(nodeFor(layout, ids.LB_FINAL).lane, "lower");
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("selects the bracket only for a coherent double-elimination snapshot", () => {
const { projection } = eightTeamProjection();
const competition = competitionDetail(projection);
assert.ok(createCompetitionBracketLayout(competition));
assert.equal(
createCompetitionBracketLayout({
...competition,
teams: competition.teams.slice(1),
}),
null,
);
assert.equal(
createCompetitionBracketLayout({
...competition,
format: { ...competition.format, resetFinalEnabled: true },
}),
null,
);
assert.equal(
createCompetitionBracketLayout({
...competition,
projection: { ...projection, formatType: "round-robin" },
} as CompetitionDetailResponse),
null,
);
});
test("marks a winner only for a completed non-draw Series outcome", () => {
const waiting = pendingSeries(
seriesId("winner-guard-waiting"),
"upper",
1,
1,
);
assert.equal(isSeriesEntryWinner(waiting, null), false);
const teamA = "winner-team-a" as TeamId;
const teamB = "winner-team-b" as TeamId;
const completed = {
...waiting,
status: "completed",
entries: [
{ slot: "A", teamId: teamA, gameWins: 2 },
{ slot: "B", teamId: teamB, gameWins: 1 },
],
outcome: {
type: "played",
winnerTeamId: teamA,
loserTeamId: teamB,
decidedByGameIds: [],
completedAt: "2026-07-13T00:00:00.000Z",
},
} as SeriesProjection;
assert.equal(isSeriesEntryWinner(completed, teamA), true);
assert.equal(isSeriesEntryWinner(completed, teamB), false);
const drawn = {
...completed,
outcome: {
type: "draw",
basis: { type: "played", decidedByGameIds: [] },
completedAt: "2026-07-13T00:00:00.000Z",
},
} as SeriesProjection;
assert.equal(isSeriesEntryWinner(drawn, teamA), false);
assert.equal(isSeriesEntryWinner(drawn, teamB), false);
});
test("places every code-less eight-team Series once regardless of input order", () => {
const ordered = eightTeamProjection();
const shuffled = eightTeamProjection({ shuffled: true });
assert.equal(
shuffled.projection.series.every((series) => series.code === undefined),
true,
);
const orderedLayout = requireLayout(ordered.projection, EIGHT_TEAM_LAYOUT);
const shuffledLayout = requireLayout(shuffled.projection, EIGHT_TEAM_LAYOUT);
const expectedColumns = {
[ordered.ids.WB_R1_M1]: 0,
[ordered.ids.WB_R1_M2]: 0,
[ordered.ids.WB_R1_M3]: 0,
[ordered.ids.WB_R1_M4]: 0,
[ordered.ids.WB_R2_M1]: 1,
[ordered.ids.WB_R2_M2]: 1,
[ordered.ids.WB_FINAL]: 2,
[ordered.ids.LB_R1_M1]: 1,
[ordered.ids.LB_R1_M2]: 1,
[ordered.ids.LB_R2_M1]: 2,
[ordered.ids.LB_R2_M2]: 2,
[ordered.ids.LB_R3_M1]: 3,
[ordered.ids.LB_FINAL]: 4,
[ordered.ids.GF]: 5,
};
assert.deepEqual(columnsBySeriesId(orderedLayout), expectedColumns);
assert.deepEqual(columnsBySeriesId(shuffledLayout), expectedColumns);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
assert.equal(shuffledLayout.nodes.length, shuffled.projection.series.length);
assert.equal(
new Set(shuffledLayout.nodes.map((node) => node.seriesId)).size,
shuffled.projection.series.length,
);
});
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);
assert.deepEqual(routeFrom(layout, ids.WB_R2_M2, "winner"), {
fromSeriesId: ids.WB_R2_M2,
select: "winner",
toSeriesId: ids.WB_FINAL,
toSlot: "B",
kind: "winner",
});
assert.deepEqual(routeFrom(layout, ids.WB_R2_M2, "loser"), {
fromSeriesId: ids.WB_R2_M2,
select: "loser",
toSeriesId: ids.LB_R2_M1,
toSlot: "B",
kind: "loser",
});
});
test("maps grand-final slot carry-over to two distinct reset routes", () => {
const { projection, ids } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
assert.equal(nodeFor(layout, ids.GF_RESET).column, 6);
assert.deepEqual(
layout.connectors
.filter((connector) => connector.fromSeriesId === ids.GF)
.map(connectorIdentity)
.sort((left, right) => left.select.localeCompare(right.select)),
[
{
fromSeriesId: ids.GF,
select: "slot-a",
toSeriesId: ids.GF_RESET,
toSlot: "A",
kind: "reset",
},
{
fromSeriesId: ids.GF,
select: "slot-b",
toSeriesId: ids.GF_RESET,
toSlot: "B",
kind: "reset",
},
],
);
});
test("orders mobile groups as winners, losers, grand final, then reset final", () => {
const ordered = eightTeamProjection({ resetFinal: true });
const shuffled = eightTeamProjection({ resetFinal: true, shuffled: true });
const orderedLayout = requireLayout(
ordered.projection,
EIGHT_TEAM_RESET_LAYOUT,
);
const shuffledLayout = requireLayout(
shuffled.projection,
EIGHT_TEAM_RESET_LAYOUT,
);
assert.deepEqual(mobileGroupKeys(shuffledLayout), [
"upper:1",
"upper:2",
"upper:3",
"lower:1",
"lower:2",
"lower:3",
"lower:4",
"grand-final:1",
"reset-final:1",
]);
assert.deepEqual(
shuffledLayout.mobileGroups.map((group) => group.seriesIds),
orderedLayout.mobileGroups.map((group) => group.seriesIds),
);
assert.deepEqual(
shuffledLayout.mobileGroups.flatMap((group) => group.seriesIds).sort(),
shuffled.projection.series.map((series) => series.seriesId).sort(),
);
});
test("rejects a canonical projection that does not match the configured team count", () => {
const { projection } = eightTeamProjection();
assert.equal(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_LAYOUT),
null,
);
});
test("rejects a reset-final node when reset is disabled by the format", () => {
const { projection } = fourTeamProjection({ resetFinal: true });
assert.equal(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_LAYOUT),
null,
);
assert.ok(
createDoubleEliminationBracketLayout(projection, FOUR_TEAM_RESET_LAYOUT),
);
});
test("requires reset final to carry over the grand-final A and B slots", () => {
const { projection, ids } = eightTeamProjection({ resetFinal: true });
const malformed = cloneProjection(projection);
const slotA = malformed.connectors.find(
({ from }) => from.seriesId === ids.GF && from.select === "slot-a",
);
const slotB = malformed.connectors.find(
({ from }) => from.seriesId === ids.GF && from.select === "slot-b",
);
assert.ok(slotA);
assert.ok(slotB);
slotA.from.select = "slot-b";
slotB.from.select = "slot-a";
assert.equal(
createDoubleEliminationBracketLayout(
malformed,
EIGHT_TEAM_RESET_LAYOUT,
),
null,
);
});
test("rejects invalid stage transitions when source selections remain unique", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const winnerRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M1 && from.select === "winner",
);
const loserRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M1 && from.select === "loser",
);
assert.ok(winnerRoute);
assert.ok(loserRoute);
winnerRoute.from.select = "loser";
loserRoute.from.select = "winner";
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("rejects duplicate source selections when every transition is valid", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const winnerRoute = malformed.connectors.find(
({ from }) =>
from.seriesId === ids.WB_R1_M2 && from.select === "winner",
);
assert.ok(winnerRoute);
winnerRoute.from.seriesId = ids.WB_R1_M1;
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("returns null instead of throwing for an unknown connector discriminator", () => {
const { projection } = fourTeamProjection();
const malformed = cloneProjection(projection);
(
malformed.connectors[0].from as {
seriesId: SeriesId;
select: string;
}
).select = "unexpected";
assert.doesNotThrow(() =>
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
);
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("keeps connector rails distinct 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);
const target = nodes.get(route.toSeriesId);
assert.ok(source);
assert.ok(target);
assert.equal(Number.isFinite(route.verticalX), true);
assert.equal(Number.isFinite(route.sourceY), true);
assert.equal(Number.isFinite(route.targetY), true);
assert.equal(route.path.includes("NaN"), false);
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);
for (const intermediate of layout.nodes) {
if (
intermediate.column <= source.column ||
intermediate.column >= target.column
) {
continue;
}
assert.equal(
route.verticalX > intermediate.x &&
route.verticalX < intermediate.x + intermediate.width,
false,
);
}
const rails = routesByTargetColumn.get(target.column) ?? [];
rails.push(route.verticalX);
routesByTargetColumn.set(target.column, rails);
}
for (const rails of routesByTargetColumn.values()) {
assert.equal(new Set(rails).size, rails.length);
}
});
test("minimizes connector crossings without introducing segment overlaps", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
assert.equal(countStrictConnectorCrossings(layout.connectors), 12);
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
});
test("aligns connector endpoints with the A and B entry row centers", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
for (const route of layout.connectors) {
const source = nodes.get(route.fromSeriesId);
const target = nodes.get(route.toSeriesId);
assert.ok(source);
assert.ok(target);
assert.equal(route.targetY, entryRowCenterY(target.y, route.toSlot));
if (route.select === "slot-a" || route.select === "slot-b") {
assert.equal(
route.sourceY,
entryRowCenterY(source.y, route.select === "slot-a" ? "A" : "B"),
);
}
}
});
test("keeps every node in its lane and centers finals between both lanes", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
for (const node of layout.nodes) {
if (node.lane === "upper") {
assert.ok(node.y >= layout.upperLane.top);
assert.ok(
node.y + node.height <=
layout.upperLane.top + layout.upperLane.height,
);
} else if (node.lane === "lower") {
assert.ok(node.y >= layout.lowerLane.top);
assert.ok(
node.y + node.height <=
layout.lowerLane.top + layout.lowerLane.height,
);
} else {
assert.equal(node.y + node.height / 2, layout.finalCenterY);
}
}
});
test("returns null when a connector references a missing Series", () => {
const { projection, ids } = fourTeamProjection();
const malformed = cloneProjection(projection);
malformed.connectors.push(
connector(ids.GF, "winner", seriesId("missing-series"), "A"),
);
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("returns null when multiple connectors target the same Series slot", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const rerouted = malformed.connectors.find(
(candidate) =>
candidate.from.seriesId === ids.WB_R1_M3 &&
candidate.from.select === "winner",
);
assert.ok(rerouted);
rerouted.to = { seriesId: ids.WB_R2_M1, slot: "A" };
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
test("returns null when connectors introduce a cycle", () => {
const { projection, ids } = fourTeamProjection();
const malformed = cloneProjection(projection);
const openingLoser = malformed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "loser" &&
to.seriesId === ids.LB_R1_M1 &&
to.slot === "A",
);
const lowerFinalWinner = malformed.connectors.find(
({ from, to }) =>
from.seriesId === ids.LB_FINAL &&
from.select === "winner" &&
to.seriesId === ids.GF &&
to.slot === "B",
);
assert.ok(openingLoser);
assert.ok(lowerFinalWinner);
openingLoser.from = { seriesId: ids.LB_FINAL, select: "winner" };
lowerFinalWinner.from = { seriesId: ids.WB_R1_M1, select: "loser" };
assert.equal(
createDoubleEliminationBracketLayout(malformed, FOUR_TEAM_LAYOUT),
null,
);
});
test("returns null when round membership disagrees with Series stage metadata", () => {
const { projection, ids } = eightTeamProjection();
const malformed = cloneProjection(projection);
const series = malformed.series.find(
(candidate) => candidate.seriesId === ids.WB_R1_M1,
);
assert.ok(series);
series.stage = { ...series.stage, roundNumber: 2 };
assert.equal(
createDoubleEliminationBracketLayout(malformed, EIGHT_TEAM_LAYOUT),
null,
);
});
function fourTeamProjection(options: { resetFinal?: boolean } = {}) {
const ids = FOUR_TEAM_IDS;
const series = [
pendingSeries(ids.WB_R1_M1, "upper", 1, 1),
pendingSeries(ids.WB_R1_M2, "upper", 1, 2),
pendingSeries(ids.WB_FINAL, "upper", 2, 3),
pendingSeries(ids.LB_R1_M1, "lower", 1, 4),
pendingSeries(ids.LB_FINAL, "lower", 2, 5),
pendingSeries(ids.GF, "grand-final", 1, 6),
];
const rounds = [
round("upper", 1, 1, [ids.WB_R1_M1, ids.WB_R1_M2]),
round("upper", 2, 3, [ids.WB_FINAL]),
round("lower", 1, 4, [ids.LB_R1_M1]),
round("lower", 2, 5, [ids.LB_FINAL]),
round("grand-final", 1, 6, [ids.GF]),
];
const connectors = [
connector(ids.WB_R1_M1, "winner", ids.WB_FINAL, "A"),
connector(ids.WB_R1_M2, "winner", ids.WB_FINAL, "B"),
connector(ids.WB_R1_M1, "loser", ids.LB_R1_M1, "A"),
connector(ids.WB_R1_M2, "loser", ids.LB_R1_M1, "B"),
connector(ids.LB_R1_M1, "winner", ids.LB_FINAL, "A"),
connector(ids.WB_FINAL, "loser", ids.LB_FINAL, "B"),
connector(ids.WB_FINAL, "winner", ids.GF, "A"),
connector(ids.LB_FINAL, "winner", ids.GF, "B"),
];
if (options.resetFinal) {
series.push(pendingSeries(ids.GF_RESET, "reset-final", 1, 7));
rounds.push(round("reset-final", 1, 7, [ids.GF_RESET]));
connectors.push(
connector(ids.GF, "slot-a", ids.GF_RESET, "A"),
connector(ids.GF, "slot-b", ids.GF_RESET, "B"),
);
}
return { ids, projection: projection(series, rounds, connectors) };
}
function eightTeamProjection(
options: { resetFinal?: boolean; shuffled?: boolean } = {},
) {
const ids = EIGHT_TEAM_IDS;
const series = [
pendingSeries(ids.WB_R1_M1, "upper", 1, 1),
pendingSeries(ids.WB_R1_M2, "upper", 1, 2),
pendingSeries(ids.WB_R1_M3, "upper", 1, 3),
pendingSeries(ids.WB_R1_M4, "upper", 1, 4),
pendingSeries(ids.WB_R2_M1, "upper", 2, 5),
pendingSeries(ids.WB_R2_M2, "upper", 2, 6),
pendingSeries(ids.WB_FINAL, "upper", 3, 7),
pendingSeries(ids.LB_R1_M1, "lower", 1, 8),
pendingSeries(ids.LB_R1_M2, "lower", 1, 9),
pendingSeries(ids.LB_R2_M1, "lower", 2, 10),
pendingSeries(ids.LB_R2_M2, "lower", 2, 11),
pendingSeries(ids.LB_R3_M1, "lower", 3, 12),
pendingSeries(ids.LB_FINAL, "lower", 4, 13),
pendingSeries(ids.GF, "grand-final", 1, 14),
];
const rounds = [
round("upper", 1, 1, [
ids.WB_R1_M1,
ids.WB_R1_M2,
ids.WB_R1_M3,
ids.WB_R1_M4,
]),
round("upper", 2, 5, [ids.WB_R2_M1, ids.WB_R2_M2]),
round("upper", 3, 7, [ids.WB_FINAL]),
round("lower", 1, 8, [ids.LB_R1_M1, ids.LB_R1_M2]),
round("lower", 2, 10, [ids.LB_R2_M1, ids.LB_R2_M2]),
round("lower", 3, 12, [ids.LB_R3_M1]),
round("lower", 4, 13, [ids.LB_FINAL]),
round("grand-final", 1, 14, [ids.GF]),
];
const connectors = [
connector(ids.WB_R1_M1, "winner", ids.WB_R2_M1, "A"),
connector(ids.WB_R1_M2, "winner", ids.WB_R2_M1, "B"),
connector(ids.WB_R1_M3, "winner", ids.WB_R2_M2, "A"),
connector(ids.WB_R1_M4, "winner", ids.WB_R2_M2, "B"),
connector(ids.WB_R2_M1, "winner", ids.WB_FINAL, "A"),
connector(ids.WB_R2_M2, "winner", ids.WB_FINAL, "B"),
connector(ids.WB_R1_M1, "loser", ids.LB_R1_M1, "A"),
connector(ids.WB_R1_M2, "loser", ids.LB_R1_M1, "B"),
connector(ids.WB_R1_M3, "loser", ids.LB_R1_M2, "A"),
connector(ids.WB_R1_M4, "loser", ids.LB_R1_M2, "B"),
connector(ids.LB_R1_M1, "winner", ids.LB_R2_M1, "A"),
connector(ids.WB_R2_M2, "loser", ids.LB_R2_M1, "B"),
connector(ids.LB_R1_M2, "winner", ids.LB_R2_M2, "A"),
connector(ids.WB_R2_M1, "loser", ids.LB_R2_M2, "B"),
connector(ids.LB_R2_M1, "winner", ids.LB_R3_M1, "A"),
connector(ids.LB_R2_M2, "winner", ids.LB_R3_M1, "B"),
connector(ids.LB_R3_M1, "winner", ids.LB_FINAL, "A"),
connector(ids.WB_FINAL, "loser", ids.LB_FINAL, "B"),
connector(ids.WB_FINAL, "winner", ids.GF, "A"),
connector(ids.LB_FINAL, "winner", ids.GF, "B"),
];
if (options.resetFinal) {
series.push(pendingSeries(ids.GF_RESET, "reset-final", 1, 15));
rounds.push(round("reset-final", 1, 15, [ids.GF_RESET]));
connectors.push(
connector(ids.GF, "slot-a", ids.GF_RESET, "A"),
connector(ids.GF, "slot-b", ids.GF_RESET, "B"),
);
}
const orderedProjection = projection(series, rounds, connectors);
if (!options.shuffled) return { ids, projection: orderedProjection };
return {
ids,
projection: {
...orderedProjection,
series: shuffledCopy(orderedProjection.series),
rounds: shuffledCopy(orderedProjection.rounds).map((value) => ({
...value,
seriesIds: shuffledCopy(value.seriesIds),
})),
connectors: shuffledCopy(orderedProjection.connectors),
},
};
}
function projection(
series: SeriesProjection[],
rounds: BracketRoundView[],
connectors: SeriesConnectorView[],
): DoubleEliminationCompetitionProjection {
return {
sourceRevision: 1,
projectorVersion: 1,
phase: "running",
formatType: "double-elimination",
series,
games: [],
gameSlots: [],
rounds,
connectors,
placements: [],
};
}
function competitionDetail(
projection: DoubleEliminationCompetitionProjection,
): CompetitionDetailResponse {
return {
projection,
format: {
type: "double-elimination",
teamCount: 8,
resetFinalEnabled: false,
},
teams: Array.from({ length: 8 }, (_, index) => ({
teamId: `team-${index + 1}`,
})),
} as CompetitionDetailResponse;
}
function pendingSeries(
id: SeriesId,
stage: BracketStage,
roundNumber: number,
displayOrder: number,
): SeriesProjection {
return {
seriesId: id,
stage: { type: stage, roundNumber, displayOrder },
rule: { type: "first-to", winsRequired: 1, maxGames: 1 },
entries: [
{ slot: "A", teamId: null, gameWins: 0 },
{ slot: "B", teamId: null, gameWins: 0 },
],
status: "waiting",
};
}
function round(
stage: BracketStage,
roundNumber: number,
displayOrder: number,
seriesIds: SeriesId[],
): BracketRoundView {
return {
stage,
roundNumber,
displayOrder,
label: `${stage}-${roundNumber}`,
seriesIds,
};
}
function connector(
fromSeriesId: SeriesId,
select: SeriesConnectorView["from"]["select"],
toSeriesId: SeriesId,
slot: SeriesConnectorView["to"]["slot"],
): SeriesConnectorView {
return {
from: { seriesId: fromSeriesId, select },
to: { seriesId: toSeriesId, slot },
};
}
function seriesId(value: string): SeriesId {
return value as SeriesId;
}
function cloneProjection(
value: DoubleEliminationCompetitionProjection,
): DoubleEliminationCompetitionProjection {
return structuredClone(value);
}
function shuffledCopy<T>(values: readonly T[]): T[] {
return values.filter((_, index) => index % 2 === 1).reverse().concat(
values.filter((_, index) => index % 2 === 0).reverse(),
);
}
function requireLayout(
projection: DoubleEliminationCompetitionProjection,
options:
| typeof FOUR_TEAM_LAYOUT
| typeof FOUR_TEAM_RESET_LAYOUT
| typeof EIGHT_TEAM_LAYOUT
| typeof EIGHT_TEAM_RESET_LAYOUT,
) {
const layout = createDoubleEliminationBracketLayout(projection, options);
assert.ok(layout);
return layout;
}
function entryRowCenterY(top: number, slot: "A" | "B"): number {
const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY;
const rowIndex = slot === "A" ? 0 : 1;
return (
top +
geometry.cardBorderWidth +
geometry.cardHeaderHeight +
geometry.cardEntryHeight * (rowIndex + 0.5)
);
}
type ConnectorLayout = NonNullable<
ReturnType<typeof createDoubleEliminationBracketLayout>
>["connectors"][number];
type OrthogonalSegment =
| { orientation: "horizontal"; fixed: number; start: number; end: number }
| { orientation: "vertical"; fixed: number; start: number; end: number };
function connectorSegments(route: ConnectorLayout): OrthogonalSegment[] {
return [
segment("horizontal", route.sourceY, route.sourceX, route.verticalX),
segment("vertical", route.verticalX, route.sourceY, route.targetY),
segment("horizontal", route.targetY, route.verticalX, route.targetX),
];
}
function segment(
orientation: OrthogonalSegment["orientation"],
fixed: number,
first: number,
second: number,
): OrthogonalSegment {
return {
orientation,
fixed,
start: Math.min(first, second),
end: Math.max(first, second),
};
}
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
let crossings = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftSegments = connectorSegments(routes[leftIndex]);
for (let rightIndex = leftIndex + 1; rightIndex < routes.length; rightIndex += 1) {
const rightSegments = connectorSegments(routes[rightIndex]);
for (const left of leftSegments) {
for (const right of rightSegments) {
const horizontal =
left.orientation === "horizontal"
? left
: right.orientation === "horizontal"
? right
: null;
const vertical =
left.orientation === "vertical"
? left
: right.orientation === "vertical"
? right
: null;
if (
horizontal &&
vertical &&
vertical.fixed > horizontal.start &&
vertical.fixed < horizontal.end &&
horizontal.fixed > vertical.start &&
horizontal.fixed < vertical.end
) {
crossings += 1;
}
}
}
}
}
return crossings;
}
function countCollinearConnectorOverlaps(routes: readonly ConnectorLayout[]): number {
let overlaps = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
const leftSegments = connectorSegments(routes[leftIndex]);
for (let rightIndex = leftIndex + 1; rightIndex < routes.length; rightIndex += 1) {
const rightSegments = connectorSegments(routes[rightIndex]);
for (const left of leftSegments) {
for (const right of rightSegments) {
if (
left.orientation === right.orientation &&
left.fixed === right.fixed &&
Math.min(left.end, right.end) > Math.max(left.start, right.start)
) {
overlaps += 1;
}
}
}
}
}
return overlaps;
}
function columnsBySeriesId(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return Object.fromEntries(
layout.nodes
.map((node) => [node.seriesId, node.column] as const)
.sort(([left], [right]) => left.localeCompare(right)),
);
}
function nodeFor(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
) {
const node = layout.nodes.find((candidate) => candidate.seriesId === id);
assert.ok(node);
return node;
}
function routeFrom(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
select: SeriesConnectorView["from"]["select"],
) {
const route = layout.connectors.find(
(candidate) =>
candidate.fromSeriesId === id && candidate.select === select,
);
assert.ok(route);
return connectorIdentity(route);
}
function connectorIdentity(
connector: NonNullable<
ReturnType<typeof createDoubleEliminationBracketLayout>
>["connectors"][number],
) {
return {
fromSeriesId: connector.fromSeriesId,
select: connector.select,
toSeriesId: connector.toSeriesId,
toSlot: connector.toSlot,
kind: connector.kind,
};
}
function mobileGroupKeys(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return layout.mobileGroups.map(
(group) => `${group.stage}:${group.roundNumber ?? 0}`,
);
}