Files
lolympus-tournament-support/apps/web/test/double-elimination-bracket-layout.test.ts

1305 lines
41 KiB
TypeScript

import assert from "node:assert/strict";
import test from "node:test";
import type {
BracketRoundView,
CompetitionDetailResponse,
DoubleEliminationCompetitionProjection,
SeriesConnectorView,
SeriesId,
SeriesProjection,
TeamId,
} from "@lolympus/contracts";
import {
DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS,
MATCH_PAGE_MAX_WIDTH_CLASS,
createCompetitionBracketLayout,
} from "../src/components/competition/competition-display-layout.ts";
import {
bracketRoundAccessibleLabel,
bracketRoundLabel,
createDoubleEliminationBracketLayout,
DOUBLE_ELIMINATION_BRACKET_GEOMETRY,
} from "../src/components/competition/double-elimination-bracket-layout.ts";
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("uses compact bracket vocabulary with expanded accessible round names", () => {
assert.equal(bracketRoundLabel("upper", 1), "브래킷 1R");
assert.equal(bracketRoundLabel("upper", 2), "브래킷 상위 2R");
assert.equal(bracketRoundLabel("lower", 1), "브래킷 하위 1R");
assert.equal(bracketRoundLabel("lower", 4), "브래킷 하위 4R");
assert.equal(bracketRoundLabel("grand-final", 1), "그랜드 파이널");
assert.equal(bracketRoundLabel("reset-final", 1), "리셋 파이널");
assert.equal(bracketRoundLabel("round-robin", 3), "3라운드");
assert.equal(
bracketRoundAccessibleLabel("upper", 1),
"브래킷 1라운드",
);
assert.equal(
bracketRoundAccessibleLabel("upper", 2),
"브래킷 상위 2라운드",
);
assert.equal(
bracketRoundAccessibleLabel("lower", 1),
"브래킷 하위 1라운드",
);
assert.equal(
bracketRoundAccessibleLabel("grand-final", 1),
"그랜드 파이널",
);
assert.equal(
bracketRoundAccessibleLabel("round-robin", 3),
"3라운드",
);
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const upperOpening = layout.rounds.find(
({ stage, roundNumber }) => stage === "upper" && roundNumber === 1,
);
const lowerOpening = layout.mobileGroups.find(
({ stage, roundNumber }) => stage === "lower" && roundNumber === 1,
);
assert.ok(upperOpening);
assert.ok(lowerOpening);
assert.equal(upperOpening.label, "브래킷 1R");
assert.equal(upperOpening.accessibleLabel, "브래킷 1라운드");
assert.equal(lowerOpening.label, "브래킷 하위 1R");
assert.equal(lowerOpening.accessibleLabel, "브래킷 하위 1라운드");
});
test("keeps the match page narrow and gives only the desktop bracket a wide viewport", () => {
assert.equal(MATCH_PAGE_MAX_WIDTH_CLASS, "max-w-5xl");
assert.match(DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS, /max-w-\[1600px\]/);
assert.match(
DOUBLE_ELIMINATION_BRACKET_VIEWPORT_CLASS,
/w-\[calc\(100vw-3rem\)\]/,
);
});
test("uses a 40px routing gap while keeping the canonical bracket inside its viewport", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
assert.equal(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap, 40);
assert.equal(layout.columnCount, 6);
assert.equal(layout.width, 1592);
});
test("selects the bracket only for a coherent double-elimination snapshot", () => {
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("uses human-readable match names while preserving technical Series codes", () => {
const ordered = eightTeamProjection();
const shuffled = eightTeamProjection({ shuffled: true });
for (const fixture of [ordered, shuffled]) {
for (const series of fixture.projection.series) {
series.code = `CODE-${series.seriesId}`;
}
}
const codedSeries = shuffled.projection.series.find(
(series) => series.seriesId === shuffled.ids.WB_R2_M2,
);
assert.ok(codedSeries);
codedSeries.code = "WB_R2_M2";
const orderedLayout = requireLayout(ordered.projection, EIGHT_TEAM_LAYOUT);
const shuffledLayout = requireLayout(shuffled.projection, EIGHT_TEAM_LAYOUT);
const node = nodeFor(shuffledLayout, shuffled.ids.WB_R2_M2);
const winnerRoute = shuffledLayout.connectors.find(
(route) =>
route.fromSeriesId === shuffled.ids.WB_R2_M2 && route.select === "winner",
);
assert.ok(winnerRoute);
assert.equal(node.label, "브래킷 상위 2R · 2경기");
assert.equal(node.accessibleLabel, "브래킷 상위 2라운드 · 2경기");
assert.deepEqual(labelsBySeriesId(shuffledLayout), labelsBySeriesId(orderedLayout));
assert.match(winnerRoute.label, /^브래킷 상위 2R · 2경기 승자 →/);
assert.match(
winnerRoute.accessibleLabel,
/^브래킷 상위 2라운드 · 2경기 승자 →/,
);
assert.doesNotMatch(winnerRoute.label, /WB_R2_M2/);
});
test("keeps the known WB_R2_M2 winner and loser routes keyed by opaque Series identity", () => {
const { projection, ids } = eightTeamProjection({ shuffled: true });
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
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.connectors, orderedLayout.connectors);
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 finite and outside intervening card rectangles", () => {
const { projection } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
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 - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap,
);
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,
);
}
}
});
test("aligns paired winner bends on one shared rail", () => {
const fourTeam = fourTeamProjection();
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
for (const targetSeriesId of [fourTeam.ids.WB_FINAL, fourTeam.ids.GF]) {
const routes = winnerRoutesTo(fourTeamLayout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(routes[0].verticalX, routes[1].verticalX);
}
const { projection, ids } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [
ids.WB_R2_M1,
ids.WB_R2_M2,
ids.WB_FINAL,
ids.LB_R3_M1,
ids.GF,
]) {
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.equal(
routes[0].verticalX,
routes[1].verticalX,
`${targetSeriesId} winner routes must share one bend rail`,
);
}
});
test("keeps reversed winner slots on deterministic non-overlapping rails", () => {
const { projection, ids } = fourTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_FINAL,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_FINAL, slot: "B" };
secondWinner.to = { seriesId: ids.WB_FINAL, slot: "A" };
const orderedLayout = requireLayout(reversed, FOUR_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, FOUR_TEAM_LAYOUT);
const routes = winnerRoutesTo(orderedLayout, ids.WB_FINAL);
assert.equal(routes.length, 2);
assert.equal(new Set(routes.map(({ verticalX }) => verticalX)).size, 2);
assert.equal(countCollinearConnectorOverlaps(orderedLayout.connectors), 0);
assert.deepEqual(shuffledLayout.connectors, orderedLayout.connectors);
});
test("moves reversed winner rails clear of overlapping connector underlays", () => {
const { projection, ids } = eightTeamProjection();
const reversed = cloneProjection(projection);
const firstWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M1 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
const secondWinner = reversed.connectors.find(
({ from, to }) =>
from.seriesId === ids.WB_R1_M2 &&
from.select === "winner" &&
to.seriesId === ids.WB_R2_M1,
);
assert.ok(firstWinner);
assert.ok(secondWinner);
firstWinner.to = { seriesId: ids.WB_R2_M1, slot: "B" };
secondWinner.to = { seriesId: ids.WB_R2_M1, slot: "A" };
const layout = requireLayout(reversed, EIGHT_TEAM_LAYOUT);
const shuffled = cloneProjection(reversed);
shuffled.connectors = shuffledCopy(shuffled.connectors);
const shuffledLayout = requireLayout(shuffled, EIGHT_TEAM_LAYOUT);
const winners = winnerRoutesTo(layout, ids.WB_R2_M1);
assert.equal(winners.length, 2);
for (const winner of winners) {
for (const route of layout.connectors) {
if (
route === winner ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
route.sourceY,
route.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - route.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${route.fromSeriesId} ${route.kind} rail ${route.verticalX}`,
);
}
}
assert.deepEqual(shuffledLayout.connectors, layout.connectors);
});
test("centers conflict-free paired winner bends in the routing gap", () => {
const fourTeam = fourTeamProjection();
const fourTeamLayout = requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT);
const fourTeamGrandFinal = nodeFor(fourTeamLayout, fourTeam.ids.GF);
assert.deepEqual(
winnerRoutesTo(fourTeamLayout, fourTeam.ids.GF).map(
({ verticalX }) => verticalX,
),
[
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
fourTeamGrandFinal.x -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2,
],
);
const { projection, ids } = eightTeamProjection();
const layout = requireLayout(projection, EIGHT_TEAM_LAYOUT);
for (const targetSeriesId of [ids.LB_R3_M1, ids.GF]) {
const target = nodeFor(layout, targetSeriesId);
const expectedVerticalX =
target.x - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2;
const routes = winnerRoutesTo(layout, targetSeriesId);
assert.equal(routes.length, 2);
assert.deepEqual(
routes.map(({ verticalX }) => verticalX),
[expectedVerticalX, expectedVerticalX],
);
}
});
test("preserves baseline rails for loser and reset paths", () => {
const { projection } = eightTeamProjection({ resetFinal: true });
const layout = requireLayout(projection, EIGHT_TEAM_RESET_LAYOUT);
const nodes = new Map(layout.nodes.map((node) => [node.seriesId, node]));
const routesByTargetColumn = new Map<number, ConnectorLayout[]>();
for (const route of layout.connectors) {
const target = nodes.get(route.toSeriesId);
assert.ok(target);
const routes = routesByTargetColumn.get(target.column) ?? [];
routes.push(route);
routesByTargetColumn.set(target.column, routes);
}
for (const routes of routesByTargetColumn.values()) {
routes.sort(
(left, right) =>
right.sourceY - left.sourceY ||
right.targetY - left.targetY ||
connectorLayoutKey(left).localeCompare(connectorLayoutKey(right)),
);
routes.forEach((route, index) => {
if (route.kind === "winner") return;
assert.equal(
route.verticalX,
route.targetX -
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap +
(DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap * (index + 1)) /
(routes.length + 1),
);
});
}
});
test("keeps paired winner rails clear of overlapping loser paths", () => {
const fourTeam = fourTeamProjection();
const eightTeam = eightTeamProjection();
const fixtures = [
{
layout: requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
fourTeam.ids.WB_FINAL,
fourTeam.ids.GF,
]),
},
{
layout: requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
pairedWinnerTargets: new Set<SeriesId>([
eightTeam.ids.WB_R2_M1,
eightTeam.ids.WB_R2_M2,
eightTeam.ids.WB_FINAL,
eightTeam.ids.LB_R3_M1,
eightTeam.ids.GF,
]),
},
];
for (const { layout, pairedWinnerTargets } of fixtures) {
for (const winner of layout.connectors) {
if (
winner.kind !== "winner" ||
!pairedWinnerTargets.has(winner.toSeriesId)
) {
continue;
}
for (const loser of layout.connectors) {
if (
loser.kind !== "loser" ||
!intervalsStrictlyOverlap(
winner.sourceY,
winner.targetY,
loser.sourceY,
loser.targetY,
)
) {
continue;
}
assert.ok(
Math.abs(winner.verticalX - loser.verticalX) >=
DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance,
`${winner.fromSeriesId} winner rail ${winner.verticalX} is too close to ${loser.fromSeriesId} loser rail ${loser.verticalX}`,
);
}
}
}
});
test("minimizes connector crossings without introducing segment overlaps", () => {
const fourTeam = fourTeamProjection();
const fourTeamReset = fourTeamProjection({ resetFinal: true });
const eightTeam = eightTeamProjection();
const eightTeamReset = eightTeamProjection({ resetFinal: true });
const layouts = [
requireLayout(fourTeam.projection, FOUR_TEAM_LAYOUT),
requireLayout(fourTeamReset.projection, FOUR_TEAM_RESET_LAYOUT),
requireLayout(eightTeam.projection, EIGHT_TEAM_LAYOUT),
requireLayout(eightTeamReset.projection, EIGHT_TEAM_RESET_LAYOUT),
];
assert.ok(countStrictConnectorCrossings(layouts[2].connectors) <= 12);
for (const layout of layouts) {
assert.equal(countCollinearConnectorOverlaps(layout.connectors), 0);
}
});
test("aligns connector endpoints with the A and B entry row centers", () => {
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 intervalsStrictlyOverlap(
firstStart: number,
firstEnd: number,
secondStart: number,
secondEnd: number,
): boolean {
return (
Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) &&
Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd)
);
}
function countStrictConnectorCrossings(routes: readonly ConnectorLayout[]): number {
let crossings = 0;
for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) {
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 labelsBySeriesId(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return Object.fromEntries(
layout.nodes
.map((node) => [node.seriesId, node.label] as const)
.sort(([left], [right]) => left.localeCompare(right)),
);
}
function nodeFor(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
) {
const node = layout.nodes.find((candidate) => candidate.seriesId === id);
assert.ok(node);
return node;
}
function winnerRoutesTo(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
targetSeriesId: SeriesId,
) {
return layout.connectors.filter(
(route) =>
route.kind === "winner" && route.toSeriesId === targetSeriesId,
);
}
function routeFrom(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
id: SeriesId,
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 connectorLayoutKey(connector: ConnectorLayout): string {
return `${connector.fromSeriesId}:${connector.select}:${connector.toSeriesId}:${connector.toSlot}`;
}
function mobileGroupKeys(
layout: NonNullable<ReturnType<typeof createDoubleEliminationBracketLayout>>,
) {
return layout.mobileGroups.map(
(group) => `${group.stage}:${group.roundNumber ?? 0}`,
);
}