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: 40, // Matches the widest focused connector underlay so parallel routes stay legible. connectorRailClearance: 5, cardBorderWidth: SERIES_SCORE_CARD_GEOMETRY.borderWidth, cardHeight: SERIES_SCORE_CARD_GEOMETRY.height, cardHeaderHeight: SERIES_SCORE_CARD_GEOMETRY.headerHeight, cardEntryHeight: SERIES_SCORE_CARD_GEOMETRY.entryHeight, cardGap: 20, upperTop: 64, laneGap: 152, } as const; export interface BracketNodeLayout { seriesId: SeriesId; label: string; accessibleLabel: 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; accessibleLabel: string; } export interface DoubleEliminationBracketConfiguration { teamCount: 4 | 8; resetFinalEnabled: boolean; } export interface BracketRoundLayout { stage: BracketStage; roundNumber: number; label: string; accessibleLabel: string; lane: BracketLane; column: number; x: number; labelY: number; seriesIds: SeriesId[]; } export interface MobileBracketGroup { stage: BracketStage; roundNumber: number; label: string; accessibleLabel: 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; roundBySeriesId: Map; rounds: NormalizedRound[]; rankBySeriesId: Map; } interface NormalizedRound { stage: BracketStage; roundNumber: number; label: string; accessibleLabel: string; seriesIds: SeriesId[]; } interface ConnectorRoute { connector: SeriesConnectorView; key: string; kind: BracketConnectorKind; targetColumn: number; targetNodeY: number; sourceX: number; sourceY: number; targetX: number; targetY: number; } interface SeparateWinnerRailChoice { verticalXs: [number, number]; crossings: number; distanceFromBaseline: number; distanceFromCenter: number; } type OrthogonalSegment = | { orientation: "horizontal"; fixed: number; start: number; end: number } | { orientation: "vertical"; fixed: number; start: number; end: number }; const STAGE_ORDER: Record = { 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, }; // A focused 5px underlay extends 2.5px from its centerline. const CONNECTOR_RAIL_EDGE_INSET = 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 { return formatBracketRoundLabel(stage, roundNumber, "R"); } export function bracketRoundAccessibleLabel( stage: SeriesStageType, roundNumber?: number, ): string { return formatBracketRoundLabel(stage, roundNumber, "라운드"); } function formatBracketRoundLabel( stage: SeriesStageType, roundNumber: number | undefined, roundUnit: "R" | "라운드", ): string { const round = roundNumber ?? 1; switch (stage) { case "upper": return round === 1 ? `브래킷 1${roundUnit}` : `브래킷 상위 ${round}${roundUnit}`; case "lower": return `브래킷 하위 ${round}${roundUnit}`; case "grand-final": return "그랜드 파이널"; case "reset-final": return "리셋 파이널"; case "pair": return "대진"; case "round-robin": return `${round}라운드`; } } 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(); 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(); 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(); 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), accessibleLabel: bracketRoundAccessibleLabel( 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 | null { const indegree = new Map(seriesIds.map((seriesId) => [seriesId, 0])); const outgoing = new Map(seriesIds.map((seriesId) => [seriesId, [] as SeriesId[]])); const targetedSlots = new Set(); 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(); const sourceSelections = new Set(); 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: seriesDisplayName(round, seriesId, round.label), accessibleLabel: seriesDisplayName( round, seriesId, round.accessibleLabel, ), 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, 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, ): BracketConnectorLayout[] | null { const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY; const routes: ConnectorRoute[] = []; const routesByTargetColumn = new Map(); 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 route = { connector, key: connectorKey(connector), kind: connectorKind(connector.from.select), targetColumn: target.column, targetNodeY: target.y, sourceX: source.x + source.width, sourceY: connectorAnchorY(source, connector.from.select), targetX: target.x, targetY: targetSlotY(target, connector.to.slot), } satisfies ConnectorRoute; routes.push(route); const columnRoutes = routesByTargetColumn.get(target.column) ?? []; columnRoutes.push(route); routesByTargetColumn.set(target.column, columnRoutes); } const verticalXByConnector = new Map(); for (const columnRoutes of routesByTargetColumn.values()) { columnRoutes.sort( (left, right) => right.sourceY - left.sourceY || right.targetY - left.targetY || left.key.localeCompare(right.key), ); columnRoutes.forEach(({ key, targetX }, index) => { verticalXByConnector.set( key, targetX - geometry.columnGap + (geometry.columnGap * (index + 1)) / (columnRoutes.length + 1), ); }); } if (!alignWinnerBundleRails(routes, verticalXByConnector)) return null; const result: BracketConnectorLayout[] = []; for (const route of routes) { const { connector, key, kind, sourceX, sourceY, targetX, targetY } = route; const verticalX = verticalXByConnector.get(key); if (verticalX === undefined) return null; 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, "label"), accessibleLabel: connectorLabel(connector, graph, "accessibleLabel"), }); } 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 alignWinnerBundleRails( routes: readonly ConnectorRoute[], verticalXByConnector: Map, ): boolean { const winnersByTarget = new Map(); for (const route of routes) { if (route.kind !== "winner") continue; const winners = winnersByTarget.get(route.connector.to.seriesId) ?? []; winners.push(route); winnersByTarget.set(route.connector.to.seriesId, winners); } const bundles = [...winnersByTarget.values()] .filter( (winners) => winners.length === 2 && winners[0].connector.to.slot !== winners[1].connector.to.slot, ) .sort( (left, right) => left[0].targetColumn - right[0].targetColumn || left[0].targetNodeY - right[0].targetNodeY || left[0].key.localeCompare(right[0].key), ); for (const bundle of bundles) { const preferredX = bundle[0].targetX - DOUBLE_ELIMINATION_BRACKET_GEOMETRY.columnGap / 2; if ( intervalsOverlap( bundle[0].sourceY, bundle[0].targetY, bundle[1].sourceY, bundle[1].targetY, ) ) { const assignment = chooseSeparateWinnerRails( bundle, routes, verticalXByConnector, preferredX, ); if (!assignment) return false; for (const [key, verticalX] of assignment) { verticalXByConnector.set(key, verticalX); } continue; } const verticalX = chooseWinnerBundleRail( bundle, routes, verticalXByConnector, preferredX, ); if (verticalX === null) return false; for (const route of bundle) verticalXByConnector.set(route.key, verticalX); } return true; } function chooseWinnerBundleRail( bundle: readonly ConnectorRoute[], routes: readonly ConnectorRoute[], verticalXByConnector: Map, preferredX: number, ): number | null { const previousRails = bundle.map((route) => verticalXByConnector.get(route.key), ); if (previousRails.some((verticalX) => verticalX === undefined)) return null; const previousScore = connectorConflictScore(routes, verticalXByConnector); // Keep the existing crossing budget, then favor stroke-clear rails nearest center. let best: | { verticalX: number; crossings: number; clearanceConflicts: number; distanceFromCenter: number; } | null = null; for (const candidateX of winnerRailCandidates(preferredX)) { for (const route of bundle) { verticalXByConnector.set(route.key, candidateX); } const score = connectorConflictScore(routes, verticalXByConnector); if ( score.overlaps !== 0 || score.crossings > previousScore.crossings || score.clearanceConflicts > previousScore.clearanceConflicts ) { continue; } const distanceFromCenter = Math.abs(candidateX - preferredX); if ( !best || score.clearanceConflicts < best.clearanceConflicts || (score.clearanceConflicts === best.clearanceConflicts && (score.crossings < best.crossings || (score.crossings === best.crossings && distanceFromCenter < best.distanceFromCenter))) ) { best = { verticalX: candidateX, crossings: score.crossings, clearanceConflicts: score.clearanceConflicts, distanceFromCenter, }; } } if (best) return best.verticalX; bundle.forEach((route, index) => { const previousX = previousRails[index]; if (previousX !== undefined) { verticalXByConnector.set(route.key, previousX); } }); return null; } function winnerRailCandidates(preferredX: number): number[] { const geometry = DOUBLE_ELIMINATION_BRACKET_GEOMETRY; const maximumOffset = geometry.columnGap / 2 - CONNECTOR_RAIL_EDGE_INSET; const candidates = [preferredX]; for (let offset = 1; offset <= maximumOffset; offset += 1) { candidates.push(preferredX - offset, preferredX + offset); } return candidates; } function chooseSeparateWinnerRails( bundle: readonly ConnectorRoute[], routes: readonly ConnectorRoute[], verticalXByConnector: Map, preferredX: number, ): Map | null { const orderedBundle = [...bundle].sort( (left, right) => left.sourceY - right.sourceY || left.targetY - right.targetY || left.key.localeCompare(right.key), ); const previousRails: number[] = []; for (const route of orderedBundle) { const previousX = verticalXByConnector.get(route.key); if (previousX === undefined) return null; previousRails.push(previousX); } const previousScore = connectorConflictScore(routes, verticalXByConnector); const bundleKeys = new Set(orderedBundle.map(({ key }) => key)); const candidates = [ ...new Set([...previousRails, ...winnerRailCandidates(preferredX)]), ]; let best: SeparateWinnerRailChoice | null = null; for (const firstX of candidates) { for (const secondX of candidates) { if (firstX === secondX) continue; verticalXByConnector.set(orderedBundle[0].key, firstX); verticalXByConnector.set(orderedBundle[1].key, secondX); const bundleScore = connectorConflictScore( routes, verticalXByConnector, bundleKeys, ); const score = connectorConflictScore(routes, verticalXByConnector); if ( bundleScore.overlaps !== 0 || bundleScore.clearanceConflicts !== 0 || score.overlaps !== 0 || score.crossings > previousScore.crossings ) { continue; } const distanceFromBaseline = Math.abs(firstX - previousRails[0]) + Math.abs(secondX - previousRails[1]); const distanceFromCenter = Math.abs(firstX - preferredX) + Math.abs(secondX - preferredX); const candidate: SeparateWinnerRailChoice = { verticalXs: [firstX, secondX], crossings: score.crossings, distanceFromBaseline, distanceFromCenter, }; if (!best || compareSeparateWinnerRailChoices(candidate, best) < 0) { best = candidate; } } } orderedBundle.forEach((route, index) => { verticalXByConnector.set(route.key, previousRails[index]); }); if (!best) return null; return new Map( orderedBundle.map((route, index) => [route.key, best.verticalXs[index]]), ); } function compareSeparateWinnerRailChoices( left: SeparateWinnerRailChoice, right: SeparateWinnerRailChoice, ): number { return ( left.crossings - right.crossings || left.distanceFromBaseline - right.distanceFromBaseline || left.distanceFromCenter - right.distanceFromCenter || left.verticalXs[0] - right.verticalXs[0] || left.verticalXs[1] - right.verticalXs[1] ); } function connectorConflictScore( routes: readonly ConnectorRoute[], verticalXByConnector: ReadonlyMap, focusedRouteKeys?: ReadonlySet, ): { crossings: number; overlaps: number; clearanceConflicts: number } { let crossings = 0; let overlaps = 0; let clearanceConflicts = 0; for (let leftIndex = 0; leftIndex < routes.length; leftIndex += 1) { const leftX = verticalXByConnector.get(routes[leftIndex].key); if (leftX === undefined) continue; const leftSegments = connectorRouteSegments(routes[leftIndex], leftX); for ( let rightIndex = leftIndex + 1; rightIndex < routes.length; rightIndex += 1 ) { if ( focusedRouteKeys && !focusedRouteKeys.has(routes[leftIndex].key) && !focusedRouteKeys.has(routes[rightIndex].key) ) { continue; } const rightX = verticalXByConnector.get(routes[rightIndex].key); if (rightX === undefined) continue; const rightSegments = connectorRouteSegments(routes[rightIndex], rightX); for (const left of leftSegments) { for (const right of rightSegments) { if (left.orientation === right.orientation) { const overlapLength = Math.min(left.end, right.end) - Math.max(left.start, right.start); if (left.fixed === right.fixed && overlapLength > 0) { overlaps += 1; } else if ( left.orientation === "vertical" && overlapLength > 0 && Math.abs(left.fixed - right.fixed) < DOUBLE_ELIMINATION_BRACKET_GEOMETRY.connectorRailClearance ) { clearanceConflicts += 1; } continue; } const horizontal = left.orientation === "horizontal" ? left : right; const vertical = left.orientation === "vertical" ? left : right; if ( vertical.fixed > horizontal.start && vertical.fixed < horizontal.end && horizontal.fixed > vertical.start && horizontal.fixed < vertical.end ) { crossings += 1; } } } } } return { crossings, overlaps, clearanceConflicts }; } function connectorRouteSegments( route: ConnectorRoute, verticalX: number, ): OrthogonalSegment[] { return [ orthogonalSegment("horizontal", route.sourceY, route.sourceX, verticalX), orthogonalSegment("vertical", verticalX, route.sourceY, route.targetY), orthogonalSegment("horizontal", route.targetY, verticalX, route.targetX), ]; } function orthogonalSegment( orientation: OrthogonalSegment["orientation"], fixed: number, first: number, second: number, ): OrthogonalSegment { return { orientation, fixed, start: Math.min(first, second), end: Math.max(first, second), }; } function intervalsOverlap( firstStart: number, firstEnd: number, secondStart: number, secondEnd: number, ): boolean { return ( Math.min(firstStart, firstEnd) < Math.max(secondStart, secondEnd) && Math.min(secondStart, secondEnd) < Math.max(firstStart, firstEnd) ); } function connectorLabel( connector: SeriesConnectorView, graph: ValidatedGraph, labelKey: "label" | "accessibleLabel", ): string { const sourceRound = graph.roundBySeriesId.get(connector.from.seriesId); const targetRound = graph.roundBySeriesId.get(connector.to.seriesId); const sourceName = seriesDisplayName( sourceRound, connector.from.seriesId, sourceRound?.[labelKey], ); const targetName = seriesDisplayName( targetRound, connector.to.seriesId, targetRound?.[labelKey], ); 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 seriesDisplayName( round: NormalizedRound | undefined, seriesId: SeriesId, roundLabel: string | undefined, ): string { if (!round || !roundLabel) return "알 수 없는 경기"; const index = round.seriesIds.indexOf(seriesId); return round.seriesIds.length > 1 ? `${roundLabel} · ${index + 1}경기` : roundLabel; } 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); }