@ethlete/components 1.0.0-next.119 → 1.0.0-next.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"ethlete-components-bracket.mjs","names":["createNothingToOneRelation","createTwoToOneRelation","createTwoToNothingRelation"],"sources":["../../../../libs/components/bracket/lib/bracket-errors.ts","../../../../libs/components/bracket/lib/bracket-runtime-error.ts","../../../../libs/components/bracket/lib/core/bracket-map.ts","../../../../libs/components/bracket/lib/core/layout.ts","../../../../libs/components/bracket/lib/core/tournament.ts","../../../../libs/components/bracket/lib/core/round.ts","../../../../libs/components/bracket/lib/core/match-participant.ts","../../../../libs/components/bracket/lib/core/match.ts","../../../../libs/components/bracket/lib/core/participant.ts","../../../../libs/components/bracket/lib/core/bracket.ts","../../../../libs/components/bracket/lib/drawing/path.ts","../../../../libs/components/bracket/lib/drawing/curve.ts","../../../../libs/components/bracket/lib/drawing/grid/types.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-element-part.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-element.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-finalizer.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-grid.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-master-column.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-master-column-section.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-sub-column.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-continue-master-column.ts","../../../../libs/components/bracket/lib/drawing/line.ts","../../../../libs/components/bracket/lib/drawing/draw-man.ts","../../../../libs/components/bracket/lib/drawing/draw-man-swiss.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination-utils.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-sub-column-relative-to-first-round.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-folded-third-place-section.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-gap-master-column.ts","../../../../libs/components/bracket/lib/drawing/grid/row-span.ts","../../../../libs/components/bracket/lib/drawing/grid/single-elimination.ts","../../../../libs/components/bracket/lib/drawing/grid/sections.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination-stacked.ts","../../../../libs/components/bracket/lib/linked/match-relations.ts","../../../../libs/components/bracket/lib/linked/round-relations.ts","../../../../libs/components/bracket/lib/linked/bracket.ts","../../../../libs/components/bracket/lib/linked/resolve-bracket-slot.ts","../../../../libs/components/bracket/lib/linked/migrate-bracket-picks.ts","../../../../libs/components/bracket/lib/linked/swiss.ts","../../../../libs/components/bracket/lib/linked/standing-rank-sides.ts","../../../../libs/components/bracket/lib/linked/validate-bracket-source.ts","../../../../libs/components/bracket/lib/drawing/grid/swiss.ts","../../../../libs/components/bracket/lib/integrations/bracket-slot.ts","../../../../libs/components/bracket/lib/layout-registry.ts","../../../../libs/components/bracket/lib/placeholder-source.ts","../../../../libs/components/bracket/lib/standings/standing-pick.ts","../../../../libs/components/bracket/lib/standings/standing-pick-order.ts","../../../../libs/components/bracket/lib/standings/swap-standing-rank.ts"],"sourcesContent":["export const BRACKET_ERROR_CODES = {\n /** The source has no rounds/matches to render. */\n SOURCE_EMPTY: 3401,\n /** An integration received a tournament mode it does not support. */\n MODE_UNSUPPORTED: 3402,\n /** Two rounds in the source share an id. */\n DUPLICATE_ROUND: 3403,\n /** Two matches in the source share an id. */\n DUPLICATE_MATCH: 3404,\n /** A round-to-round relation could not be resolved (malformed round structure). */\n ROUND_RELATION_INVALID: 3405,\n /** A match-to-match relation could not be resolved (match counts don't line up). */\n MATCH_RELATION_INVALID: 3406,\n /** The computed layout grid is in an inconsistent state. */\n GRID_INVALID: 3407,\n /** Swiss groups could not be generated from the source. */\n SWISS_GROUPING_FAILED: 3408,\n /** A Swiss group ended up without any matches while headers are enabled. */\n SWISS_GROUP_EMPTY: 3409,\n /** A match's resolved winner id is not among its participants. */\n WINNER_NOT_FOUND: 3410,\n /** A required key was missing from an internal bracket lookup map. */\n DATA_LOOKUP_FAILED: 3411,\n /** The default cards are rendering but no `matchNormalizer` was registered to feed them. */\n MISSING_MATCH_NORMALIZER: 3412,\n /** No registered {@link BracketLayout} matches the source's tournament `mode`. */\n LAYOUT_NOT_REGISTERED: 3413,\n /** A cell the bracket draws has no card - neither an input, the layout, nor the config names one. */\n CARD_NOT_REGISTERED: 3414,\n /** `createPlaceholderBracketSource` got an invalid participant or round count for its mode. */\n PLACEHOLDER_SHAPE_INVALID: 3415,\n} as const;\n","/**\n * The error every `@ethlete/components/bracket` engine function throws for a malformed source. `code` is one of\n * {@link BRACKET_ERROR_CODES}; the message starts with `ET<code>: `.\n */\nexport class BracketRuntimeError extends Error {\n public readonly code: number;\n\n constructor(code: number, message: string) {\n super(`ET${code}: ${message}`);\n this.name = 'BracketRuntimeError';\n this.code = code;\n }\n}\n","import { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\nexport class BracketMap<TKey, TValue> extends Map<TKey, TValue> {\n constructor() {\n super();\n }\n\n getOrThrow(key: TKey): TValue {\n const value = super.get(key);\n\n if (value === undefined) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.DATA_LOOKUP_FAILED,\n `Value for key ${key} not found in bracket map`,\n );\n }\n\n return value;\n }\n\n first(): TValue | undefined {\n return this.values().next().value;\n }\n\n last(): TValue | undefined {\n const values = Array.from(this.values());\n return values.length > 0 ? values[values.length - 1] : undefined;\n }\n}\n","export const BRACKET_DATA_LAYOUT = {\n LEFT_TO_RIGHT: 'left-to-right',\n\n /**\n * Folded in half: each round up to the first one too small to halve is drawn twice, once on each\n * side, converging on that round and the ones after it. Halves the height and roughly doubles the\n * width, which is what a poster or a broadcast graphic wants.\n *\n * Carried by the mirrored layout factories - a layout that has no fold to make (swiss) simply has no\n * mirrored variant.\n */\n MIRRORED: 'mirrored',\n} as const;\n\nexport type BracketDataLayout = (typeof BRACKET_DATA_LAYOUT)[keyof typeof BRACKET_DATA_LAYOUT];\n","export const TOURNAMENT_MODE = {\n SINGLE_ELIMINATION: 'single-elimination',\n DOUBLE_ELIMINATION: 'double-elimination',\n SWISS_WITH_ELIMINATION: 'swiss-with-elimination',\n SWISS: 'swiss',\n} as const;\n\nexport type TournamentMode = (typeof TOURNAMENT_MODE)[keyof typeof TOURNAMENT_MODE];\n\n/** Whether a stage is drawn as swiss record groups: `'swiss-with-elimination'` or `'swiss'`, which eliminates nobody. */\nexport const isSwissMode = (mode: TournamentMode) =>\n mode === TOURNAMENT_MODE.SWISS_WITH_ELIMINATION || mode === TOURNAMENT_MODE.SWISS;\n\n/** Wins that advance a participant out of a swiss stage. */\nexport const SWISS_ADVANCE_WINS = 3;\n\n/** Losses that eliminate a participant from a swiss stage. */\nexport const SWISS_ELIMINATE_LOSSES = 3;\n","import { BracketDataSource } from '../integrations';\nimport { GenerateBracketDataOptions } from './bracket';\nimport { BracketMap } from './bracket-map';\nimport { BRACKET_DATA_LAYOUT } from './layout';\nimport { BracketMatchId } from './match';\nimport { TOURNAMENT_MODE } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketRoundId = string & { _brand: 'BracketRoundId' };\nexport type BracketRoundShortId = string & { _brand: 'BracketRoundShortId' };\nexport type BracketRoundPosition = number & { _brand: 'BracketRoundPosition' };\nexport type BracketRoundMirrorType = (typeof BRACKET_ROUND_MIRROR_TYPE)[keyof typeof BRACKET_ROUND_MIRROR_TYPE];\n\nexport const BRACKET_ROUND_MIRROR_TYPE = {\n LEFT: 'left',\n RIGHT: 'right',\n} as const;\n\nexport const COMMON_BRACKET_ROUND_TYPE = {\n THIRD_PLACE: 'third-place',\n FINAL: 'final',\n} as const;\n\nexport const SINGLE_ELIMINATION_BRACKET_ROUND_TYPE = {\n SINGLE_ELIMINATION_BRACKET: 'single-elimination-bracket',\n} as const;\n\nexport const DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE = {\n UPPER_BRACKET: 'upper-bracket',\n LOWER_BRACKET: 'lower-bracket',\n REVERSE_FINAL: 'reverse-final',\n} as const;\n\nexport const SWISS_BRACKET_ROUND_TYPE = {\n SWISS: 'swiss',\n} as const;\n\nexport const GROUP_BRACKET_ROUND_TYPE = {\n GROUP: 'group',\n} as const;\n\nexport type CommonBracketRoundType = (typeof COMMON_BRACKET_ROUND_TYPE)[keyof typeof COMMON_BRACKET_ROUND_TYPE];\nexport type SingleEliminationBracketRoundType =\n | CommonBracketRoundType\n | (typeof SINGLE_ELIMINATION_BRACKET_ROUND_TYPE)[keyof typeof SINGLE_ELIMINATION_BRACKET_ROUND_TYPE];\nexport type DoubleEliminationBracketRoundType =\n | CommonBracketRoundType\n | (typeof DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE)[keyof typeof DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE];\nexport type SwissBracketRoundType = (typeof SWISS_BRACKET_ROUND_TYPE)[keyof typeof SWISS_BRACKET_ROUND_TYPE];\nexport type GroupBracketRoundType = (typeof GROUP_BRACKET_ROUND_TYPE)[keyof typeof GROUP_BRACKET_ROUND_TYPE];\n\nexport type BracketRoundType =\n SingleEliminationBracketRoundType | DoubleEliminationBracketRoundType | SwissBracketRoundType | GroupBracketRoundType;\n\nexport const TERMINAL_ROUND_SORT_PRIORITY: Partial<Record<string, number>> = {\n final: 1,\n 'reverse-final': 2,\n 'third-place': 3,\n};\n\nexport type BracketRoundBase<TRoundData> = {\n /**\n * How deep this round sits in its own bracket - 0 for the opening round, counted separately for the\n * upper and lower halves of a double elimination.\n *\n * **Both halves of a mirrored round share it.** That is what makes it the fold's coordinate: a\n * mirrored layout draws each depth twice, once on each side, so the depth is the only thing that says\n * which right-hand column belongs opposite which left-hand one.\n */\n logicalIndex: number;\n type: BracketRoundType;\n id: BracketRoundId;\n shortId: BracketRoundShortId;\n data: TRoundData;\n position: BracketRoundPosition;\n name: string;\n matchCount: number;\n mirrorRoundType: BracketRoundMirrorType | null;\n isFirstRound: boolean;\n isLastRound: boolean;\n isFirstOfType: boolean;\n isLastOfType: boolean;\n};\n\nexport type BracketRoundWithRelationsBase<TRoundData> = BracketRoundBase<TRoundData> & {\n matchIds: BracketMatchId[];\n};\n\nexport const createRoundsMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: GenerateBracketDataOptions,\n) => {\n const map = new BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>();\n\n const shouldSplitRoundsInTwo = options.layout === BRACKET_DATA_LAYOUT.MIRRORED;\n const isDoubleElimination = source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION;\n\n let currentUpperBracketIndex = 0;\n let currentLowerBracketIndex = 0;\n\n // A fold converges once, on the first round it cannot halve, and every later round stays whole -\n // otherwise a bye (`[6, 3, 2, 1]`) reopens the fold past its middle and draws a round on both sides\n // of one that has no side. Tracked per bracket half, because the two converge separately.\n const foldClosed = { upper: false, lower: false };\n\n const splitRoundsRest: BracketRoundWithRelationsBase<TRoundData>[] = [];\n\n const orderedRounds = [...source.rounds].sort(\n (a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0),\n );\n\n for (const [roundIndex, round] of orderedRounds.entries()) {\n const isUpperBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET;\n const isLowerBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET;\n const isCommonDoubleEliminationRound = !isUpperBracket && !isLowerBracket && isDoubleElimination;\n\n const matches = source.matches.filter((m) => m.roundId === round.id);\n const roundId = round.id as BracketRoundId;\n const foldSide = isLowerBracket || isCommonDoubleEliminationRound ? 'lower' : 'upper';\n const canHalveRound = matches.length >= 2 && matches.length % 2 === 0;\n const shouldSplitRound = shouldSplitRoundsInTwo && canHalveRound && !foldClosed[foldSide];\n\n if (!canHalveRound) foldClosed[foldSide] = true;\n\n const isFirstRound = roundIndex === 0;\n const isLastRound = roundIndex === orderedRounds.length - 1;\n\n const isFirstOfType = orderedRounds.findIndex((r) => r.type === round.type) === roundIndex;\n const isLastOfType =\n orderedRounds\n .slice()\n .reverse()\n .findIndex((r) => r.type === round.type) ===\n orderedRounds.length - roundIndex - 1;\n\n const depth =\n isLowerBracket || isCommonDoubleEliminationRound ? currentLowerBracketIndex : currentUpperBracketIndex;\n\n if (shouldSplitRound) {\n const firstHalfRoundId = `${roundId}--half-1` as BracketRoundId;\n const secondHalfRoundId = `${roundId}--half-2` as BracketRoundId;\n const firstHalfMatchesMaxIndex = matches.length / 2 - 1;\n\n // Both halves are the same round at the same depth, drawn on either side of the fold - so they\n // carry the same `logicalIndex`, which is what pairs a right-hand column with its left-hand twin.\n const halfBase = {\n type: round.type,\n logicalIndex: depth,\n data: round.data,\n position: (depth + 1) as BracketRoundPosition,\n name: round.name,\n matchCount: matches.length / 2,\n isFirstRound,\n isLastRound,\n isFirstOfType,\n isLastOfType,\n };\n\n const bracketRoundFirstHalf: BracketRoundWithRelationsBase<TRoundData> = {\n ...halfBase,\n id: firstHalfRoundId,\n shortId: `${roundIndex}-left` as BracketRoundShortId,\n matchIds: matches.slice(0, firstHalfMatchesMaxIndex + 1).map((m) => m.id as BracketMatchId),\n mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.LEFT,\n };\n\n const bracketRoundSecondHalf: BracketRoundWithRelationsBase<TRoundData> = {\n ...halfBase,\n id: secondHalfRoundId,\n shortId: `${roundIndex}-right` as BracketRoundShortId,\n matchIds: matches.slice(firstHalfMatchesMaxIndex + 1).map((m) => m.id as BracketMatchId),\n mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.RIGHT,\n };\n\n map.set(firstHalfRoundId, bracketRoundFirstHalf);\n\n splitRoundsRest.unshift(bracketRoundSecondHalf);\n } else {\n const bracketRound: BracketRoundWithRelationsBase<TRoundData> = {\n type: round.type,\n id: roundId,\n shortId: `${roundIndex}` as BracketRoundShortId,\n logicalIndex: depth,\n data: round.data,\n position: (depth + 1) as BracketRoundPosition,\n name: round.name,\n matchCount: matches.length,\n matchIds: matches.map((m) => m.id as BracketMatchId),\n mirrorRoundType: null,\n isFirstRound,\n isLastRound,\n isFirstOfType,\n isLastOfType,\n };\n\n map.set(roundId, bracketRound);\n }\n\n if (isLowerBracket || isCommonDoubleEliminationRound) {\n currentLowerBracketIndex++;\n } else {\n currentUpperBracketIndex++;\n }\n }\n\n // The right halves close the map, deepest first, so walking it in order walks the fold: out along the\n // left side, through the rounds too small to halve, and back along the right. `splitRoundsRest` was\n // built by unshifting, so it is already in that order - and each half keeps the depth of its twin\n // rather than being renumbered past the last round, which is what lets a builder pair the two sides.\n if (splitRoundsRest.length) {\n if (!map.last()) throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, 'Last round not found');\n\n for (const splitRound of splitRoundsRest) {\n map.set(splitRound.id, splitRound);\n }\n }\n\n return map;\n};\n","import { BracketDataSource, BracketMatchSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketMatchId } from './match';\nimport { MatchParticipantId, BracketParticipantBase, BracketParticipantWithRelationsBase } from './participant';\nimport {\n BracketRoundId,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n BracketRoundWithRelationsBase,\n} from './round';\nimport { SWISS_ELIMINATE_LOSSES, TOURNAMENT_MODE } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type ParticipantMatchResult = 'win' | 'loss' | 'tie';\nexport type MatchParticipantSide = 'home' | 'away';\n\nexport type BracketMatchParticipantBase = BracketParticipantBase & {\n result: ParticipantMatchResult | null;\n isEliminated: boolean;\n isEliminationMatch: boolean;\n tieCount: number;\n winCount: number;\n lossCount: number;\n side: MatchParticipantSide;\n};\n\nexport type BracketMatchParticipantWithRelationsBase = BracketMatchParticipantBase &\n BracketParticipantWithRelationsBase;\n\nconst thirdPlaceFeederRoundId = <TRoundData, TMatchData>(source: BracketDataSource<TRoundData, TMatchData>) => {\n if (!source.rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)) return null;\n\n const chain = source.rounds.filter((round) => round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE);\n const finalIndex = chain.findIndex((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL);\n\n return finalIndex > 0 ? (chain[finalIndex - 1]?.id ?? null) : null;\n};\n\nexport const createNewMatchParticipantBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n participantId: MatchParticipantId | null,\n match: BracketMatchSource<TMatchData>,\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>,\n matchRoundId: BracketRoundId,\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>,\n sourceMatchesById?: ReadonlyMap<string, BracketMatchSource<TMatchData>>,\n // eslint-disable-next-line max-params -- builder maps one source participant to a bracket node; its lookups are distinct positional inputs\n) => {\n if (!participantId) return null;\n\n const findSourceMatch = (matchId: string | undefined) =>\n matchId === undefined\n ? undefined\n : sourceMatchesById\n ? sourceMatchesById.get(matchId)\n : source.matches.find((m) => m.id === matchId);\n\n const participantBase = participants.getOrThrow(participantId);\n const roundBase = rounds.getOrThrow(matchRoundId as BracketRoundId);\n\n const matchIndex = participantBase.matchIds.indexOf(match.id as BracketMatchId);\n if (matchIndex === -1)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match with id ${match.id} not found in participant with id ${participantId}`,\n );\n\n const participantSide = match.home === participantId ? 'home' : 'away';\n const isWinner = match.winner === participantSide;\n const isLooser = match.winner && match.winner !== participantSide;\n const isTie = match.status === 'completed' && !match.winner;\n\n let winsTilNow = isWinner ? 1 : 0;\n let lossesTilNow = isLooser ? 1 : 0;\n let tiesTilNow = isTie ? 1 : 0;\n\n for (let i = 0; i < matchIndex; i++) {\n const previousMatchId = participantBase.matchIds[i];\n const previousMatch = findSourceMatch(previousMatchId);\n const myPreviousMatchSide =\n previousMatch?.home === participantId ? 'home' : previousMatch?.away === participantId ? 'away' : null;\n\n if (!previousMatch || !myPreviousMatchSide) continue;\n\n const previousIsWinner = previousMatch.winner === myPreviousMatchSide;\n const previousIsLooser = previousMatch.winner && previousMatch.winner !== myPreviousMatchSide;\n const previousIsTie = previousMatch.status === 'completed' && !previousMatch.winner;\n\n if (previousIsWinner) {\n winsTilNow++;\n } else if (previousIsLooser) {\n lossesTilNow++;\n } else if (previousIsTie) {\n tiesTilNow++;\n }\n }\n\n const hasElimination =\n source.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION ||\n source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION ||\n source.mode === TOURNAMENT_MODE.SWISS_WITH_ELIMINATION;\n\n let isEliminated = false;\n let isEliminationMatch = false;\n\n if (hasElimination) {\n switch (source.mode) {\n case TOURNAMENT_MODE.SINGLE_ELIMINATION: {\n isEliminationMatch = match.roundId !== thirdPlaceFeederRoundId(source);\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n break;\n }\n case TOURNAMENT_MODE.DOUBLE_ELIMINATION: {\n isEliminationMatch =\n roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET ||\n roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL ||\n roundBase.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE;\n\n // Final is only an elimination match if there is no reverse final or there is one and this participant came from the lower bracket\n if (roundBase.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {\n const hasReverseFinal = source.rounds.some(\n (r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL,\n );\n\n if (!hasReverseFinal) {\n isEliminationMatch = true;\n isEliminated = isLooser ?? false;\n break;\n }\n\n isEliminationMatch = participantBase.matchIds.some((matchId) => {\n const playedMatch = findSourceMatch(matchId);\n\n return (\n !!playedMatch &&\n source.rounds.find((round) => round.id === playedMatch.roundId)?.type ===\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET\n );\n });\n }\n\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n break;\n }\n case TOURNAMENT_MODE.SWISS_WITH_ELIMINATION: {\n // `lossesTilNow` counts this match too, so the losses carried *into* it are one fewer for a\n // loser - it is those that decide whether losing here is what puts the participant out.\n const priorLosses = lossesTilNow - (isLooser ? 1 : 0);\n\n isEliminationMatch = priorLosses >= SWISS_ELIMINATE_LOSSES - 1;\n\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n }\n }\n }\n\n const matchParticipantBase: BracketMatchParticipantWithRelationsBase = {\n ...participantBase,\n isEliminated,\n isEliminationMatch,\n lossCount: lossesTilNow,\n tieCount: tiesTilNow,\n winCount: winsTilNow,\n result: isWinner ? 'win' : isLooser ? 'loss' : isTie ? 'tie' : null,\n side: participantSide,\n };\n\n return matchParticipantBase;\n};\n","import { BracketDataSource, BracketSlotSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport {\n MatchParticipantSide,\n BracketMatchParticipantWithRelationsBase,\n createNewMatchParticipantBase,\n} from './match-participant';\nimport { MatchParticipantId, BracketParticipantWithRelationsBase } from './participant';\nimport { BracketRoundId, BracketRoundWithRelationsBase } from './round';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketMatchId = string & { _brand: 'BracketMatchId' };\nexport type BracketMatchShortId = string & { _brand: 'BracketMatchShortId' };\nexport type BracketMatchPosition = number & { _brand: 'BracketMatchPosition' };\n\nexport type BracketMatchStatus = 'completed' | 'pending';\n\nexport type BracketMatchBase<TMatchData> = {\n data: TMatchData;\n indexInRound: number;\n id: BracketMatchId;\n shortId: BracketMatchShortId;\n position: BracketMatchPosition;\n winnerSide: MatchParticipantSide | null;\n status: BracketMatchStatus;\n homeSource: BracketSlotSource | null;\n awaySource: BracketSlotSource | null;\n};\n\nexport type BracketMatchWithRelationsBase<TMatchData> = BracketMatchBase<TMatchData> & {\n roundId: BracketRoundId;\n home: BracketMatchParticipantWithRelationsBase | null;\n away: BracketMatchParticipantWithRelationsBase | null;\n winner: BracketMatchParticipantWithRelationsBase | null;\n};\n\nexport const createMatchesMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>,\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>,\n // eslint-disable-next-line max-params -- builder threads the source plus its round and participant lookup maps\n) => {\n const map: BracketMap<BracketMatchId, BracketMatchWithRelationsBase<TMatchData>> = new BracketMap();\n const sourceMatchesById = new Map(source.matches.map((match) => [match.id, match]));\n\n for (const match of source.matches) {\n const genericRound = rounds.get(match.roundId as BracketRoundId);\n const splitRound = rounds.get(`${match.roundId}--half-1` as BracketRoundId);\n const splitRound2 = rounds.get(`${match.roundId}--half-2` as BracketRoundId);\n\n const genericRoundMatchIndex = genericRound?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n const splitRoundMatchIndex = splitRound?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n const splitRound2MatchIndex = splitRound2?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n\n const roundToUse =\n genericRoundMatchIndex !== -1\n ? genericRound\n : splitRoundMatchIndex !== -1\n ? splitRound\n : splitRound2MatchIndex !== -1\n ? splitRound2\n : null;\n\n if (!roundToUse)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match \"${match.id}\" names round \"${match.roundId}\", which is not in source.rounds (known: ${source.rounds.map((round) => round.id).join(', ')})`,\n );\n\n const indexInRound =\n genericRoundMatchIndex !== -1\n ? genericRoundMatchIndex\n : splitRoundMatchIndex !== -1\n ? splitRoundMatchIndex\n : splitRound2MatchIndex !== -1\n ? splitRound2MatchIndex\n : -1;\n\n if (indexInRound === -1)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match with id ${match.id} not found in round with id ${roundToUse.id}`,\n );\n\n const home = createNewMatchParticipantBase(\n source,\n match.home as MatchParticipantId | null,\n match,\n rounds,\n roundToUse.id,\n participants,\n sourceMatchesById,\n );\n const away = createNewMatchParticipantBase(\n source,\n match.away as MatchParticipantId | null,\n match,\n rounds,\n roundToUse.id,\n participants,\n sourceMatchesById,\n );\n const winner = match.winner === 'home' ? home : match.winner === 'away' ? away : null;\n\n const matchBase: BracketMatchWithRelationsBase<TMatchData> = {\n home,\n away,\n data: match.data,\n shortId: `${roundToUse.shortId}-${indexInRound}` as BracketMatchShortId,\n id: match.id as BracketMatchId,\n indexInRound,\n position: (indexInRound + 1) as BracketMatchPosition,\n roundId: roundToUse?.id,\n status: match.status,\n homeSource: match.homeSource ?? null,\n awaySource: match.awaySource ?? null,\n winner,\n winnerSide: match.winner,\n };\n\n map.set(matchBase.id, matchBase);\n }\n\n return map;\n};\n","import { BracketDataSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketMatchId } from './match';\n\nexport type MatchParticipantId = string & { _brand: 'MatchParticipantId' };\nexport type MatchParticipantShortId = string & { _brand: 'MatchParticipantShortId' };\n\nexport type BracketParticipantBase = {\n id: MatchParticipantId;\n shortId: MatchParticipantShortId;\n};\n\nexport type BracketParticipantWithRelationsBase = BracketParticipantBase & {\n matchIds: BracketMatchId[];\n};\n\nexport const createParticipantsMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n) => {\n const map: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase> = new BracketMap();\n\n const participantIds = source.matches\n .map((m) => [m.home, m.away])\n .flat()\n .filter((p) => !!p) as MatchParticipantId[];\n\n const matchIdsByParticipant = new Map<string, BracketMatchId[]>();\n\n for (const match of source.matches) {\n for (const participantId of new Set([match.home, match.away])) {\n if (!participantId) continue;\n\n const matchIds = matchIdsByParticipant.get(participantId) ?? [];\n\n matchIds.push(match.id as BracketMatchId);\n matchIdsByParticipant.set(participantId, matchIds);\n }\n }\n\n for (const [index, participantId] of participantIds.entries()) {\n const participantBase: BracketParticipantWithRelationsBase = {\n id: participantId as MatchParticipantId,\n shortId: `p${index}` as MatchParticipantShortId,\n matchIds: matchIdsByParticipant.get(participantId) ?? [],\n };\n\n map.set(participantId, participantBase);\n }\n\n return map;\n};\n","import { BracketDataSource, BracketMatchSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketDataLayout } from './layout';\nimport { BracketMatchId, BracketMatchWithRelationsBase, createMatchesMapBase } from './match';\nimport { BracketParticipantWithRelationsBase, createParticipantsMapBase, MatchParticipantId } from './participant';\nimport {\n BracketRoundId,\n BracketRoundWithRelationsBase,\n createRoundsMapBase,\n TERMINAL_ROUND_SORT_PRIORITY,\n} from './round';\nimport { TournamentMode } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketBase<TRoundData, TMatchData> = {\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>;\n matches: BracketMap<BracketMatchId, BracketMatchWithRelationsBase<TMatchData>>;\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>;\n mode: TournamentMode;\n};\n\nexport type GenerateBracketDataOptions = {\n layout: BracketDataLayout;\n};\n\n/**\n * Something in a source `createBracket` accepted but probably did not mean: a feeder id that names no\n * match, or a match the declared graph links to nothing because it carries no provenance.\n */\nexport type BracketWarning =\n | { type: 'unknown-feeder'; matchId: string; feederId: string; message: string }\n | { type: 'unlinked-match'; matchId: string; message: string };\n\nexport type CreateBracketOptions<TMatchData> = GenerateBracketDataOptions & {\n /** The matches feeding this one, upper arm first. Slot provenance is used when omitted. */\n previousMatchIds?: (match: BracketMatchSource<TMatchData>) => string[];\n /** Called once per {@link BracketWarning} while the bracket is linked from a declared graph. */\n onWarning?: (warning: BracketWarning) => void;\n};\n\nconst sortSourceMatchesByRoundOrder = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n): BracketDataSource<TRoundData, TMatchData> => {\n const orderedRoundIds = [...source.rounds]\n .sort((a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0))\n .map((r) => r.id);\n\n const roundIndexMap = new Map(orderedRoundIds.map((id, i) => [id, i]));\n\n const sortedMatches = [...source.matches].sort(\n (a, b) => (roundIndexMap.get(a.roundId) ?? 0) - (roundIndexMap.get(b.roundId) ?? 0),\n );\n\n return { ...source, matches: sortedMatches };\n};\n\nconst assertUniqueIds = (options: { ids: string[]; code: number; kind: string }) => {\n const seen = new Set<string>();\n\n for (const id of options.ids) {\n if (seen.has(id)) {\n throw new BracketRuntimeError(options.code, `${options.kind} with id ${id} exists more than once in the source.`);\n }\n\n seen.add(id);\n }\n};\n\nexport const createBracketBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: GenerateBracketDataOptions,\n) => {\n assertUniqueIds({\n ids: source.rounds.map((round) => round.id),\n code: BRACKET_ERROR_CODES.DUPLICATE_ROUND,\n kind: 'Round',\n });\n assertUniqueIds({\n ids: source.matches.map((match) => match.id),\n code: BRACKET_ERROR_CODES.DUPLICATE_MATCH,\n kind: 'Match',\n });\n\n const normalizedSource = sortSourceMatchesByRoundOrder(source);\n\n const participants = createParticipantsMapBase(normalizedSource);\n const rounds = createRoundsMapBase(normalizedSource, options);\n const matches = createMatchesMapBase(normalizedSource, rounds, participants);\n\n const bracketData: BracketBase<TRoundData, TMatchData> = {\n matches,\n rounds,\n participants,\n mode: source.mode,\n };\n\n return bracketData;\n};\n","import { BracketEdge } from './shapes';\n\nexport type PathOptions = {\n /** Unique within one drawing - see {@link BracketEdge.id}. */\n id: string;\n width: number;\n dashArray: number;\n dashOffset: number;\n className: string;\n stroke?: string;\n};\n\nexport const path = (d: string, options: PathOptions): BracketEdge => {\n const commands = d.replace(/\\s+/g, ' ').trim();\n\n return {\n id: options.id,\n d: commands,\n cssPath: `path(\"${commands}\")`,\n cssClass: options.className,\n strokeWidth: options.width,\n dashArray: options.dashArray,\n dashOffset: options.dashOffset,\n stroke: options.stroke ?? 'currentColor',\n };\n};\n","import { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\n\nexport type CurveOptions = {\n lineStartingCurveAmount: number;\n lineEndingCurveAmount: number;\n path: PathOptions;\n inverted?: boolean;\n /**\n * Where the vertical part of the connector sits, in px from the feeding card. `null` or omitted turns\n * it at the middle of the gap.\n */\n turnOffset?: number | null;\n};\n\nexport const curvePath = (\n from: BracketPosition,\n to: BracketPosition,\n direction: 'up' | 'down',\n options: CurveOptions,\n // eslint-disable-next-line max-params -- geometry helper: (from, to, direction, options) reads naturally positional\n) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.end : to.inline.start;\n const fromBlock = from.block.center;\n const toBlock = to.block.center;\n\n // Both bends have to fit inside the block and the inline distance between the two cards, or the line\n // turns past its target and comes back. Scaling them down instead - to nothing, for two cards on the\n // same row - is also what keeps the six commands below identical for every connector: a CSS `d`\n // transition interpolates only between two paths of the same shape.\n const requestedCurve = options.lineStartingCurveAmount + options.lineEndingCurveAmount;\n const totalInline = Math.abs(toInline - fromInline);\n const room = Math.min(Math.abs(toBlock - fromBlock), totalInline);\n const curveScale = requestedCurve > room ? room / requestedCurve : 1;\n\n const startCurve = options.lineStartingCurveAmount * curveScale;\n const endCurve = options.lineEndingCurveAmount * curveScale;\n const straightTotal = totalInline - startCurve - endCurve;\n const turnOffset = options.turnOffset ?? null;\n const leadingStraight =\n turnOffset === null ? straightTotal / 2 : Math.max(0, Math.min(turnOffset - startCurve, straightTotal));\n const trailingStraight = straightTotal - leadingStraight;\n\n const straightEnd = inverted ? fromInline - leadingStraight : fromInline + leadingStraight;\n const straightStart = inverted ? toInline + trailingStraight : toInline - trailingStraight;\n\n const firstCurveEndX = inverted ? straightEnd - startCurve : straightEnd + startCurve;\n const firstCurveEndY = direction === 'down' ? fromBlock + startCurve : fromBlock - startCurve;\n\n const secondCurveStartY = direction === 'down' ? toBlock - endCurve : toBlock + endCurve;\n const secondCurveEndX = straightStart;\n const secondCurveEndY = toBlock;\n const secondCurveBezierX = inverted ? straightStart + endCurve : straightStart - endCurve;\n\n const d = [\n `M ${fromInline} ${fromBlock}`,\n `H ${straightEnd}`,\n `Q ${firstCurveEndX} ${fromBlock}, ${firstCurveEndX} ${firstCurveEndY}`,\n `V ${secondCurveStartY}`,\n `Q ${secondCurveBezierX} ${toBlock}, ${secondCurveEndX} ${secondCurveEndY}`,\n `H ${toInline}`,\n ].join(' ');\n\n return path(d, options.path);\n};\n","import { BracketDataLayout } from '../../core';\nimport { FinalizedBracketColumn, FinalizedBracketMatchElementMap, MutableBracketGrid } from './core';\nimport { BracketGridSection } from './sections';\n\nexport type ComputedBracketGrid<TRoundData, TMatchData> = {\n raw: MutableBracketGrid<TRoundData, TMatchData>;\n columns: FinalizedBracketColumn<TRoundData, TMatchData>[];\n matchElementMap: FinalizedBracketMatchElementMap<TRoundData, TMatchData>;\n /** The parts of the bracket and where they sit. Only the left-to-right double elimination grid sets it. */\n sections?: BracketGridSection<TRoundData, TMatchData>[];\n /** @internal Set when the finals were moved off the upper bracket final's row. */\n finalAlignment?: BracketFinalAlignment;\n};\n\n/** Returns the width needed to render a computed bracket grid without horizontal clipping. */\nexport const bracketGridNaturalWidth = <TRoundData, TMatchData>(\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n): number => grid.raw.grid.dimensions.width;\n\nexport const BRACKET_FINAL_ALIGNMENT = {\n UPPER: 'upper',\n CENTER: 'center',\n} as const;\n\n/**\n * Where a left-to-right double elimination puts its finals: `'upper'` level with the upper bracket final,\n * `'center'` on the midpoint between the centres of the upper bracket final and the lower bracket final.\n */\nexport type BracketFinalAlignment = (typeof BRACKET_FINAL_ALIGNMENT)[keyof typeof BRACKET_FINAL_ALIGNMENT];\n\nexport type CreateBracketGridConfig = {\n includeRoundHeaders: boolean;\n columnWidth: number;\n matchHeight: number;\n roundHeaderHeight: number;\n roundHeaderGap: number;\n columnGap: number;\n rowRoundGap: number;\n rowGap: number;\n rowSpanRoundId: string | null;\n /** @internal Resolved by a grid builder from `rowSpanRoundId`. */\n rowSpanMatchCount?: number;\n finalMatchHeight: number;\n finalColumnWidth: number;\n\n /**\n * What the final keeps between its round header and its card, in px, where that is more than\n * `roundHeaderGap`. The room goes to the final's column alone. Unset gives it the same gap as every\n * other round.\n */\n finalRoundHeaderGap?: number | null;\n\n /**\n * How far below the top of the final's card a third place match sits, in px, when the two share a\n * column. Unset (or `null`) gives the third place a column of its own, except in a mirrored layout,\n * which folds it one `rowGap` below the final's card.\n */\n thirdPlaceTopOffset?: number | null;\n swissGroupPadding: number;\n swissGroupBorderWidth: number;\n\n /**\n * The band reserved above each section for its title, in px. Only the left-to-right double elimination\n * grid reserves it; unset or `0` reserves none.\n */\n sectionTitleHeight?: number;\n\n /** The space between a section title band and the first row of its section, in px. Unset reserves none. */\n sectionTitleGap?: number;\n\n /**\n * Where the left-to-right double elimination grid puts the final and the bracket reset, see\n * {@link BracketFinalAlignment}. Unset means `'upper'`; a centred final never overlaps a third place below it.\n */\n finalAlignment?: BracketFinalAlignment;\n layout: BracketDataLayout;\n continueElement?: {\n columnWidth: number;\n elementHeight: number;\n } | null;\n};\n","import { Dimensions } from './types';\n\nexport type CreateBracketElementPartConfig = {\n elementPartHeight: number;\n};\n\nexport type BracketElementPart = {\n dimensions: Dimensions;\n};\n\nexport const createBracketElementPart = (config: CreateBracketElementPartConfig): BracketElementPart => ({\n dimensions: {\n width: 0,\n height: config.elementPartHeight,\n top: 0,\n left: 0,\n },\n});\n","import { BracketRoundSwissGroup, BracketMatch, BracketRound } from '../../../linked';\nimport { BracketElementPart, createBracketElementPart } from './bracket-element-part';\nimport { BracketContinueComponent, BracketMatchComponent, BracketRoundHeaderComponent, Dimensions } from './types';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport type BracketElementBase = {\n area: string;\n dimensions: Dimensions;\n containerDimensions: Dimensions;\n\n parts: ReadonlyArray<BracketElementPart>;\n\n span?: BracketElementSpanCoordinates;\n};\n\nexport type HeaderBracketElement<TRoundData, TMatchData> = BracketElementBase &\n HeaderBracketElementDetails<TRoundData, TMatchData>;\n\nexport type MatchBracketElement<TRoundData, TMatchData> = BracketElementBase &\n MatchBracketElementDetails<TRoundData, TMatchData>;\n\nexport type GapBracketElement = BracketElementBase & GapBracketElementDetails;\n\nexport type ContinueBracketElement<TRoundData, TMatchData> = BracketElementBase &\n ContinueBracketElementDetails<TRoundData, TMatchData>;\n\nexport type BracketElement<TRoundData, TMatchData> =\n | HeaderBracketElement<TRoundData, TMatchData>\n | MatchBracketElement<TRoundData, TMatchData>\n | GapBracketElement\n | ContinueBracketElement<TRoundData, TMatchData>;\n\nexport type BracketElementSpanCoordinates = {\n masterColumnStart: number;\n masterColumnEnd: number;\n sectionStart: number;\n sectionEnd: number;\n subColumnStart: number;\n subColumnEnd: number;\n};\n\nexport type BracketElementToCreateBase = {\n area: string;\n partHeights: number[];\n elementHeight: number;\n};\n\nexport type HeaderBracketElementDetails<TRoundData, TMatchData> = {\n type: 'header';\n component: BracketRoundHeaderComponent<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type HeaderBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n HeaderBracketElementDetails<TRoundData, TMatchData>;\n\ntype MatchBracketElementDetails<TRoundData, TMatchData> = {\n type: 'match';\n component: BracketMatchComponent<TRoundData, TMatchData>;\n match: BracketMatch<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type MatchBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n MatchBracketElementDetails<TRoundData, TMatchData>;\n\nexport type GapBracketElementDetails = {\n type: 'matchGap' | 'roundHeaderGap' | 'roundGap' | 'colGap';\n};\n\nexport type GapBracketElementToCreate = BracketElementToCreateBase & GapBracketElementDetails;\n\nexport type ContinueBracketElementDetails<TRoundData, TMatchData> = {\n type: 'continue';\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport type ContinueBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n ContinueBracketElementDetails<TRoundData, TMatchData>;\n\nexport type BracketElementToCreate<TRoundData, TMatchData> =\n | HeaderBracketElementToCreate<TRoundData, TMatchData>\n | MatchBracketElementToCreate<TRoundData, TMatchData>\n | GapBracketElementToCreate\n | ContinueBracketElementToCreate<TRoundData, TMatchData>;\n\nexport const createBracketElement = <TRoundData, TMatchData>(\n config: BracketElementToCreate<TRoundData, TMatchData>,\n): BracketElement<TRoundData, TMatchData> => {\n const { type, area, elementHeight, partHeights } = config;\n\n const parts: BracketElementPart[] = [];\n\n const newElementBase: BracketElementBase = {\n dimensions: {\n width: 0,\n height: elementHeight,\n top: 0,\n left: 0,\n },\n containerDimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n parts,\n area,\n };\n\n const newElement: BracketElement<TRoundData, TMatchData> = (() => {\n switch (type) {\n case 'header':\n return {\n ...newElementBase,\n type,\n component: config.component,\n round: config.round,\n roundSwissGroup: config.roundSwissGroup,\n } satisfies HeaderBracketElement<TRoundData, TMatchData>;\n case 'match':\n return {\n ...newElementBase,\n type,\n component: config.component,\n match: config.match,\n round: config.round,\n roundSwissGroup: config.roundSwissGroup,\n } satisfies MatchBracketElement<TRoundData, TMatchData>;\n case 'matchGap':\n case 'roundHeaderGap':\n case 'roundGap':\n case 'colGap':\n return {\n ...newElementBase,\n type,\n } satisfies GapBracketElement;\n case 'continue':\n return {\n ...newElementBase,\n type,\n component: config.component,\n matches: config.matches,\n } satisfies ContinueBracketElement<TRoundData, TMatchData>;\n default:\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n `Unknown element type: ${type as unknown as string}`,\n );\n }\n })();\n\n for (const partHeight of partHeights) {\n parts.push(createBracketElementPart({ elementPartHeight: partHeight }));\n }\n\n return newElement;\n};\n","import { BracketMap } from '../../../core';\nimport { BracketRoundSwissGroup, BracketMatch, BracketRound } from '../../../linked';\nimport { MutableBracketGrid } from './bracket-grid';\nimport { BracketContinueComponent, BracketMatchComponent, BracketRoundHeaderComponent, Dimensions } from './types';\n\nexport type FinalizedBracketColumn<TRoundData = unknown, TMatchData = unknown> = {\n dimensions: Dimensions;\n elements: FinalizedBracketElement<TRoundData, TMatchData>[];\n};\n\nexport type FinalizedHeaderBracketElement<TRoundData, TMatchData> = {\n type: 'header';\n dimensions: Dimensions;\n component: BracketRoundHeaderComponent<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type FinalizedMatchBracketElement<TRoundData, TMatchData> = {\n type: 'match';\n dimensions: Dimensions;\n component: BracketMatchComponent<TRoundData, TMatchData>;\n match: BracketMatch<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n classes: string;\n};\n\nexport type FinalizedContinueBracketElement<TRoundData, TMatchData> = {\n type: 'continue';\n dimensions: Dimensions;\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport type FinalizedBracketElement<TRoundData = unknown, TMatchData = unknown> =\n | FinalizedHeaderBracketElement<TRoundData, TMatchData>\n | FinalizedMatchBracketElement<TRoundData, TMatchData>\n | FinalizedContinueBracketElement<TRoundData, TMatchData>;\n\nexport type FinalizedBracketMatchElementMap<TRoundData, TMatchData> = BracketMap<\n string,\n FinalizedMatchBracketElement<TRoundData, TMatchData>\n>;\n\nexport const finalizeBracketGrid = <TRoundData, TMatchData>(grid: MutableBracketGrid<TRoundData, TMatchData>) => {\n const finalizedColumns: FinalizedBracketColumn<TRoundData, TMatchData>[] = [];\n const finalizedElementMap: FinalizedBracketMatchElementMap<TRoundData, TMatchData> = new BracketMap();\n\n const ignoredSections: { masterColumnIndex: number; sectionIndex: number }[] = [];\n\n for (const [masterColumnIndex, masterColumn] of grid.grid.masterColumns.entries()) {\n for (const [sectionIndex, section] of masterColumn.sections.entries()) {\n if (ignoredSections.some((s) => s.masterColumnIndex === masterColumnIndex && s.sectionIndex === sectionIndex)) {\n continue;\n }\n\n const elements: FinalizedBracketElement<TRoundData, TMatchData>[] = [];\n const firstSubColumn = section.subColumns[0];\n const lastSubColumn = section.subColumns[section.subColumns.length - 1];\n\n if (!firstSubColumn || !lastSubColumn) continue;\n\n let sectionWidth = section.dimensions.width;\n\n for (const element of firstSubColumn.elements) {\n if (element.type === 'header') {\n elements.push({\n type: 'header',\n dimensions: element.dimensions,\n component: element.component,\n round: element.round,\n roundSwissGroup: element.roundSwissGroup,\n });\n } else if (element.type === 'match') {\n const matchEl: FinalizedMatchBracketElement<TRoundData, TMatchData> = {\n type: 'match',\n dimensions: element.dimensions,\n component: element.component,\n match: element.match,\n round: element.round,\n classes: [element.match.home?.shortId, element.match.away?.shortId].filter((v) => !!v).join(' '),\n roundSwissGroup: element.roundSwissGroup,\n };\n\n elements.push(matchEl);\n finalizedElementMap.set(element.match.id, matchEl);\n } else if (element.type === 'continue') {\n elements.push({\n type: 'continue',\n dimensions: element.dimensions,\n component: element.component,\n matches: element.matches,\n });\n }\n }\n\n if (!lastSubColumn.span.isEnd) {\n for (let index = masterColumnIndex + 1; index < grid.grid.masterColumns.length; index++) {\n const nextMaster = grid.grid.masterColumns[index];\n const nextSection = nextMaster?.sections[sectionIndex];\n\n if (!nextSection) break;\n\n sectionWidth += nextSection.dimensions.width;\n ignoredSections.push({ masterColumnIndex: index, sectionIndex });\n\n if (nextSection.subColumns.some((sc) => sc.span.isEnd)) {\n break;\n }\n }\n }\n\n if (!elements.length) continue;\n\n finalizedColumns.push({\n dimensions: {\n ...section.dimensions,\n width: sectionWidth,\n },\n elements,\n });\n }\n }\n\n return {\n columns: finalizedColumns,\n elementMap: finalizedElementMap,\n };\n};\n","import { DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../../core';\nimport { BracketElementSpanCoordinates } from './bracket-element';\nimport { BracketMasterColumn } from './bracket-master-column';\nimport { Dimensions } from './types';\n\nexport type BracketGrid<TRoundData, TMatchData> = {\n masterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n};\n\nexport type MutableBracketGrid<TRoundData, TMatchData> = {\n grid: BracketGrid<TRoundData, TMatchData>;\n pushMasterColumn: (...masterColumns: BracketMasterColumn<TRoundData, TMatchData>[]) => void;\n calculateDimensions: () => void;\n setupElementSpans: () => void;\n};\n\nexport const createBracketGrid = <TRoundData, TMatchData>(config: {\n spanElementWidth: number;\n}): MutableBracketGrid<TRoundData, TMatchData> => {\n const masterColumns: BracketMasterColumn<TRoundData, TMatchData>[] = [];\n const contentWidths = new WeakMap<BracketMasterColumn<TRoundData, TMatchData>, number>();\n\n const newGrid: BracketGrid<TRoundData, TMatchData> = {\n dimensions: { width: 0, height: 0, top: 0, left: 0 },\n masterColumns,\n };\n\n const pushMasterColumn = (...newMasterColumns: BracketMasterColumn<TRoundData, TMatchData>[]) => {\n masterColumns.push(...newMasterColumns);\n };\n\n const calculateDimensions = () => {\n let currentMasterColumnLeft = 0;\n let maxGridHeight = 0;\n const masterCols = newGrid.masterColumns;\n\n for (const masterColumn of masterCols) {\n const { padding } = masterColumn;\n\n masterColumn.dimensions.left = currentMasterColumnLeft;\n masterColumn.dimensions.top = 0;\n const contentWidth = contentWidths.get(masterColumn) ?? masterColumn.dimensions.width;\n\n contentWidths.set(masterColumn, contentWidth);\n masterColumn.dimensions.width = contentWidth + padding.left + padding.right;\n\n const sections = masterColumn.sections;\n let runningTop = 0;\n\n const firstElement = sections[0]?.subColumns[0]?.elements[0];\n const firstSectionIsHeader = firstElement?.type === 'header';\n\n for (const [secIdx, section] of sections.entries()) {\n const sectionPadding = section.padding ?? padding;\n\n let sectionPaddingTop: number;\n if (secIdx === 0) {\n sectionPaddingTop = firstSectionIsHeader ? 0 : sectionPadding.top;\n } else {\n sectionPaddingTop = sectionPadding.top;\n }\n\n section.dimensions.width = masterColumn.dimensions.width;\n section.dimensions.left = masterColumn.dimensions.left;\n section.dimensions.top = runningTop;\n\n runningTop += sectionPaddingTop;\n\n const sectionContentWidth = masterColumn.dimensions.width - sectionPadding.left - sectionPadding.right;\n const subColumns = section.subColumns;\n const totalSubColumns = subColumns.length;\n const subColumnWidth = sectionContentWidth / totalSubColumns;\n let currentSubColumnLeft = masterColumn.dimensions.left + sectionPadding.left;\n let maxSectionHeight = 0;\n\n for (const subColumn of subColumns) {\n subColumn.dimensions.width = subColumnWidth;\n subColumn.dimensions.left = currentSubColumnLeft;\n subColumn.dimensions.top = section.dimensions.top + sectionPaddingTop;\n\n let totalSubColumnHeight = 0;\n const elements = subColumn.elements;\n\n for (const element of elements) {\n let totalElementHeight = 0;\n const parts = element.parts;\n\n for (const part of parts) {\n part.dimensions.width = subColumnWidth;\n part.dimensions.left = currentSubColumnLeft;\n part.dimensions.top = subColumn.dimensions.top + totalSubColumnHeight + totalElementHeight;\n totalElementHeight += part.dimensions.height;\n }\n\n element.containerDimensions.height = totalElementHeight;\n element.containerDimensions.width = subColumnWidth;\n element.containerDimensions.left = currentSubColumnLeft;\n element.containerDimensions.top = subColumn.dimensions.top + totalSubColumnHeight;\n\n element.dimensions.width = subColumnWidth;\n element.dimensions.left = currentSubColumnLeft;\n element.dimensions.top =\n element.containerDimensions.top + (totalElementHeight - element.dimensions.height) * 0.5;\n\n totalSubColumnHeight += totalElementHeight;\n }\n\n subColumn.dimensions.height = totalSubColumnHeight;\n if (totalSubColumnHeight > maxSectionHeight) maxSectionHeight = totalSubColumnHeight;\n currentSubColumnLeft += subColumnWidth;\n }\n\n // Never negative: a section may start above where it would stack (a folded third place asks for\n // that with a negative padding), but its own box still has to be a box.\n section.dimensions.height = Math.max(0, sectionPaddingTop + maxSectionHeight + sectionPadding.bottom);\n\n runningTop += maxSectionHeight + sectionPadding.bottom;\n }\n\n masterColumn.dimensions.height = runningTop;\n if (masterColumn.dimensions.height > maxGridHeight) maxGridHeight = masterColumn.dimensions.height;\n currentMasterColumnLeft += masterColumn.dimensions.width;\n }\n\n newGrid.dimensions.width = currentMasterColumnLeft;\n newGrid.dimensions.height = maxGridHeight;\n\n calculateSpanningElementDimensions();\n };\n\n const calculateSpanningElementDimensions = () => {\n const spanDimensions = new Map<string, { width: number; left: number }>();\n const masterCols = newGrid.masterColumns;\n\n for (const [mcIdx, masterColumn] of masterCols.entries()) {\n const sections = masterColumn.sections;\n\n for (const [secIdx, section] of sections.entries()) {\n const subColumns = section.subColumns;\n\n for (const [scIdx, subColumn] of subColumns.entries()) {\n const elements = subColumn.elements;\n\n for (const element of elements) {\n if (!element.span) continue;\n\n const span = element.span;\n const isStartPosition =\n mcIdx === span.masterColumnStart && secIdx === span.sectionStart && scIdx === span.subColumnStart;\n\n const spanKey = `${span.masterColumnStart}-${span.masterColumnEnd}-${span.sectionStart}-${span.sectionEnd}-${span.subColumnStart}-${span.subColumnEnd}`;\n\n if (isStartPosition && !spanDimensions.has(spanKey)) {\n const { left: spanStartLeft, width: totalSpannedWidth } = calculateSpanExtent(span, masterCols);\n const width = config.spanElementWidth;\n\n // Winner bracket rounds span two lower bracket columns. Left-align them within that\n // span (factor 0) instead of centering (factor 0.5) so each winner round n sits above\n // the lower bracket round its losers drop into (round 2n-2) - the round whose matches\n // merge into the next one. That makes the participant's drop target unambiguous. Every\n // other spanning round (e.g. lower rounds split across sub-columns) stays centered.\n const round = element.type === 'header' || element.type === 'match' ? element.round : null;\n const alignFactor = round?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET ? 0 : 0.5;\n\n spanDimensions.set(spanKey, { width, left: spanStartLeft + (totalSpannedWidth - width) * alignFactor });\n }\n\n const storedDimensions = spanDimensions.get(spanKey);\n if (storedDimensions) {\n element.dimensions.width = storedDimensions.width;\n element.dimensions.left = storedDimensions.left;\n }\n }\n }\n }\n }\n };\n\n const calculateSpanExtent = (\n span: BracketElementSpanCoordinates,\n masterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>,\n ) => {\n const start = masterColumns[span.masterColumnStart]?.sections[span.sectionStart]?.subColumns[span.subColumnStart];\n const end = masterColumns[span.masterColumnEnd]?.sections[span.sectionEnd]?.subColumns[span.subColumnEnd];\n\n if (!start || !end) return { left: start?.dimensions.left ?? 0, width: 0 };\n\n return { left: start.dimensions.left, width: end.dimensions.left + end.dimensions.width - start.dimensions.left };\n };\n\n const setupElementSpans = () => {\n const masterCols = newGrid.masterColumns;\n for (const [mcIdx, masterColumn] of masterCols.entries()) {\n const sections = masterColumn.sections;\n\n for (const [secIdx, section] of sections.entries()) {\n const subColumns = section.subColumns;\n\n for (const [scIdx, subColumn] of subColumns.entries()) {\n if (subColumn.span.isStart && subColumn.span.isEnd) continue;\n\n let spanStart = { masterColumnIndex: mcIdx, sectionIndex: secIdx, subColumnIndex: scIdx };\n if (!subColumn.span.isStart) {\n outer: for (let m = mcIdx; m >= 0; m--) {\n const mc = masterCols[m];\n if (!mc) continue;\n const sec = mc.sections[secIdx];\n if (!sec) continue;\n const end = m === mcIdx ? scIdx : sec.subColumns.length - 1;\n for (let s = end; s >= 0; s--) {\n if (sec.subColumns[s]?.span.isStart) {\n spanStart = { masterColumnIndex: m, sectionIndex: secIdx, subColumnIndex: s };\n break outer;\n }\n }\n }\n }\n\n let spanEnd = { masterColumnIndex: mcIdx, sectionIndex: secIdx, subColumnIndex: scIdx };\n if (!subColumn.span.isEnd) {\n outer: for (let m = mcIdx; m < masterCols.length; m++) {\n const mc = masterCols[m];\n if (!mc) continue;\n const sec = mc.sections[secIdx];\n if (!sec) continue;\n const start = m === mcIdx ? scIdx : 0;\n for (let s = start; s < sec.subColumns.length; s++) {\n if (sec.subColumns[s]?.span.isEnd) {\n spanEnd = { masterColumnIndex: m, sectionIndex: secIdx, subColumnIndex: s };\n break outer;\n }\n }\n }\n }\n\n const elements = subColumn.elements;\n for (const element of elements) {\n element.span = {\n masterColumnStart: spanStart.masterColumnIndex,\n masterColumnEnd: spanEnd.masterColumnIndex,\n sectionStart: spanStart.sectionIndex,\n sectionEnd: spanEnd.sectionIndex,\n subColumnStart: spanStart.subColumnIndex,\n subColumnEnd: spanEnd.subColumnIndex,\n };\n }\n }\n }\n }\n };\n\n return {\n grid: newGrid,\n pushMasterColumn,\n calculateDimensions,\n setupElementSpans,\n };\n};\n","import { BracketMasterColumnSection } from './bracket-master-column-section';\nimport { Dimensions, Spacing } from './types';\n\nexport type BracketMasterColumn<TRoundData, TMatchData> = {\n sections: ReadonlyArray<BracketMasterColumnSection<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n padding: Spacing;\n};\n\nexport type CreateBracketMasterColumnConfig = {\n columnWidth: number;\n padding: Spacing;\n};\n\nexport type MutableBracketMasterColumn<TRoundData, TMatchData> = {\n masterColumn: BracketMasterColumn<TRoundData, TMatchData>;\n pushSection: (...sections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketMasterColumnConfig,\n): MutableBracketMasterColumn<TRoundData, TMatchData> => {\n const { columnWidth, padding } = config;\n\n const sections: BracketMasterColumnSection<TRoundData, TMatchData>[] = [];\n\n const newMasterColumn: BracketMasterColumn<TRoundData, TMatchData> = {\n dimensions: {\n width: columnWidth,\n height: 0,\n top: 0,\n left: 0,\n },\n padding,\n sections,\n };\n\n const pushSection = (...newSections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => {\n sections.push(...newSections);\n };\n\n return {\n masterColumn: newMasterColumn,\n pushSection,\n };\n};\n","import { BracketSubColumn } from './bracket-sub-column';\nimport { Dimensions, Spacing } from './types';\n\nexport type BracketMasterColumnSectionType = 'round' | 'gap';\n\nexport type BracketMasterColumnSection<TRoundData, TMatchData> = {\n subColumns: ReadonlyArray<BracketSubColumn<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n type: BracketMasterColumnSectionType;\n\n /** Overrides the master column padding for this section */\n padding?: Spacing;\n};\n\nexport type CreateBracketMasterColumnSectionConfig = {\n type: BracketMasterColumnSectionType;\n padding?: Spacing;\n};\n\nexport type MutableBracketMasterColumnSection<TRoundData, TMatchData> = {\n masterColumnSection: BracketMasterColumnSection<TRoundData, TMatchData>;\n pushSubColumn: (...subColumns: BracketSubColumn<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketMasterColumnSection = <TRoundData, TMatchData>(\n config: CreateBracketMasterColumnSectionConfig,\n): MutableBracketMasterColumnSection<TRoundData, TMatchData> => {\n const { type, padding } = config;\n\n const subColumns: BracketSubColumn<TRoundData, TMatchData>[] = [];\n\n const newMasterColumnSection: BracketMasterColumnSection<TRoundData, TMatchData> = {\n dimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n subColumns,\n type,\n padding,\n };\n\n const pushSubColumn = (...newSubColumns: BracketSubColumn<TRoundData, TMatchData>[]) => {\n subColumns.push(...newSubColumns);\n };\n\n return {\n masterColumnSection: newMasterColumnSection,\n pushSubColumn,\n };\n};\n","import { BracketElement } from './bracket-element';\nimport { Dimensions } from './types';\n\nexport type BracketSubColumn<TRoundData, TMatchData> = {\n dimensions: Dimensions;\n elements: ReadonlyArray<BracketElement<TRoundData, TMatchData>>;\n span: BracketSubColumnSpan;\n};\n\nexport type BracketSubColumnSpan = {\n isStart: boolean;\n isEnd: boolean;\n};\n\nexport type CreateBracketSubColumnConfig = {\n span: BracketSubColumnSpan;\n};\n\nexport type MutableBracketSubColumn<TRoundData, TMatchData> = {\n subColumn: BracketSubColumn<TRoundData, TMatchData>;\n pushElement: (...elements: BracketElement<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketSubColumn = <TRoundData, TMatchData>(\n config: CreateBracketSubColumnConfig,\n): MutableBracketSubColumn<TRoundData, TMatchData> => {\n const { span } = config;\n\n const elements: BracketElement<TRoundData, TMatchData>[] = [];\n\n const newSubColumn: BracketSubColumn<TRoundData, TMatchData> = {\n dimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n elements,\n span,\n };\n\n const pushElement = (...newElements: BracketElement<TRoundData, TMatchData>[]) => {\n elements.push(...newElements);\n };\n\n return {\n subColumn: newSubColumn,\n pushElement,\n };\n};\n","import { COMMON_BRACKET_ROUND_TYPE } from '../../../core';\nimport { Bracket, BracketMatch } from '../../../linked';\nimport {\n BracketContinueComponent,\n BracketMasterColumn,\n createBracketElement,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n} from '../core';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport const isBracketContinueMatch = <TRoundData, TMatchData>(match: BracketMatch<TRoundData, TMatchData>) =>\n match.round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE &&\n (match.relation.type === 'one-to-nothing' || match.relation.type === 'two-to-nothing');\n\nexport const getBracketContinueMatches = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n): BracketMatch<TRoundData, TMatchData>[] =>\n Array.from(bracketData.matches.values()).filter((match) => isBracketContinueMatch(match));\n\nexport type CreateBracketContinueMasterColumnConfig<TRoundData, TMatchData> = {\n existingMasterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n columnWidth: number;\n elementHeight: number;\n\n /** Vertical space taken by the round header block (header + gap). 0 if headers are hidden. */\n headerOffset: number;\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport const createBracketContinueMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketContinueMasterColumnConfig<TRoundData, TMatchData>,\n) => {\n const { existingMasterColumns, columnWidth, elementHeight, headerOffset, component, matches } = config;\n\n const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];\n\n if (!lastMasterColumn) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'No last master column found in existing master columns',\n );\n }\n\n // Dimensions are not calculated yet at this point, but all part heights are static, so the\n // total column height is the sum of the tallest sub column of every section plus its padding - the\n // same sum `calculateDimensions` makes, which skips the top padding of a leading header section.\n const firstSectionIsHeader = lastMasterColumn.sections[0]?.subColumns[0]?.elements[0]?.type === 'header';\n let totalHeight = 0;\n\n for (const [sectionIndex, section] of lastMasterColumn.sections.entries()) {\n const padding = section.padding ?? lastMasterColumn.padding;\n const paddingTop = sectionIndex === 0 && firstSectionIsHeader ? 0 : padding.top;\n const sectionHeight = Math.max(\n 0,\n ...section.subColumns.map((subColumn) =>\n subColumn.elements.reduce(\n (subColumnHeight, element) =>\n subColumnHeight + element.parts.reduce((sum, part) => sum + part.dimensions.height, 0),\n 0,\n ),\n ),\n );\n\n totalHeight += paddingTop + sectionHeight + padding.bottom;\n }\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n if (headerOffset > 0) {\n const headerGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: headerOffset,\n partHeights: [headerOffset],\n });\n\n pushElement(headerGapElement);\n }\n\n const containerHeight = Math.max(elementHeight, totalHeight - headerOffset);\n\n const continueElement = createBracketElement<TRoundData, TMatchData>({\n area: 'continue',\n type: 'continue',\n elementHeight,\n partHeights: [containerHeight],\n component,\n matches,\n });\n\n pushElement(continueElement);\n\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n\n return masterColumn;\n};\n","import { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\n\nexport type LineOptions = {\n path: PathOptions;\n\n /** Draw right to left - the flow direction of a mirrored bracket's way back. */\n inverted?: boolean;\n};\n\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const linePath = (from: BracketPosition, to: BracketPosition, options: LineOptions) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.end : to.inline.start;\n\n return path(`M ${fromInline} ${from.block.center} L ${toInline} ${to.block.center}`, options.path);\n};\n\n/**\n * The connector between two cards sharing a column, where {@link linePath} and `curvePath` both\n * degenerate to a zero-width horizontal run: straight down (or up) the column, edge to edge.\n */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const verticalPath = (from: BracketPosition, to: BracketPosition, options: LineOptions) => {\n const inline = (from.inline.center + to.inline.center) / 2;\n const isDownwards = to.block.center >= from.block.center;\n\n const fromBlock = isDownwards ? from.block.end : from.block.start;\n const toBlock = isDownwards ? to.block.start : to.block.end;\n\n return path(`M ${inline} ${fromBlock} V ${toBlock}`, options.path);\n};\n\nexport type GutterLineOptions = LineOptions & {\n /** How far past the column's edge the vertical run sits - half a column gap keeps it clear of both. */\n gutter: number;\n};\n\n/**\n * A same-column connector for two cards with others stacked between them: out sideways, along the\n * empty strip beside the column, and back in. {@link verticalPath} would run through everything in\n * its way.\n */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const gutterPath = (from: BracketPosition, to: BracketPosition, options: GutterLineOptions) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.start : to.inline.end;\n const runInline = inverted\n ? Math.min(fromInline, toInline) - options.gutter\n : Math.max(fromInline, toInline) + options.gutter;\n\n return path(`M ${fromInline} ${from.block.center} H ${runInline} V ${to.block.center} H ${toInline}`, options.path);\n};\n","import { BRACKET_ROUND_MIRROR_TYPE, COMMON_BRACKET_ROUND_TYPE } from '../core';\nimport { CurveOptions, curvePath } from './curve';\nimport { Dimensions } from './grid/core/types';\nimport { BRACKET_FINAL_ALIGNMENT, ComputedBracketGrid } from './grid/types';\nimport { isBracketContinueMatch } from './grid/prebuild/bracket-continue-master-column';\nimport { gutterPath, linePath, LineOptions, verticalPath } from './line';\nimport { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\nimport { BracketDrawing, BracketEdge } from './shapes';\n\nexport type DrawManDimensions<TRoundData, TMatchData> = {\n columnWidth: number;\n matchHeight: number;\n roundHeaderHeight: number;\n columnGap: number;\n upperLowerGap: number;\n rowGap: number;\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>;\n path: Omit<PathOptions, 'className' | 'id'>;\n curve: Omit<CurveOptions, 'path' | 'inverted'>;\n\n /** Path options for the lines connecting the continuing matches to the continue element */\n continuePath?: Omit<PathOptions, 'className' | 'id'>;\n};\n\nconst makePos = (dimensions: Dimensions): BracketPosition => ({\n block: {\n start: dimensions.top,\n end: dimensions.top + dimensions.height,\n center: dimensions.top + dimensions.height / 2,\n },\n inline: {\n start: dimensions.left,\n end: dimensions.left + dimensions.width,\n center: dimensions.left + dimensions.width / 2,\n },\n});\n\n/**\n * Two cards in the same column - the shape a stacked layout's centre chain makes, where a round hangs\n * directly below the one that feeds it and every horizontal run has zero width.\n */\nconst isSameColumn = (from: BracketPosition, to: BracketPosition) =>\n Math.abs(from.inline.center - to.inline.center) < 1;\n\n/** A one-to-one connector, whichever way round the two cards sit. */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nconst straightPath = (from: BracketPosition, to: BracketPosition, options: LineOptions) =>\n isSameColumn(from, to) ? verticalPath(from, to, options) : linePath(from, to, options);\n\n/** One arm of a merge, bending towards its card, collapsing to a straight run when the two share a column. */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nconst mergePath = (from: BracketPosition, to: BracketPosition, options: CurveOptions) =>\n isSameColumn(from, to)\n ? verticalPath(from, to, { path: options.path })\n : curvePath(from, to, to.block.center >= from.block.center ? 'down' : 'up', options);\n\nconst edgeId = (fromMatchId: string, toMatchId: string) => `${fromMatchId}|${toMatchId}`;\n\nexport const drawMan = <TRoundData, TMatchData>(\n dimensions: DrawManDimensions<TRoundData, TMatchData>,\n): BracketDrawing => {\n const edges: BracketEdge[] = [];\n const takenIds = new Set<string>();\n\n // A repeated id would make the host's `@for` throw, and a mirrored fold can draw the same pair of\n // cards from both of its sides.\n const pushEdge = (edge: BracketEdge) => {\n let id = edge.id;\n\n for (let attempt = 2; takenIds.has(id); attempt++) id = `${edge.id}#${attempt}`;\n\n takenIds.add(id);\n edges.push(id === edge.id ? edge : { ...edge, id });\n };\n\n const continueElement = dimensions.bracketGrid.columns\n .flatMap((col) => col.elements)\n .find((el) => el.type === 'continue');\n const continuePos = continueElement ? makePos(continueElement.dimensions) : null;\n const continueSources: { pos: BracketPosition; className: string; matchId: string }[] = [];\n\n for (const col of dimensions.bracketGrid.columns) {\n for (const el of col.elements) {\n if (el.type !== 'match') continue;\n\n const currentMatchParticipantsShortIds = [el.match.home?.shortId, el.match.away?.shortId]\n .filter((id) => !!id)\n .join(' ');\n\n const currentPos = makePos(el.dimensions);\n\n if (el.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;\n\n if (continuePos && isBracketContinueMatch(el.match)) {\n continueSources.push({\n pos: currentPos,\n className: el.match.winner?.shortId || '',\n matchId: el.match.id,\n });\n }\n\n // Crossing the middle of a fold. Every other line here is drawn by the match it flows *into*, but a\n // round in the middle of a mirrored bracket is fed from both sides and its relation names only one\n // of them - so the round on the way back draws its own line. Deliberately outside the switch below:\n // which relation a match has says nothing about which side of a fold it sits on.\n if (el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT && 'nextMatch' in el.match.relation) {\n const { nextMatch, nextRound } = el.match.relation;\n\n if (nextRound.mirrorRoundType === null) {\n const next = dimensions.bracketGrid.matchElementMap.getOrThrow(nextMatch.id);\n\n // The winner's short id, not both participants': this line is somebody advancing along it, and\n // the journey highlight lights the path a participant actually travelled.\n pushEdge(\n straightPath(makePos(next.dimensions), currentPos, {\n path: {\n ...dimensions.path,\n id: edgeId(nextMatch.id, el.match.id),\n className: el.match.winner?.shortId || '',\n },\n }),\n );\n }\n }\n\n switch (el.match.relation.type) {\n case 'none':\n case 'nothing-to-one': {\n continue;\n }\n case 'one-to-nothing':\n case 'one-to-one': {\n const prev = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousMatch.id);\n const prevPos = makePos(prev.dimensions);\n\n // The winner of the match it comes from, like every other connector, or the journey highlight\n // lights the line for whoever arrived from somewhere else.\n pushEdge(\n straightPath(prevPos, currentPos, {\n path: {\n ...dimensions.path,\n id: edgeId(el.match.relation.previousMatch.id, el.match.id),\n className: el.match.relation.previousMatch.winner?.shortId || '',\n },\n // The way back runs right to left: the round it comes from sits on the *other* side.\n inverted: el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT,\n }),\n );\n\n break;\n }\n\n case 'two-to-nothing':\n case 'two-to-one': {\n const prevUpper = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousUpperMatch.id);\n const prevLower = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousLowerMatch.id);\n\n const prevUpperPos = makePos(prevUpper.dimensions);\n const prevLowerPos = makePos(prevLower.dimensions);\n\n const upperId = edgeId(el.match.relation.previousUpperMatch.id, el.match.id);\n const lowerId = edgeId(el.match.relation.previousLowerMatch.id, el.match.id);\n\n const isLowerUpperMerger =\n el.match.relation.previousLowerRound.id !== el.match.relation.previousUpperRound.id;\n\n const invertCurve = el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;\n\n const curveOptions: CurveOptions = {\n ...dimensions.curve,\n inverted: invertCurve,\n path: { ...dimensions.path, id: upperId, className: '' },\n };\n\n if (isLowerUpperMerger && dimensions.bracketGrid.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER) {\n pushEdge(\n straightPath(prevUpperPos, currentPos, {\n path: { ...dimensions.path, id: upperId, className: currentMatchParticipantsShortIds },\n inverted: invertCurve,\n }),\n );\n } else {\n pushEdge(\n mergePath(prevUpperPos, currentPos, {\n ...curveOptions,\n path: {\n ...curveOptions.path,\n className: el.match.relation.previousUpperMatch.winner?.shortId || '',\n },\n }),\n );\n }\n\n const lowerPathOptions = {\n ...curveOptions.path,\n id: lowerId,\n className: el.match.relation.previousLowerMatch.winner?.shortId || '',\n };\n\n // A feeder directly *below* in the same column is the one connector a stacked layout has that\n // crosses its own cards - the losers champion coming up to the grand final, past everything\n // hanging under it. Every other same-column pair is adjacent, so a straight run is clear.\n const isBlockToBlock =\n isSameColumn(prevLowerPos, currentPos) && prevLowerPos.block.start > currentPos.block.end;\n\n pushEdge(\n isBlockToBlock\n ? gutterPath(prevLowerPos, currentPos, {\n // Dashed, like the continue column's: it runs the height of a block past cards it has\n // nothing to do with, and reads as a stray bracket edge if it looks like one.\n path: {\n ...(dimensions.continuePath ?? dimensions.path),\n id: lowerId,\n className: lowerPathOptions.className,\n },\n inverted: invertCurve,\n gutter: dimensions.columnGap / 2,\n })\n : mergePath(prevLowerPos, currentPos, { ...curveOptions, path: lowerPathOptions }),\n );\n\n break;\n }\n }\n }\n }\n\n if (continuePos && continueSources.length) {\n const continuePathOptions = dimensions.continuePath ?? dimensions.path;\n const curveAmount = dimensions.curve.lineStartingCurveAmount;\n const trunkInline = continuePos.inline.start - dimensions.columnGap / 2;\n const continueBlockCenter = continuePos.block.center;\n const sourceBlocks = continueSources.map((source) => source.pos.block.center);\n const firstSourceBlock = Math.min(...sourceBlocks);\n const lastSourceBlock = Math.max(...sourceBlocks);\n const trunkBlocks: number[] = [continueBlockCenter];\n\n for (const source of continueSources) {\n const sourceBlockCenter = source.pos.block.center;\n const blockDistance = continueBlockCenter - sourceBlockCenter;\n const sourcePathOptions: PathOptions = {\n ...continuePathOptions,\n id: edgeId(source.matchId, 'continue'),\n className: source.className,\n };\n\n const isTrunkCorner =\n (sourceBlockCenter === firstSourceBlock && blockDistance > 0.5) ||\n (sourceBlockCenter === lastSourceBlock && blockDistance < -0.5);\n\n // The straight run into the trunk is the same three commands with a zero-radius corner, so that a\n // source turning into a corner as the rows move animates rather than jumping.\n const curve = isTrunkCorner ? Math.min(curveAmount, Math.abs(blockDistance)) : 0;\n const curveEndBlock = sourceBlockCenter + curve * Math.sign(blockDistance);\n\n pushEdge(\n path(\n `M ${source.pos.inline.end} ${sourceBlockCenter}\n H ${trunkInline - curve}\n Q ${trunkInline} ${sourceBlockCenter}, ${trunkInline} ${curveEndBlock}`,\n sourcePathOptions,\n ),\n );\n\n trunkBlocks.push(curveEndBlock);\n }\n\n const trunkBlockStart = Math.min(...trunkBlocks);\n const trunkBlockEnd = Math.max(...trunkBlocks);\n\n if (trunkBlockEnd - trunkBlockStart > 0.5) {\n pushEdge(\n path(`M ${trunkInline} ${trunkBlockStart} V ${trunkBlockEnd}`, {\n ...continuePathOptions,\n id: 'continue|trunk',\n className: '',\n }),\n );\n }\n\n pushEdge(\n path(`M ${trunkInline} ${continueBlockCenter} H ${continuePos.inline.start}`, {\n ...continuePathOptions,\n id: 'continue|element',\n className: '',\n }),\n );\n }\n\n return { edges, rects: [], gradients: [] };\n};\n","import { BracketRoundId } from '../core';\nimport { BracketSwissColors, BracketSwissGroupColorType } from '../linked/swiss';\nimport { curvePath } from './curve';\nimport { FinalizedBracketElement, FinalizedMatchBracketElement } from './grid/core/bracket-finalizer';\nimport { ComputedBracketGrid } from './grid/types';\nimport { BracketPosition } from './math';\nimport { PathOptions } from './path';\nimport { BracketDrawing, BracketEdge, BracketGradient, BracketRect } from './shapes';\n\nexport type DrawSwissManDimensions<TRoundData, TMatchData> = {\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>;\n path: Omit<PathOptions, 'className' | 'stroke' | 'id'>;\n\n // The swiss connection lines always bend twice with the same radius, so there is no\n // dedicated ending curve amount (it would make no sense here).\n curve: {\n lineStartingCurveAmount: number;\n };\n groupBorder: {\n padding: number;\n radius: number;\n width: number;\n };\n colors?: BracketSwissColors;\n\n /** Used to create document wide unique ids for the connection line gradients */\n idPrefix: string;\n};\n\ntype SwissGroupGeometry = {\n id: string;\n wins: number;\n losses: number;\n colorType: BracketSwissGroupColorType;\n position: BracketPosition;\n winnerShortIds: string[];\n loserShortIds: string[];\n};\n\ntype SwissRoundGeometry = {\n groups: Map<string, SwissGroupGeometry>;\n};\n\n// Every finalized column of a swiss grid is one group section. The connection lines run\n// from group to group instead of match to match: the winners of group (w-l) move to group\n// (w+1-l) inside the next round, the losers move to group (w-l+1).\nconst collectSwissRoundGeometries = <TRoundData, TMatchData>(\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>,\n): SwissRoundGeometry[] => {\n const rounds = new Map<BracketRoundId, SwissRoundGeometry>();\n\n for (const column of bracketGrid.columns) {\n const matchElements = column.elements.filter(\n (\n element: FinalizedBracketElement<TRoundData, TMatchData>,\n ): element is FinalizedMatchBracketElement<TRoundData, TMatchData> => element.type === 'match',\n );\n const group = matchElements[0]?.roundSwissGroup;\n const round = matchElements[0]?.round;\n\n if (!group || !round) continue;\n\n const [wins, losses] = group.id.split('-').map(Number);\n\n if (wins === undefined || losses === undefined || isNaN(wins) || isNaN(losses)) continue;\n\n const matchesTop = Math.min(...matchElements.map((element) => element.dimensions.top));\n const matchesBottom = Math.max(\n ...matchElements.map((element) => element.dimensions.top + element.dimensions.height),\n );\n\n const winnerShortIds: string[] = [];\n const loserShortIds: string[] = [];\n\n for (const element of matchElements) {\n if (!element.match.winner) continue;\n\n const winner = element.match.winner;\n const loser = element.match.home?.id === winner.id ? element.match.away : element.match.home;\n\n winnerShortIds.push(winner.shortId);\n if (loser) loserShortIds.push(loser.shortId);\n }\n\n // The lines attach to the group border, which wraps the matches plus the group\n // padding and therefore matches the section bounds horizontally.\n const position: BracketPosition = {\n block: {\n start: matchesTop,\n end: matchesBottom,\n center: (matchesTop + matchesBottom) / 2,\n },\n inline: {\n start: column.dimensions.left,\n end: column.dimensions.left + column.dimensions.width,\n center: column.dimensions.left + column.dimensions.width / 2,\n },\n };\n\n let roundGeometry = rounds.get(round.id);\n\n if (!roundGeometry) {\n roundGeometry = { groups: new Map() };\n rounds.set(round.id, roundGeometry);\n }\n\n roundGeometry.groups.set(group.id, {\n id: group.id,\n wins,\n losses,\n colorType: group.colorType,\n position,\n winnerShortIds,\n loserShortIds,\n });\n }\n\n // The finalized columns are ordered left to right, so first appearance equals round order\n return Array.from(rounds.values());\n};\n\nconst groupBorderRect = (\n group: SwissGroupGeometry,\n border: DrawSwissManDimensions<unknown, unknown>['groupBorder'],\n color: string | undefined,\n id: string,\n // eslint-disable-next-line max-params -- SVG geometry helper; (group, border, color, id) are distinct positional inputs\n): BracketRect => {\n // The group box wraps the matches plus the group padding plus the border itself. The\n // rect is inset by half the stroke width so the stroke renders fully inside the group\n // bounds instead of getting cut off at the edges of the bracket container.\n const boxPadding = border.padding + border.width;\n const strokeInset = border.width / 2;\n\n return {\n id,\n x: group.position.inline.start + strokeInset,\n y: group.position.block.start - boxPadding + strokeInset,\n width: group.position.inline.end - group.position.inline.start - border.width,\n height: group.position.block.end - group.position.block.start + boxPadding * 2 - border.width,\n radius: border.radius,\n stroke: color ?? 'currentColor',\n strokeWidth: border.width,\n tone: group.colorType,\n cssClass: `et-bracket-swiss-group-border et-bracket-swiss-group-border--${group.id} et-bracket-swiss-group-border--${group.colorType}`,\n };\n};\n\ntype SwissLineGradient = {\n id: string;\n fromX: number;\n toX: number;\n from: string;\n neutral: string;\n to: string;\n};\n\n// A horizontal gradient for the connection lines: they leave the source group in its\n// color, fade to the neutral color towards their vertical jog in the middle and fade into\n// the target group color on the second half. The connection lines always run from left to\n// right, so user space coordinates can be used (they also work for straight lines, where\n// the bounding box has no height).\nconst lineGradient = (config: SwissLineGradient): BracketGradient => ({\n id: config.id,\n fromX: config.fromX,\n toX: config.toX,\n stops: [\n { offset: '0%', color: config.from },\n { offset: '50%', color: config.neutral },\n { offset: '100%', color: config.to },\n ],\n});\n\nexport const drawSwissMan = <TRoundData, TMatchData>(\n dimensions: DrawSwissManDimensions<TRoundData, TMatchData>,\n): BracketDrawing => {\n const edges: BracketEdge[] = [];\n const rects: BracketRect[] = [];\n const gradients: BracketGradient[] = [];\n\n const roundGeometries = collectSwissRoundGeometries(dimensions.bracketGrid);\n const colors = dimensions.colors;\n\n for (const [roundIndex, roundGeometry] of roundGeometries.entries()) {\n for (const group of roundGeometry.groups.values()) {\n rects.push(\n groupBorderRect(group, dimensions.groupBorder, colors?.[group.colorType], `r${roundIndex}|${group.id}`),\n );\n }\n }\n\n const curveOptions = {\n lineStartingCurveAmount: dimensions.curve.lineStartingCurveAmount,\n lineEndingCurveAmount: dimensions.curve.lineStartingCurveAmount,\n };\n\n for (const [roundIndex, roundGeometry] of roundGeometries.entries()) {\n const nextRoundGeometry = roundGeometries[roundIndex + 1];\n\n if (!nextRoundGeometry) break;\n\n for (const group of roundGeometry.groups.values()) {\n const targets = [\n { geometry: nextRoundGeometry.groups.get(`${group.wins + 1}-${group.losses}`), shortIds: group.winnerShortIds },\n { geometry: nextRoundGeometry.groups.get(`${group.wins}-${group.losses + 1}`), shortIds: group.loserShortIds },\n ];\n\n for (const { geometry: target, shortIds } of targets) {\n if (!target) continue;\n\n const edgeId = `r${roundIndex}|${group.id}|${target.id}`;\n // Only URI characters: this ends up inside a `url(#…)` the `stroke` attribute has to resolve.\n const gradientId = `${dimensions.idPrefix}-swiss-line-r${roundIndex}-${group.id}-to-${target.id}`;\n const neutralColor = colors?.neutral;\n\n let stroke = neutralColor;\n\n if (neutralColor) {\n const from = colors?.[group.colorType] ?? neutralColor;\n const to = colors?.[target.colorType] ?? neutralColor;\n\n if (from !== neutralColor || to !== neutralColor) {\n gradients.push(\n lineGradient({\n id: gradientId,\n fromX: group.position.inline.end,\n toX: target.position.inline.start,\n from,\n neutral: neutralColor,\n to,\n }),\n );\n\n stroke = `url(#${gradientId})`;\n }\n }\n\n const pathOptions: PathOptions = {\n ...dimensions.path,\n id: edgeId,\n className: shortIds.join(' '),\n stroke,\n };\n const blockDelta = target.position.block.center - group.position.block.center;\n\n // Always a curve, even between two groups on the same row, where the bends collapse to nothing\n // and it draws as a straight run - one shape per connector is what lets it animate.\n edges.push(\n curvePath(group.position, target.position, blockDelta < 0 ? 'up' : 'down', {\n ...curveOptions,\n path: pathOptions,\n }),\n );\n }\n }\n }\n\n return { edges, rects, gradients };\n};\n","export const calculateUpperLowerRatio = (upperRoundsCount: number, lowerRoundsCount: number) => {\n const remainingUpperRounds = upperRoundsCount - 1;\n const remainingLowerRounds = lowerRoundsCount - 1;\n\n if (remainingUpperRounds === 0) return 1;\n\n return remainingLowerRounds / remainingUpperRounds;\n};\n\nexport const calculateColumnSplitFactor = (upperToLowerRatio: number) => (upperToLowerRatio === 1.5 ? 2 : 1);\n\nexport const calculateLowerRoundIndex = (subColumnIndex: number, splitFactor: number) =>\n Math.floor(subColumnIndex / splitFactor);\n\n// eslint-disable-next-line max-params -- index math over positional grid coordinates\nexport const calculateUpperRoundIndex = (subColumnIndex: number, upperToLowerRatio: number, splitFactor: number) => {\n const completeColumnIndex = Math.floor(subColumnIndex / splitFactor);\n\n if (completeColumnIndex === 0) return 0;\n\n return Math.floor((completeColumnIndex - 1) / upperToLowerRatio) + 1;\n};\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../../core';\nimport { BracketRound } from '../../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n BracketSubColumnSpan,\n createBracketElement,\n createBracketSubColumn,\n} from '../core';\nimport { CreateBracketGridConfig } from '../types';\n\nexport type CreateRoundBracketSubColumnRelativeToFirstRoundConfig<TRoundData, TMatchData> = {\n firstRound: BracketRound<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n span: BracketSubColumnSpan;\n hasReverseFinal: boolean;\n options: CreateBracketGridConfig;\n components: BracketComponents<TRoundData, TMatchData>;\n\n /**\n * Reserved space below the last match, for a layout whose columns are taller than the first round\n * needs - a stacked bracket's centre chain hanging past the bottom of its block.\n */\n bottomPadding?: number;\n\n topPadding?: number;\n\n /**\n * How many first-round rows each of this round's matches owns. Derived from the round's own match\n * count when unset; a folded round is placed by its offset instead and takes `1`.\n */\n matchFactor?: number;\n};\n\nexport const createRoundBracketSubColumnRelativeToFirstRound = <TRoundData, TMatchData>(\n config: CreateRoundBracketSubColumnRelativeToFirstRoundConfig<TRoundData, TMatchData>,\n) => {\n const { firstRound, round, options, span, hasReverseFinal } = config;\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span,\n });\n\n const matchFactor =\n config.matchFactor ?? Math.max(1, (options.rowSpanMatchCount ?? firstRound.matchCount) / round.matchCount);\n const matches = Array.from(round.matches.values());\n\n const isFinalRound = hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n const roundHeaderGap = isFinalRound\n ? Math.max(options.roundHeaderGap, options.finalRoundHeaderGap ?? 0)\n : options.roundHeaderGap;\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n if (options.roundHeaderHeight > 0) {\n elementsToCreate.push(\n {\n type: 'header',\n area: `h${round.shortId}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: config.components.roundHeader,\n round,\n roundSwissGroup: null,\n },\n {\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [roundHeaderGap],\n elementHeight: roundHeaderGap,\n },\n );\n }\n\n if (config.topPadding) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [config.topPadding],\n elementHeight: config.topPadding,\n });\n }\n\n for (const [matchIndex, match] of matches.entries()) {\n const isLastMatch = matchIndex === matches.length - 1;\n\n // One row per match this one is fed by. A fractional factor has no whole feeder row to align to,\n // so floor it and let the block padding below absorb the remainder - rounding up instead emits a\n // row the block height cannot pay for, and the padding turns negative to compensate.\n const fedMatchCount = Math.floor(matchFactor);\n const matchRows: number[] = [];\n\n for (let factorIndex = 0; factorIndex < fedMatchCount; factorIndex++) {\n matchRows.push(options.matchHeight);\n\n if (factorIndex < fedMatchCount - 1) matchRows.push(options.rowGap);\n }\n\n const elementHeight = isFinalRound ? options.finalMatchHeight : options.matchHeight;\n const blockHeight = Math.max(elementHeight, matchFactor * options.matchHeight + (matchFactor - 1) * options.rowGap);\n const currentBlockHeight = matchRows.reduce((total, height) => total + height, 0);\n\n matchRows[matchRows.length - 1] = (matchRows[matchRows.length - 1] ?? 0) + blockHeight - currentBlockHeight;\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: matchRows,\n elementHeight,\n component: isFinalRound ? config.components.finalMatch : config.components.match,\n match,\n round,\n roundSwissGroup: null,\n });\n\n if (!isLastMatch) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [options.rowGap],\n elementHeight: options.rowGap,\n });\n }\n }\n\n if (config.bottomPadding) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [config.bottomPadding],\n elementHeight: config.bottomPadding,\n });\n }\n\n for (const elementData of elementsToCreate) {\n const element = createBracketElement(elementData);\n\n pushElement(element);\n }\n\n return subColumn;\n};\n","import { BracketRound } from '../../../linked';\nimport {\n BracketComponents,\n BracketElement,\n BracketMasterColumnSection,\n BracketSubColumn,\n createBracketMasterColumnSection,\n} from '../core';\nimport { CreateBracketGridConfig } from '../types';\nimport { createRoundBracketSubColumnRelativeToFirstRound } from './bracket-sub-column-relative-to-first-round';\n\nexport type CreateFoldedThirdPlaceSectionConfig<TRoundData, TMatchData> = {\n /** The sub column holding the final, which the folded round is placed relative to. */\n finalSubColumn: BracketSubColumn<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n /** How far below the top of the final's card the third place card sits, in px. */\n topOffset: number;\n options: CreateBracketGridConfig;\n components: BracketComponents<TRoundData, TMatchData>;\n};\n\nconst heightOfElement = <TRoundData, TMatchData>(element: BracketElement<TRoundData, TMatchData>) =>\n element.parts.reduce((total, part) => total + part.dimensions.height, 0);\n\nconst cardGeometry = <TRoundData, TMatchData>(subColumn: BracketSubColumn<TRoundData, TMatchData>) => {\n let height = 0;\n let cardTop: number | null = null;\n\n for (const element of subColumn.elements) {\n const elementHeight = heightOfElement(element);\n\n if (element.type === 'match' && cardTop === null) {\n cardTop = height + (elementHeight - element.dimensions.height) / 2;\n }\n\n height += elementHeight;\n }\n\n return { cardTop: cardTop ?? 0, height };\n};\n\n/**\n * The third place match as a second section of the final's master column: one card the given number of\n * px below the top of the final's, with its own round header above it.\n *\n * @internal\n */\nexport const createFoldedThirdPlaceSection = <TRoundData, TMatchData>(\n config: CreateFoldedThirdPlaceSectionConfig<TRoundData, TMatchData>,\n): BracketMasterColumnSection<TRoundData, TMatchData> => {\n const { options, round } = config;\n const final = cardGeometry(config.finalSubColumn);\n const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n\n // The section stacks below the final's, so what it has to make up is the offset less the room the\n // final's own section already takes. Negative when the fold lands inside that room, which is the\n // ordinary case: the final's block owns the rows of every round feeding it, so it is far taller\n // than its card.\n const paddingTop = final.cardTop + config.topOffset - final.height - headerOffset;\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n padding: { top: paddingTop, bottom: 0, left: 0, right: 0 },\n });\n\n pushSubColumn(\n createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: round,\n round,\n options,\n hasReverseFinal: false,\n // Placed by its offset, so it owns one row rather than the block a squeezed round would give it.\n matchFactor: 1,\n span: { isStart: true, isEnd: true },\n components: config.components,\n }),\n );\n\n return masterColumnSection;\n};\n","import {\n BracketElementToCreate,\n BracketMasterColumn,\n createBracketElement,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n} from '../core';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport type CreateBracketGapMasterColumnConfig<TRoundData, TMatchData> = {\n existingMasterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n columnGap: number;\n};\n\nexport const createBracketGapMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketGapMasterColumnConfig<TRoundData, TMatchData>,\n) => {\n const { existingMasterColumns, columnGap } = config;\n\n const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];\n\n if (!lastMasterColumn) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'No last master column found in existing master columns',\n );\n }\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: columnGap,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n for (const section of lastMasterColumn.sections) {\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n padding: section.padding && { ...section.padding, left: 0, right: 0 },\n });\n\n const lastSubColumn = section.subColumns[section.subColumns.length - 1];\n\n if (!lastSubColumn) {\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No last sub column found in section');\n }\n\n const { pushElement, subColumn } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: lastSubColumn.span.isEnd ? true : false,\n isEnd: lastSubColumn.span.isEnd ? true : false,\n },\n });\n\n for (const lastSubColumnElement of lastSubColumn.elements) {\n const partHeights = lastSubColumnElement.parts.map((part) => part.dimensions.height);\n\n const elementToCreate: BracketElementToCreate<TRoundData, TMatchData> = (() => {\n switch (lastSubColumnElement.type) {\n case 'matchGap':\n case 'roundHeaderGap':\n case 'roundGap':\n case 'colGap': {\n return {\n area: !lastSubColumn.span.isEnd ? lastSubColumnElement.area : `.`,\n type: !lastSubColumn.span.isEnd ? lastSubColumnElement.type : 'colGap',\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n };\n }\n case 'header':\n if (lastSubColumn.span.isEnd) break;\n\n return {\n area: lastSubColumnElement.area,\n type: lastSubColumnElement.type,\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n component: lastSubColumnElement.component,\n round: lastSubColumnElement.round,\n roundSwissGroup: lastSubColumnElement.roundSwissGroup,\n };\n\n case 'match':\n if (lastSubColumn.span.isEnd) break;\n\n return {\n area: lastSubColumnElement.area,\n type: lastSubColumnElement.type,\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n component: lastSubColumnElement.component,\n round: lastSubColumnElement.round,\n match: lastSubColumnElement.match,\n roundSwissGroup: lastSubColumnElement.roundSwissGroup,\n };\n }\n\n return {\n area: `.`,\n type: 'colGap',\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n };\n })();\n\n pushElement(createBracketElement<TRoundData, TMatchData>(elementToCreate));\n }\n\n pushSubColumn(subColumn);\n\n pushSection(masterColumnSection);\n }\n\n return masterColumn;\n};\n","import { BracketRound } from '../../linked';\nimport { CreateBracketGridConfig } from './types';\n\nexport const resolveBracketGridRowSpan = <TRoundData, TMatchData>(\n bracket: { rounds: { values(): Iterable<BracketRound<TRoundData, TMatchData>> } },\n options: CreateBracketGridConfig,\n) => {\n if (!options.rowSpanRoundId) return options;\n\n const round = Array.from(bracket.rounds.values()).find(\n (candidate) =>\n candidate.id === options.rowSpanRoundId || candidate.id.startsWith(`${options.rowSpanRoundId}--half-`),\n );\n\n return round ? { ...options, rowSpanMatchCount: round.matchCount } : options;\n};\n","import { BRACKET_DATA_LAYOUT, COMMON_BRACKET_ROUND_TYPE } from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketSubColumn,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n BracketMasterColumnSection,\n finalizeBracketGrid,\n} from './core';\nimport {\n createBracketContinueMasterColumn,\n createBracketGapMasterColumn,\n createFoldedThirdPlaceSection,\n createRoundBracketSubColumnRelativeToFirstRound,\n getBracketContinueMatches,\n} from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\n// A mirrored grid has no free column for the third place: one between the final and a right half would\n// sit on the straight connector between them.\nconst resolveThirdPlaceTopOffset = (options: CreateBracketGridConfig) => {\n if (options.thirdPlaceTopOffset !== null && options.thirdPlaceTopOffset !== undefined) {\n return options.thirdPlaceTopOffset;\n }\n\n if (options.layout !== BRACKET_DATA_LAYOUT.MIRRORED) return null;\n\n const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n\n return options.finalMatchHeight + options.rowGap + headerOffset;\n};\n\nconst resolveFoldedThirdPlaceRound = <TRoundData, TMatchData>(\n rounds: BracketRound<TRoundData, TMatchData>[],\n topOffset: number | null,\n) => {\n if (topOffset === null) return null;\n if (!rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL)) return null;\n\n return rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null;\n};\n\nconst createSectionTitleBand = <TRoundData, TMatchData>(height: number) => {\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: height,\n partHeights: [height],\n }),\n );\n pushSubColumn(subColumn);\n\n return masterColumnSection;\n};\n\nexport const buildSingleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n titleSpace: number,\n // eslint-disable-next-line max-params -- grid builder signature plus the title band height\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n const rounds = Array.from(bracketData.rounds.values());\n const firstRound = bracketData.rounds.first();\n\n if (!firstRound) {\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, 'No rounds found in bracket data');\n }\n\n const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);\n const thirdPlaceTopOffset = resolveThirdPlaceTopOffset(options);\n const foldedThirdPlaceRound = resolveFoldedThirdPlaceRound(rounds, thirdPlaceTopOffset);\n const ownColumnThirdPlaceRound = foldedThirdPlaceRound\n ? null\n : (rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null);\n const chainRounds = rounds.filter((round) => round !== foldedThirdPlaceRound && round !== ownColumnThirdPlaceRound);\n\n let pushSectionToFinal: ((...sections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => void) | null = null;\n let finalSubColumn: BracketSubColumn<TRoundData, TMatchData> | null = null;\n\n const pushGapColumn = () =>\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n const pushRoundColumn = (round: BracketRound<TRoundData, TMatchData>) => {\n const { masterColumn, ...mutableMasterColumn } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: round.type === COMMON_BRACKET_ROUND_TYPE.FINAL ? options.finalColumnWidth : options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const sub = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound,\n round,\n options: resolvedOptions,\n hasReverseFinal: false,\n span: {\n isStart: true,\n isEnd: true,\n },\n components,\n });\n pushSubColumn(sub);\n\n if (titleSpace) mutableMasterColumn.pushSection(createSectionTitleBand(titleSpace));\n\n mutableMasterColumn.pushSection(masterColumnSection);\n\n grid.pushMasterColumn(masterColumn);\n\n return { pushSection: mutableMasterColumn.pushSection, sub };\n };\n\n for (const [roundIndex, round] of chainRounds.entries()) {\n if (roundIndex > 0) pushGapColumn();\n\n const { pushSection, sub } = pushRoundColumn(round);\n\n if (round.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {\n pushSectionToFinal = pushSection;\n finalSubColumn = sub;\n }\n }\n\n // After the loop, so the gap column beside the final mirrors the final's section alone: the folded\n // round has nothing to its right to stay aligned with.\n if (foldedThirdPlaceRound && pushSectionToFinal && finalSubColumn) {\n pushSectionToFinal(\n createFoldedThirdPlaceSection({\n finalSubColumn,\n round: foldedThirdPlaceRound,\n topOffset: thirdPlaceTopOffset ?? 0,\n options: resolvedOptions,\n components,\n }),\n );\n }\n\n if (options.continueElement && components.continue) {\n const continueMatches = getBracketContinueMatches(bracketData);\n\n if (continueMatches.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n grid.pushMasterColumn(\n createBracketContinueMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnWidth: options.continueElement.columnWidth,\n elementHeight: options.continueElement.elementHeight,\n headerOffset:\n titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),\n component: components.continue,\n matches: continueMatches,\n }),\n );\n }\n }\n\n // After the continue column, so the line from the final to the continue element does not cross it.\n if (ownColumnThirdPlaceRound) {\n if (chainRounds.length) pushGapColumn();\n\n pushRoundColumn(ownColumnThirdPlaceRound);\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n\nexport const createSingleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => buildSingleEliminationGrid(bracketData, options, components, 0);\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../core';\nimport { BracketRound } from '../../linked';\nimport { Dimensions, FinalizedBracketColumn } from './core';\n\nexport const BRACKET_SECTION_KEY = {\n UPPER: 'upper',\n LOWER: 'lower',\n FINALS: 'finals',\n} as const;\n\nexport type BracketSectionKey = (typeof BRACKET_SECTION_KEY)[keyof typeof BRACKET_SECTION_KEY];\n\n/** The English name of each section, for a renderer that brings no labels of its own. */\nexport const BRACKET_SECTION_DEFAULT_NAMES: Record<BracketSectionKey, string> = {\n upper: 'Upper bracket',\n lower: 'Lower bracket',\n finals: 'Finals',\n};\n\n/**\n * One part of a bracket - double elimination's upper bracket, lower bracket or finals - as a grid builder\n * placed it.\n */\nexport type BracketGridSection<TRoundData = unknown, TMatchData = unknown> = {\n key: BracketSectionKey;\n name: string;\n rounds: BracketRound<TRoundData, TMatchData>[];\n /** The box around the section's round headers and matches, from the top of the grid rows it occupies. */\n dimensions: Dimensions;\n /** The band the grid reserved for the section's title, `sectionTitleHeight` high and `sectionTitleGap` above `dimensions`. */\n titleDimensions: Dimensions;\n};\n\n/** The section a double elimination round belongs to: the third place playoff counts as one of the finals. */\nexport const doubleEliminationRoundSection = (round: BracketRound<unknown, unknown>): BracketSectionKey => {\n switch (round.type) {\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET:\n return BRACKET_SECTION_KEY.UPPER;\n\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET:\n return BRACKET_SECTION_KEY.LOWER;\n\n case COMMON_BRACKET_ROUND_TYPE.FINAL:\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL:\n case COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE:\n default:\n return BRACKET_SECTION_KEY.FINALS;\n }\n};\n\n/**\n * Groups a finalized grid's headers and matches into sections and measures each one, with its title band\n * `titleHeight` px high, `titleGap` px above it. A section starts at its `tops` entry, where the grid builder gives one, so the\n * titles of sections that share a row line up; otherwise at its highest element. Sections come in\n * {@link BRACKET_SECTION_KEY} order; an empty one is left out.\n */\nexport const createBracketGridSections = <TRoundData, TMatchData>(config: {\n columns: FinalizedBracketColumn<TRoundData, TMatchData>[];\n sectionOf: (round: BracketRound<TRoundData, TMatchData>) => BracketSectionKey;\n titleHeight: number;\n titleGap?: number;\n tops?: Partial<Record<BracketSectionKey, number>>;\n}): BracketGridSection<TRoundData, TMatchData>[] => {\n const found = new Map<\n BracketSectionKey,\n { rounds: Set<BracketRound<TRoundData, TMatchData>>; top: number; left: number; right: number; bottom: number }\n >();\n\n for (const column of config.columns) {\n for (const element of column.elements) {\n if (element.type === 'continue') continue;\n\n const key = config.sectionOf(element.round);\n const { top, left, width, height } = element.dimensions;\n const box = found.get(key);\n\n if (!box) {\n found.set(key, { rounds: new Set([element.round]), top, left, right: left + width, bottom: top + height });\n continue;\n }\n\n box.rounds.add(element.round);\n box.top = Math.min(box.top, top);\n box.left = Math.min(box.left, left);\n box.right = Math.max(box.right, left + width);\n box.bottom = Math.max(box.bottom, top + height);\n }\n }\n\n return Object.values(BRACKET_SECTION_KEY).flatMap((key) => {\n const box = found.get(key);\n\n if (!box) return [];\n\n const width = box.right - box.left;\n const top = config.tops?.[key] ?? box.top;\n\n return [\n {\n key,\n name: BRACKET_SECTION_DEFAULT_NAMES[key],\n rounds: Array.from(box.rounds),\n dimensions: { top, left: box.left, width, height: box.bottom - top },\n titleDimensions: {\n top: top - (config.titleGap ?? 0) - config.titleHeight,\n left: box.left,\n width,\n height: config.titleHeight,\n },\n },\n ];\n });\n};\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketMasterColumnSection,\n BracketSubColumnSpan,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport {\n calculateColumnSplitFactor,\n calculateLowerRoundIndex,\n calculateUpperLowerRatio,\n calculateUpperRoundIndex,\n} from './double-elimination-utils';\nimport {\n createBracketContinueMasterColumn,\n createBracketGapMasterColumn,\n createRoundBracketSubColumnRelativeToFirstRound,\n getBracketContinueMatches,\n} from './prebuild';\nimport { BRACKET_FINAL_ALIGNMENT, ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { buildSingleEliminationGrid } from './single-elimination';\nimport { createBracketGridSections, doubleEliminationRoundSection } from './sections';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\nconst sectionTitleSpace = (options: { sectionTitleHeight?: number; sectionTitleGap?: number }) =>\n options.sectionTitleHeight ? options.sectionTitleHeight + (options.sectionTitleGap ?? 0) : 0;\n\nconst hasBothSides = <TRoundData, TMatchData>(bracketData: Bracket<TRoundData, TMatchData>) =>\n !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.first() &&\n !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.first();\n\nconst createOneSidedGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const titleSpace = sectionTitleSpace(options);\n const grid = buildSingleEliminationGrid(bracketData, options, components, titleSpace);\n\n return {\n ...grid,\n sections: createBracketGridSections({\n columns: grid.columns,\n sectionOf: doubleEliminationRoundSection,\n titleHeight: options.sectionTitleHeight ?? 0,\n titleGap: options.sectionTitleGap,\n tops: { upper: titleSpace, lower: titleSpace, finals: titleSpace },\n }),\n };\n};\n\nexport const createDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n if (!hasBothSides(bracketData)) return createOneSidedGrid(bracketData, options, components);\n\n const grid = buildDoubleEliminationGrid(bracketData, options, components, new Map());\n\n if (options.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER) return grid;\n\n return {\n ...buildDoubleEliminationGrid(bracketData, options, components, centeredFinalOffsets(bracketData, grid, options)),\n finalAlignment: BRACKET_FINAL_ALIGNMENT.CENTER,\n };\n};\n\nconst matchBlock = <TRoundData, TMatchData>(\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n round: BracketRound<TRoundData, TMatchData> | null | undefined,\n) => {\n if (!round) return null;\n\n let top = Infinity;\n let bottom = -Infinity;\n\n for (const match of round.matches.values()) {\n const element = grid.matchElementMap.get(match.id);\n\n if (!element) continue;\n\n top = Math.min(top, element.dimensions.top);\n bottom = Math.max(bottom, element.dimensions.top + element.dimensions.height);\n }\n\n return top <= bottom ? { top, bottom, center: (top + bottom) / 2 } : null;\n};\n\nconst centeredFinalOffsets = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n // eslint-disable-next-line max-params -- (data, measured grid, options)\n) => {\n const offsets = new Map<string, number>();\n const upperFinal = matchBlock(\n grid,\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.last(),\n );\n const lowerFinal = matchBlock(\n grid,\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.last(),\n );\n\n if (!upperFinal || !lowerFinal) return offsets;\n\n const target = (upperFinal.center + lowerFinal.center) / 2;\n const thirdPlace = matchBlock(grid, bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first());\n const finalRounds = [\n ...(bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.FINAL)?.values() ?? []),\n ...(bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.values() ?? []),\n ];\n\n for (const round of finalRounds) {\n const final = matchBlock(grid, round);\n\n if (!final) continue;\n\n const offset = Math.max(0, target - final.center);\n const room = thirdPlace ? Math.max(0, thirdPlace.top - options.rowGap - final.bottom) : Infinity;\n\n offsets.set(round.id, Math.min(offset, room));\n }\n\n return offsets;\n};\n\nconst buildDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n finalOffsets: ReadonlyMap<string, number>,\n // eslint-disable-next-line max-params -- grid builder signature plus the measured final offsets\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: resolvedOptions.columnWidth });\n const titleSpace = sectionTitleSpace(options);\n\n const presentUpperBracketRounds = Array.from(\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.values() ?? [],\n );\n const lowerBracketRounds = Array.from(\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.values() ?? [],\n );\n\n // A complete winner bracket has (lowerRounds / 2) + 1 rounds. If fewer are present, the winner\n // bracket starts later than round 1 - e.g. a small double elimination where lower-round 1 is\n // seeded directly from a group phase and has no winner round feeding it. Pad the front of the\n // winner rounds with nulls so the column mapping keeps treating the winner bracket as complete:\n // the missing early rounds become empty slots above the lower rounds they never fed, and every\n // present winner round lines up above its real drop-in lower round.\n const fullUpperRoundCount = Math.floor(lowerBracketRounds.length / 2) + 1;\n const frontMissingUpperRounds = Math.max(0, fullUpperRoundCount - presentUpperBracketRounds.length);\n const upperBracketRounds: (BracketRound<TRoundData, TMatchData> | null)[] = [\n ...Array.from({ length: frontMissingUpperRounds }, () => null),\n ...presentUpperBracketRounds,\n ];\n\n const remainingRounds = Array.from(bracketData.rounds.values()).filter(\n (r) =>\n r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET &&\n r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET &&\n r.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,\n );\n\n const thirdPlaceRound = bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first() ?? null;\n const hasReverseFinal = !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.first();\n\n const firstUpperRound = presentUpperBracketRounds[0];\n const firstLowerRound = lowerBracketRounds[0];\n\n if (!firstUpperRound || !firstLowerRound) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.ROUND_RELATION_INVALID,\n 'No upper or lower rounds found in bracket data',\n );\n }\n\n const upperToLowerRatio = calculateUpperLowerRatio(upperBracketRounds.length, lowerBracketRounds.length);\n const columnSplitFactor = calculateColumnSplitFactor(upperToLowerRatio);\n\n /**\n * The winner-bracket half of one column, or the space it would have taken. A front-truncated winner\n * bracket has leading slots with no round in them; reserving their height keeps the lower rounds below\n * aligned with the winner rounds that do exist.\n */\n const createUpperBracketSubColumn = (config: {\n round: BracketRound<TRoundData, TMatchData> | null;\n span: BracketSubColumnSpan;\n }) => {\n if (config.round) {\n return createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstUpperRound,\n round: config.round,\n options: resolvedOptions,\n hasReverseFinal,\n span: config.span,\n components,\n });\n }\n\n const emptyUpperHeight =\n (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0) +\n firstUpperRound.matchCount * options.matchHeight +\n Math.max(0, firstUpperRound.matchCount - 1) * options.rowGap;\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({ span: config.span });\n const element = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: emptyUpperHeight,\n partHeights: [emptyUpperHeight],\n });\n\n pushElement(element);\n\n return subColumn;\n };\n\n /** The breathing room between the winner and loser halves of a column. */\n const createUpperLowerGapSubColumn = () => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n const element = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap + titleSpace,\n partHeights: [options.rowRoundGap + titleSpace],\n });\n\n pushElement(element);\n\n return subColumn;\n };\n\n /** The band above the upper bracket and the finals that holds their section titles. */\n const pushSectionTitleBand = (pushSection: (section: BracketMasterColumnSection<TRoundData, TMatchData>) => void) => {\n if (!titleSpace) return;\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: titleSpace,\n partHeights: [titleSpace],\n }),\n );\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n };\n\n let lastRoundLastSubColumnUpperIndex = -1;\n let lastRoundLastSubColumnLowerIndex = -1;\n\n for (const [lowerRoundIndex, lowerRound] of lowerBracketRounds.entries()) {\n const isLastLowerRound = lowerRoundIndex === lowerBracketRounds.length - 1;\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } =\n createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n for (let currentColumnSplitFactor = 1; currentColumnSplitFactor <= columnSplitFactor; currentColumnSplitFactor++) {\n const subColumnIndex = lowerRoundIndex * columnSplitFactor + (currentColumnSplitFactor - 1);\n\n const currentUpperRoundIndex = calculateUpperRoundIndex(subColumnIndex, upperToLowerRatio, columnSplitFactor);\n const currentLowerRoundIndex = lowerRoundIndex;\n\n const isFirstSubColumnInMasterColumn = currentColumnSplitFactor === 1;\n const isLastSubColumnInMasterColumn = currentColumnSplitFactor === columnSplitFactor;\n\n const previousSubColumnIndex = subColumnIndex - 1;\n const nextSubColumnIndex = subColumnIndex + 1;\n\n const previousUpperRoundIndex =\n previousSubColumnIndex >= 0\n ? calculateUpperRoundIndex(previousSubColumnIndex, upperToLowerRatio, columnSplitFactor)\n : -1;\n const nextUpperRoundIndex = calculateUpperRoundIndex(nextSubColumnIndex, upperToLowerRatio, columnSplitFactor);\n\n const previousLowerRoundIndex =\n previousSubColumnIndex >= 0 ? calculateLowerRoundIndex(previousSubColumnIndex, columnSplitFactor) : -1;\n const nextLowerRoundIndex = calculateLowerRoundIndex(nextSubColumnIndex, columnSplitFactor);\n\n if (currentUpperRoundIndex < 0 || currentUpperRoundIndex >= upperBracketRounds.length) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'Upper round not found for subColumnIndex: ' + subColumnIndex,\n );\n }\n\n // May be null for a leading winner slot that does not exist (front-truncated winner bracket).\n const upperRound = upperBracketRounds[currentUpperRoundIndex];\n\n const isUpperSpanStart = isFirstSubColumnInMasterColumn\n ? lowerRoundIndex === 0 || lastRoundLastSubColumnUpperIndex !== currentUpperRoundIndex\n : previousUpperRoundIndex !== currentUpperRoundIndex;\n\n const isUpperSpanEnd = isLastSubColumnInMasterColumn\n ? isLastLowerRound ||\n calculateUpperRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, upperToLowerRatio, columnSplitFactor) !==\n currentUpperRoundIndex\n : nextUpperRoundIndex !== currentUpperRoundIndex;\n\n const isLowerSpanStart = isFirstSubColumnInMasterColumn\n ? lowerRoundIndex === 0 || lastRoundLastSubColumnLowerIndex !== currentLowerRoundIndex\n : previousLowerRoundIndex !== currentLowerRoundIndex;\n\n const isLowerSpanEnd = isLastSubColumnInMasterColumn\n ? isLastLowerRound ||\n calculateLowerRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, columnSplitFactor) !==\n currentLowerRoundIndex\n : nextLowerRoundIndex !== currentLowerRoundIndex;\n\n const upperSpan = { isStart: isUpperSpanStart, isEnd: isUpperSpanEnd };\n\n pushUpperSubColumn(createUpperBracketSubColumn({ round: upperRound ?? null, span: upperSpan }));\n pushUpperLowerSubColumn(createUpperLowerGapSubColumn());\n\n const lowerSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstLowerRound,\n round: lowerRound,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: isLowerSpanStart,\n isEnd: isLowerSpanEnd,\n },\n components,\n });\n\n pushLowerSubColumn(lowerSubColumn);\n\n if (isLastSubColumnInMasterColumn) {\n lastRoundLastSubColumnUpperIndex = currentUpperRoundIndex;\n lastRoundLastSubColumnLowerIndex = currentLowerRoundIndex;\n }\n }\n\n pushSectionTitleBand(pushSection);\n pushSection(upperSection, upperLowerGapSection, lowerSection);\n\n grid.pushMasterColumn(masterColumn);\n\n // Always separate consecutive lower rounds with a gap column. The trailing gap after the\n // last lower round is only needed to connect to the finals section (remainingRounds); in a\n // truncated bracket without a final we must still gap the intermediate rounds, otherwise the\n // rounds sit flush against each other and their connector lines collapse to zero width.\n if (!isLastLowerRound || remainingRounds.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n for (const [roundIndex, round] of remainingRounds.entries()) {\n const isLastRound = roundIndex === remainingRounds.length - 1;\n const isFirstRound = roundIndex === 0;\n\n const isAnyFinal = hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: isAnyFinal ? options.finalColumnWidth : options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const finalOffset = finalOffsets.get(round.id) ?? 0;\n\n const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } =\n createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n padding: finalOffset ? { top: -finalOffset, bottom: 0, left: 0, right: 0 } : undefined,\n });\n\n const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const upperSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstUpperRound,\n round,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: true,\n isEnd: true,\n },\n components,\n topPadding: finalOffset,\n });\n\n pushUpperSubColumn(upperSubColumn);\n\n const upperLowerGapSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const upperLowerGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap + titleSpace,\n partHeights: [options.rowRoundGap + titleSpace],\n });\n\n upperLowerGapSubColumn.pushElement(upperLowerGapElement);\n\n pushUpperLowerSubColumn(upperLowerGapSubColumn.subColumn);\n\n if (thirdPlaceRound) {\n const lowerSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstLowerRound,\n round: thirdPlaceRound,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: isFirstRound,\n isEnd: isLastRound,\n },\n components,\n });\n\n pushLowerSubColumn(lowerSubColumn);\n } else {\n const lowerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const firstMasterRound = grid.grid.masterColumns[0];\n\n if (!firstMasterRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No first master round found in grid');\n\n const lastMasterColumnSection = firstMasterRound.sections[firstMasterRound.sections.length - 1];\n\n if (!lastMasterColumnSection)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No last master column section found in grid');\n\n const firstSubColumn = lastMasterColumnSection.subColumns[0];\n\n if (!firstSubColumn)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No first sub column found in grid');\n\n for (const element of firstSubColumn.elements) {\n const el = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: element.dimensions.height,\n partHeights: element.parts.map((p) => p.dimensions.height),\n });\n\n lowerSubColumn.pushElement(el);\n }\n\n pushLowerSubColumn(lowerSubColumn.subColumn);\n }\n\n pushSectionTitleBand(pushSection);\n pushSection(upperSection, upperLowerGapSection, lowerSection);\n\n grid.pushMasterColumn(masterColumn);\n\n if (!isLastRound) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n if (options.continueElement && components.continue) {\n const continueMatches = getBracketContinueMatches(bracketData);\n\n if (continueMatches.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n grid.pushMasterColumn(\n createBracketContinueMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnWidth: options.continueElement.columnWidth,\n elementHeight: options.continueElement.elementHeight,\n headerOffset:\n titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),\n component: components.continue,\n matches: continueMatches,\n }),\n );\n }\n }\n\n grid.setupElementSpans();\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n const [upperRows, lowerRows] =\n grid.grid.masterColumns[0]?.sections.filter((section) => section.type === 'round') ?? [];\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n sections: createBracketGridSections({\n columns: finalizedGrid.columns,\n sectionOf: doubleEliminationRoundSection,\n titleHeight: options.sectionTitleHeight ?? 0,\n titleGap: options.sectionTitleGap,\n tops: {\n upper: upperRows?.dimensions.top,\n lower: lowerRows?.dimensions.top,\n finals: upperRows?.dimensions.top,\n },\n }),\n };\n};\n","import {\n BRACKET_ROUND_MIRROR_TYPE,\n BracketRoundType,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n} from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport { createBracketGapMasterColumn, createRoundBracketSubColumnRelativeToFirstRound } from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { createSingleEliminationGrid } from './single-elimination';\n\nconst CENTRE_CHAIN_ORDER: Partial<Record<string, number>> = {\n final: 1,\n 'reverse-final': 2,\n 'third-place': 3,\n};\n\ntype StackedBlock<TRoundData, TMatchData> = {\n firstRound: BracketRound<TRoundData, TMatchData>;\n /** Outermost first. */\n left: BracketRound<TRoundData, TMatchData>[];\n /** Innermost first. */\n right: BracketRound<TRoundData, TMatchData>[];\n /** Top to bottom from the round both halves converge on; empty when they never meet. */\n chain: BracketRound<TRoundData, TMatchData>[];\n options: CreateBracketGridConfig;\n body: number;\n columnContent: (round: BracketRound<TRoundData, TMatchData>) => number;\n spacerTop: number;\n spacerBottom: number;\n};\n\ntype StackedBlockConfig<TRoundData, TMatchData> = {\n rounds: BracketRound<TRoundData, TMatchData>[];\n options: CreateBracketGridConfig;\n hasReverseFinal: boolean;\n};\n\nconst isFinalMatchRound = <TRoundData, TMatchData>(\n round: BracketRound<TRoundData, TMatchData>,\n hasReverseFinal: boolean,\n) =>\n hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\nconst chainRoundHeight = <TRoundData, TMatchData>(config: {\n round: BracketRound<TRoundData, TMatchData>;\n options: CreateBracketGridConfig;\n hasReverseFinal: boolean;\n}) => {\n const { round, options, hasReverseFinal } = config;\n const cardHeight = isFinalMatchRound(round, hasReverseFinal) ? options.finalMatchHeight : options.matchHeight;\n\n return round.matchCount * cardHeight + Math.max(0, round.matchCount - 1) * options.rowGap;\n};\n\nconst createStackedBlock = <TRoundData, TMatchData>(\n config: StackedBlockConfig<TRoundData, TMatchData>,\n): StackedBlock<TRoundData, TMatchData> | null => {\n const { rounds, hasReverseFinal } = config;\n const options = resolveBracketGridRowSpan({ rounds }, config.options);\n\n const halves = rounds.filter((round) => !!round.mirrorRoundType);\n const left = halves\n .filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT)\n .sort((a, b) => a.logicalIndex - b.logicalIndex);\n const right = halves\n .filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT)\n .sort((a, b) => b.logicalIndex - a.logicalIndex);\n\n const middles = rounds\n .filter((round) => !round.mirrorRoundType)\n .sort(\n (a, b) =>\n (CENTRE_CHAIN_ORDER[a.type] ?? 0) - (CENTRE_CHAIN_ORDER[b.type] ?? 0) || a.logicalIndex - b.logicalIndex,\n );\n\n // Where the two halves meet: one depth past the innermost round that had a second half to fold against.\n const foldDepth = left.length ? Math.max(...left.map((round) => round.logicalIndex)) + 1 : 0;\n\n // An odd early round could not halve, so it has no twin on the way back and keeps a slot of its own on\n // the way out rather than sitting in a middle it is far too wide for.\n const isEarly = (round: BracketRound<TRoundData, TMatchData>) =>\n !CENTRE_CHAIN_ORDER[round.type] && round.logicalIndex < foldDepth;\n\n const leftSlots = [...left, ...middles.filter(isEarly)].sort((a, b) => a.logicalIndex - b.logicalIndex);\n const chain = middles.filter((round) => !isEarly(round));\n\n const firstRound = leftSlots[0] ?? chain[0];\n\n if (!firstRound) return null;\n\n const rows = options.rowSpanMatchCount ?? firstRound.matchCount;\n const rowsHeight = (count: number) => count * options.matchHeight + Math.max(0, count - 1) * options.rowGap;\n const content = rowsHeight(rows);\n const columnContent = (round: BracketRound<TRoundData, TMatchData>) => rowsHeight(Math.max(rows, round.matchCount));\n\n let chainHeight = 0;\n\n for (const [index, round] of chain.entries()) {\n chainHeight += (index ? options.rowRoundGap : 0) + chainRoundHeight({ round, options, hasReverseFinal });\n }\n const anchorHeight = chain[0] ? chainRoundHeight({ round: chain[0], options, hasReverseFinal }) : 0;\n\n // The round both halves converge on sits on the block's vertical centre, which is where the two halves'\n // own matches sit - so the connectors into it stay straight. A chain too long to hang under it from\n // there grows the block rather than sliding up: an anchor a few px off centre turns every one of those\n // connectors into a diagonal, in a drawing where nothing else is.\n const spacerTop = Math.max(0, (content - anchorHeight) / 2);\n const body = Math.max(spacerTop + chainHeight, ...[...leftSlots, ...right].map(columnContent));\n\n return {\n firstRound,\n left: leftSlots,\n right,\n chain,\n options,\n body,\n columnContent,\n spacerTop,\n spacerBottom: Math.max(0, body - spacerTop - chainHeight),\n };\n};\n\n/**\n * Draws a double elimination as two mirrored blocks, one above the other: the winners bracket folded\n * around its own centre, the losers bracket folded around its own, and nothing but a gap between them.\n * Each block's deciding rounds hang vertically below the round its two halves converge on.\n */\nexport const createStackedDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n\n const roundsOfType = (type: BracketRoundType) => Array.from(bracketData.roundsByType.get(type)?.values() ?? []);\n\n const hasReverseFinal = !!roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL).length;\n\n const winners = createStackedBlock({\n rounds: [\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET),\n ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.FINAL),\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL),\n ],\n options,\n hasReverseFinal,\n });\n\n const losers = createStackedBlock({\n rounds: [\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET),\n ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE),\n ],\n options,\n hasReverseFinal,\n });\n\n if (!winners || !losers) return createSingleEliminationGrid(bracketData, options, components);\n\n const blocks = [winners, losers];\n const headerBlock = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n const blockHeight = (block: StackedBlock<TRoundData, TMatchData>) => headerBlock + block.body;\n\n const centreIndex = Math.max(...blocks.map((block) => block.left.length));\n const columnCount = centreIndex + 1 + Math.max(...blocks.map((block) => block.right.length));\n\n const createPlaceholderSubColumn = (block: StackedBlock<TRoundData, TMatchData>) => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n const height = blockHeight(block);\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: height,\n partHeights: [height],\n }),\n );\n\n return subColumn;\n };\n\n const createChainSubColumn = (block: StackedBlock<TRoundData, TMatchData>) => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n const anchor = block.chain[0];\n\n if (!anchor) return createPlaceholderSubColumn(block);\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n // One header for the whole chain, naming the round its two halves converge on. The rounds below it\n // are a vertical run of single matches; a header between each would sit on the line joining them.\n if (options.roundHeaderHeight > 0) {\n elementsToCreate.push(\n {\n type: 'header',\n area: `h${anchor.shortId}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: components.roundHeader,\n round: anchor,\n roundSwissGroup: null,\n },\n {\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [options.roundHeaderGap],\n elementHeight: options.roundHeaderGap,\n },\n );\n }\n\n if (block.spacerTop > 0) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [block.spacerTop],\n elementHeight: block.spacerTop,\n });\n }\n\n for (const [roundIndex, round] of block.chain.entries()) {\n if (roundIndex) {\n elementsToCreate.push({\n type: 'roundGap',\n area: '.',\n partHeights: [options.rowRoundGap],\n elementHeight: options.rowRoundGap,\n });\n }\n\n const isFinalCard = isFinalMatchRound(round, hasReverseFinal);\n const cardHeight = isFinalCard ? options.finalMatchHeight : options.matchHeight;\n\n for (const [matchIndex, match] of Array.from(round.matches.values()).entries()) {\n if (matchIndex) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [options.rowGap],\n elementHeight: options.rowGap,\n });\n }\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: [cardHeight],\n elementHeight: cardHeight,\n component: isFinalCard ? components.finalMatch : components.match,\n match,\n round,\n roundSwissGroup: null,\n });\n }\n }\n\n if (block.spacerBottom > 0) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [block.spacerBottom],\n elementHeight: block.spacerBottom,\n });\n }\n\n for (const elementData of elementsToCreate) {\n pushElement(createBracketElement<TRoundData, TMatchData>(elementData));\n }\n\n return subColumn;\n };\n\n const createBlockSubColumn = (block: StackedBlock<TRoundData, TMatchData>, columnIndex: number) => {\n const slotIndex = columnIndex - (centreIndex - block.left.length);\n\n if (slotIndex === block.left.length) return createChainSubColumn(block);\n\n const round =\n slotIndex >= 0 && slotIndex < block.left.length\n ? block.left[slotIndex]\n : block.right[slotIndex - block.left.length - 1];\n\n if (!round) return createPlaceholderSubColumn(block);\n\n return createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: block.firstRound,\n round,\n options: block.options,\n hasReverseFinal,\n bottomPadding: block.body - block.columnContent(round),\n span: { isStart: true, isEnd: true },\n components,\n });\n };\n\n const createBandSubColumn = () => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap,\n partHeights: [options.rowRoundGap],\n }),\n );\n\n return subColumn;\n };\n\n for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: columnIndex === centreIndex ? options.finalColumnWidth : options.columnWidth,\n padding: { bottom: 0, left: 0, right: 0, top: 0 },\n });\n\n const winnersSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'round' });\n const bandSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'gap' });\n const losersSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'round' });\n\n winnersSection.pushSubColumn(createBlockSubColumn(winners, columnIndex));\n bandSection.pushSubColumn(createBandSubColumn());\n losersSection.pushSubColumn(createBlockSubColumn(losers, columnIndex));\n\n pushSection(winnersSection.masterColumnSection, bandSection.masterColumnSection, losersSection.masterColumnSection);\n\n grid.pushMasterColumn(masterColumn);\n\n if (columnIndex < columnCount - 1) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n","import {\n BracketMatchId,\n BracketMatchPosition,\n BracketRoundId,\n BracketWarning,\n COMMON_BRACKET_ROUND_TYPE,\n} from '../core';\nimport { BracketMatchOutcomeSlotSource, BracketMatchSource } from '../integrations';\nimport { Bracket, BracketMatch, BracketRound } from './bracket';\nimport { BracketRoundRelation } from './round-relations';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nconst FALLBACK_MATCH_RELATION_POSITION = -1 as BracketMatchPosition;\n\n// Will usually be 0.5, 1 or 2. In Swiss this value will be gibberish\nexport type BracketMatchFactor = number;\n\n// One match has one previous match and one next match (this would be the case, if a group tournament is being displayed via a bracket)\nexport type BracketMatchRelationOneToOne<TRoundData, TMatchData> = {\n type: 'one-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousMatch: BracketMatch<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has no previous match but a single next match (eg. the start of the bracket)\nexport type BracketMatchRelationNothingToOne<TRoundData, TMatchData> = {\n type: 'nothing-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has no next match but a single previous match (eg. reverse finals)\nexport type BracketMatchRelationOneToNothing<TRoundData, TMatchData> = {\n type: 'one-to-nothing';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousMatch: BracketMatch<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has two previous matches and one next match (eg. a normal match in the bracket that is neither the start nor the end)\nexport type BracketMatchRelationTwoToOne<TRoundData, TMatchData> = {\n type: 'two-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperMatch: BracketMatch<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerMatch: BracketMatch<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has two previous matches and no next match (eg. the finals in a single elimination bracket)\nexport type BracketMatchRelationTwoToNothing<TRoundData, TMatchData> = {\n type: 'two-to-nothing';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperMatch: BracketMatch<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerMatch: BracketMatch<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketMatchRelationNone<TRoundData, TMatchData> = {\n type: 'none';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketMatchRelation<TRoundData, TMatchData> =\n | BracketMatchRelationNone<TRoundData, TMatchData>\n | BracketMatchRelationOneToOne<TRoundData, TMatchData>\n | BracketMatchRelationTwoToOne<TRoundData, TMatchData>\n | BracketMatchRelationNothingToOne<TRoundData, TMatchData>\n | BracketMatchRelationOneToNothing<TRoundData, TMatchData>\n | BracketMatchRelationTwoToNothing<TRoundData, TMatchData>;\n\nexport type MatchPositionMaps<TRoundData, TMatchData> = Map<\n BracketRoundId,\n Map<BracketMatchPosition, BracketMatch<TRoundData, TMatchData>>\n>;\n\nexport const generateMatchPosition = (\n match: BracketMatch<unknown, unknown>,\n factor: BracketMatchFactor,\n): BracketMatchPosition => Math.ceil(match.position * factor) as BracketMatchPosition;\n\nconst generatePreviousRoundMatchPositions = <TRoundData, TMatchData>(\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-one' | 'one-to-nothing' }>,\n match: BracketMatch<TRoundData, TMatchData>,\n) => {\n const feederFactor = relation.currentRound.matchCount / relation.previousRound.matchCount;\n const feederPositions: BracketMatchPosition[] = [];\n\n for (const feeder of relation.previousRound.matches.values()) {\n if (generateMatchPosition(feeder, feederFactor) === match.position) feederPositions.push(feeder.position);\n }\n\n const first = feederPositions[0];\n const last = feederPositions[feederPositions.length - 1];\n\n if (first !== undefined && last !== undefined) {\n return { previousUpperRoundMatchPosition: first, previousLowerRoundMatchPosition: last };\n }\n\n const double = relation.previousRoundMatchFactor === 2 ? 1 : 0;\n\n return {\n previousUpperRoundMatchPosition: (generateMatchPosition(match, relation.previousRoundMatchFactor) -\n double) as BracketMatchPosition,\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousRoundMatchFactor),\n };\n};\n\nexport const generateMatchRelationPositions = <TRoundData, TMatchData>(\n relation: BracketRoundRelation<TRoundData, TMatchData>,\n match: BracketMatch<TRoundData, TMatchData>,\n) => {\n switch (relation.type) {\n case 'none':\n return null;\n\n case 'nothing-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n previousUpperRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n previousLowerRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n };\n\n case 'one-to-nothing':\n return {\n nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n ...generatePreviousRoundMatchPositions(relation, match),\n };\n\n case 'one-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n ...generatePreviousRoundMatchPositions(relation, match),\n };\n\n case 'two-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor),\n };\n\n case 'two-to-nothing':\n return {\n nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor),\n };\n }\n};\n\nconst relationMatchNotFound = (options: {\n match: { id: string; round: { id: string } };\n feeder: string;\n round: { id: string };\n position: BracketMatchPosition;\n}) =>\n new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match \"${options.match.id}\" in round \"${options.match.round.id}\" has no ${options.feeder} match at position ${options.position} of round \"${options.round.id}\". Check the match counts of both rounds, or declare homeSource/awaySource.`,\n );\n\nconst createNothingToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'nothing-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationNothingToOne<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, nextRoundMatchPosition } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n\n return {\n type: 'nothing-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n};\n\nconst createOneToNothingOrTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-nothing' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}):\n | BracketMatchRelationOneToNothing<TRoundData, TMatchData>\n | BracketMatchRelationTwoToNothing<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } =\n params;\n\n const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);\n\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous',\n round: relation.previousRound,\n position: previousUpperRoundMatchPosition,\n });\n\n if (previousUpperRoundMatchPosition !== previousLowerRoundMatchPosition) {\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousRound,\n previousLowerMatch,\n previousLowerRound: relation.previousRound,\n };\n } else {\n return {\n type: 'one-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousMatch: previousUpperMatch,\n previousRound: relation.previousRound,\n };\n }\n};\n\nconst createOneToOneOrTwoToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationOneToOne<TRoundData, TMatchData> | BracketMatchRelationTwoToOne<TRoundData, TMatchData> => {\n const {\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousRound,\n position: previousLowerRoundMatchPosition,\n });\n\n if (previousUpperRoundMatchPosition === previousLowerRoundMatchPosition) {\n return {\n type: 'one-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousMatch: previousUpperMatch,\n previousRound: relation.previousRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n } else {\n return {\n type: 'two-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousRound,\n previousLowerMatch,\n previousLowerRound: relation.previousRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n }\n};\n\nconst createTwoToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'two-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationTwoToOne<TRoundData, TMatchData> => {\n const {\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n const previousUpperMatch = matchPositionMaps\n .get(relation.previousUpperRound.id)\n ?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps\n .get(relation.previousLowerRound.id)\n ?.get(previousLowerRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousUpperRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousLowerRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousUpperRound,\n previousLowerMatch,\n previousLowerRound: relation.previousLowerRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n};\n\nconst createTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'two-to-nothing' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationTwoToNothing<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } =\n params;\n\n const previousUpperMatch = matchPositionMaps\n .get(relation.previousUpperRound.id)\n ?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps\n .get(relation.previousLowerRound.id)\n ?.get(previousLowerRoundMatchPosition);\n\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousUpperRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousLowerRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousUpperRound,\n previousLowerMatch,\n previousLowerRound: relation.previousLowerRound,\n };\n};\n\nexport const generateMatchRelationsNew = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: {\n source?: { matches: BracketMatchSource<TMatchData>[] };\n previousMatchIds?: (match: BracketMatchSource<TMatchData>) => string[];\n onWarning?: (warning: BracketWarning) => void;\n } = {},\n): BracketMatchRelation<TRoundData, TMatchData>[] => {\n const sourceMatches = options.source?.matches ?? [];\n const hasDeclaredGraph =\n options.previousMatchIds !== undefined || sourceMatches.some((match) => matchOutcomeSlots(match).length > 0);\n\n if (hasDeclaredGraph) {\n return generateDeclaredMatchRelations({\n bracket: bracketData,\n sourceMatches,\n previousMatchIds: options.previousMatchIds ?? defaultPreviousMatchIds,\n onWarning: options.onWarning,\n });\n }\n\n const matchRelations: BracketMatchRelation<TRoundData, TMatchData>[] = [];\n const matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData> = new Map();\n\n for (const round of bracketData.rounds.values()) {\n const matchMap = new Map([...round.matches.values()].map((m) => [m.position, m]));\n matchPositionMaps.set(round.id, matchMap);\n }\n\n for (const match of bracketData.matches.values()) {\n const relation = match.round.relation;\n\n const positions = generateMatchRelationPositions(relation, match);\n\n if (!positions) continue;\n\n const { nextRoundMatchPosition, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = positions;\n\n switch (relation.type) {\n case 'nothing-to-one':\n matchRelations.push(\n createNothingToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n }),\n );\n break;\n\n case 'one-to-nothing':\n matchRelations.push(\n createOneToNothingOrTwoToNothingRelation({\n match,\n relation,\n matchPositionMaps,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'one-to-one':\n matchRelations.push(\n createOneToOneOrTwoToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'two-to-one':\n matchRelations.push(\n createTwoToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'two-to-nothing':\n matchRelations.push(\n createTwoToNothingRelation({\n match,\n relation,\n matchPositionMaps,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n }\n }\n\n return matchRelations;\n};\n\nconst matchOutcomeSlots = <TMatchData>(match: BracketMatchSource<TMatchData>) =>\n [match.homeSource, match.awaySource].filter(\n (slot): slot is BracketMatchOutcomeSlotSource => slot?.kind === 'match-outcome' && !!slot.matchId,\n );\n\nconst defaultPreviousMatchIds = <TMatchData>(match: BracketMatchSource<TMatchData>): string[] =>\n matchOutcomeSlots(match)\n .filter((slot) => slot.role !== 'loser')\n .map((slot) => slot.matchId);\n\nconst reportDeclaredGraphWarnings = <TRoundData, TMatchData>(options: {\n bracket: Bracket<TRoundData, TMatchData>;\n sourceMatches: BracketMatchSource<TMatchData>[];\n previousByMatchId: Map<string, string[]>;\n onWarning: (warning: BracketWarning) => void;\n}) => {\n const { bracket, sourceMatches, previousByMatchId, onWarning } = options;\n const feederIds = new Set<string>();\n\n for (const match of sourceMatches) {\n const referenced = new Set([\n ...(previousByMatchId.get(match.id) ?? []),\n ...matchOutcomeSlots(match).map((slot) => slot.matchId),\n ]);\n\n for (const feederId of referenced) {\n feederIds.add(feederId);\n\n if (bracket.matches.has(feederId as BracketMatchId)) continue;\n\n onWarning({\n type: 'unknown-feeder',\n matchId: match.id,\n feederId,\n message: `Match \"${match.id}\" is fed by \"${feederId}\", which is not in source.matches. The connector is not drawn.`,\n });\n }\n }\n\n if (sourceMatches.length < 2) return;\n\n for (const match of sourceMatches) {\n const declaresFeeders =\n (previousByMatchId.get(match.id)?.length ?? 0) > 0 ||\n matchOutcomeSlots(match).length > 0 ||\n [match.homeSource, match.awaySource].some((slot) => slot?.kind === 'unknown');\n\n if (declaresFeeders || feederIds.has(match.id)) continue;\n if (bracket.matches.get(match.id as BracketMatchId)?.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;\n\n onWarning({\n type: 'unlinked-match',\n matchId: match.id,\n message: `Match \"${match.id}\" declares no feeders and feeds no match. A source with any match-outcome slot (or a previousMatchIds option) is linked only from what it declares, so give every match its homeSource/awaySource.`,\n });\n }\n};\n\nconst generateDeclaredMatchRelations = <TRoundData, TMatchData>(options: {\n bracket: Bracket<TRoundData, TMatchData>;\n sourceMatches: BracketMatchSource<TMatchData>[];\n previousMatchIds: (match: BracketMatchSource<TMatchData>) => string[];\n onWarning?: (warning: BracketWarning) => void;\n}): BracketMatchRelation<TRoundData, TMatchData>[] => {\n const { bracket, sourceMatches, previousMatchIds, onWarning } = options;\n const previousByMatchId = new Map(sourceMatches.map((match) => [match.id, previousMatchIds(match)]));\n\n if (onWarning) reportDeclaredGraphWarnings({ bracket, sourceMatches, previousByMatchId, onWarning });\n const nextByMatchId = new Map<string, string>();\n\n // A match can feed two: a semi final feeds the final with its winner and the third place match with\n // its loser. The winner is where the match leads, so it wins over whatever the source happens to list\n // first - without this, `nextMatch` answers \"where does this winner go\" from array order.\n const winnerConsumerByFeederId = new Map<string, string>();\n\n for (const match of sourceMatches) {\n for (const slot of [match.homeSource, match.awaySource]) {\n if (slot?.kind !== 'match-outcome' || slot.role === 'loser' || !slot.matchId) continue;\n if (!winnerConsumerByFeederId.has(slot.matchId)) winnerConsumerByFeederId.set(slot.matchId, match.id);\n }\n }\n\n for (const [matchId, feederIds] of previousByMatchId) {\n for (const feederId of feederIds) {\n if (winnerConsumerByFeederId.get(feederId) === matchId) nextByMatchId.set(feederId, matchId);\n else if (!nextByMatchId.has(feederId)) nextByMatchId.set(feederId, matchId);\n }\n }\n\n const relations: BracketMatchRelation<TRoundData, TMatchData>[] = [];\n\n for (const match of bracket.matches.values()) {\n const previousMatches = (previousByMatchId.get(match.id) ?? [])\n .map((id) => bracket.matches.get(id as BracketMatchId))\n .filter((candidate): candidate is BracketMatch<TRoundData, TMatchData> => candidate !== undefined);\n const nextMatchId = nextByMatchId.get(match.id);\n const nextMatch = nextMatchId ? bracket.matches.get(nextMatchId as BracketMatchId) : undefined;\n\n if (previousMatches.length === 0 && nextMatch) {\n relations.push({\n type: 'nothing-to-one',\n currentMatch: match,\n currentRound: match.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length === 1 && nextMatch) {\n const previousMatch = previousMatches[0];\n\n if (!previousMatch) continue;\n\n relations.push({\n type: 'one-to-one',\n currentMatch: match,\n currentRound: match.round,\n previousMatch,\n previousRound: previousMatch.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length >= 2 && nextMatch) {\n const previousUpperMatch = previousMatches[0];\n const previousLowerMatch = previousMatches[1];\n\n if (!previousUpperMatch || !previousLowerMatch) continue;\n\n relations.push({\n type: 'two-to-one',\n currentMatch: match,\n currentRound: match.round,\n previousUpperMatch,\n previousUpperRound: previousUpperMatch.round,\n previousLowerMatch,\n previousLowerRound: previousLowerMatch.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length === 1) {\n const previousMatch = previousMatches[0];\n\n if (!previousMatch) continue;\n\n relations.push({\n type: 'one-to-nothing',\n currentMatch: match,\n currentRound: match.round,\n previousMatch,\n previousRound: previousMatch.round,\n });\n } else if (previousMatches.length >= 2) {\n const previousUpperMatch = previousMatches[0];\n const previousLowerMatch = previousMatches[1];\n\n if (!previousUpperMatch || !previousLowerMatch) continue;\n\n relations.push({\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: match.round,\n previousUpperMatch,\n previousUpperRound: previousUpperMatch.round,\n previousLowerMatch,\n previousLowerRound: previousLowerMatch.round,\n });\n }\n }\n\n return relations;\n};\n","import { BRACKET_ROUND_MIRROR_TYPE, COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../core';\nimport { Bracket, BracketRound } from './bracket';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\n// One round has one next round (the first round of the bracket)\nexport type BracketRoundRelationNothingToOne<TRoundData, TMatchData> = {\n type: 'nothing-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n};\n\n// One round has one previous round (eg. the finals round of the bracket in case of a single elimination bracket)\nexport type BracketRoundRelationOneToNothing<TRoundData, TMatchData> = {\n type: 'one-to-nothing';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n previousRoundMatchFactor: number;\n rootRoundMatchFactor: number;\n};\n\n// One round has one previous round and one next round (eg. a normal round in the bracket that is neither the start nor the end)\nexport type BracketRoundRelationOneToOne<TRoundData, TMatchData> = {\n type: 'one-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n previousRoundMatchFactor: number;\n rootRoundMatchFactor: number;\n};\n\n// One round has two previous rounds and one next round (eg. the finals round in a double elimination bracket when the reverse finals is also being played)\nexport type BracketRoundRelationTwoToOne<TRoundData, TMatchData> = {\n type: 'two-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n previousUpperRoundMatchFactor: number;\n previousLowerRoundMatchFactor: number;\n upperRootRoundMatchFactor: number;\n lowerRootRoundMatchFactor: number;\n};\n\n// One round has two previous rounds and no next round (eg. the finals round in a double elimination bracket when the reverse finals is not being played)\nexport type BracketRoundRelationTwoToNothing<TRoundData, TMatchData> = {\n type: 'two-to-nothing';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRoundMatchFactor: number;\n previousLowerRoundMatchFactor: number;\n upperRootRoundMatchFactor: number;\n lowerRootRoundMatchFactor: number;\n};\n\nexport type BracketRoundRelationNone<TRoundData, TMatchData> = {\n type: 'none';\n currentRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketRoundRelation<TRoundData, TMatchData> =\n | BracketRoundRelationNone<TRoundData, TMatchData>\n | BracketRoundRelationNothingToOne<TRoundData, TMatchData>\n | BracketRoundRelationOneToNothing<TRoundData, TMatchData>\n | BracketRoundRelationOneToOne<TRoundData, TMatchData>\n | BracketRoundRelationTwoToOne<TRoundData, TMatchData>\n | BracketRoundRelationTwoToNothing<TRoundData, TMatchData>;\n\nconst calculateMatchFactor = <TRoundData, TMatchData>(\n numeratorRound: BracketRound<TRoundData, TMatchData>,\n denominatorRound: BracketRound<TRoundData, TMatchData>,\n) => numeratorRound.matchCount / denominatorRound.matchCount;\n\nconst createNothingToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationNothingToOne<TRoundData, TMatchData> => ({\n type: 'nothing-to-one',\n currentRound: params.currentRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n});\n\nconst createOneToNothingRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n rootRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationOneToNothing<TRoundData, TMatchData> => ({\n type: 'one-to-nothing',\n currentRound: params.currentRound,\n previousRound: params.previousRound,\n previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),\n rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound),\n});\n\nconst createOneToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n rootRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationOneToOne<TRoundData, TMatchData> => ({\n type: 'one-to-one',\n currentRound: params.currentRound,\n previousRound: params.previousRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),\n rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound),\n});\n\nconst createTwoToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationTwoToOne<TRoundData, TMatchData> => ({\n type: 'two-to-one',\n currentRound: params.currentRound,\n previousUpperRound: params.previousUpperRound,\n previousLowerRound: params.previousLowerRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),\n previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),\n upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),\n lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound),\n});\n\nconst createTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationTwoToNothing<TRoundData, TMatchData> => ({\n type: 'two-to-nothing',\n currentRound: params.currentRound,\n previousUpperRound: params.previousUpperRound,\n previousLowerRound: params.previousLowerRound,\n previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),\n previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),\n upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),\n lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound),\n});\n\n/** A round drawn on the way back from the middle of a mirrored bracket. */\nconst isFoldedBackRound = <TRoundData, TMatchData>(round: BracketRound<TRoundData, TMatchData>) =>\n round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;\n\n/** One bracket's rounds keyed by depth, with the two sides of a fold kept apart. */\ntype BracketRoundsByDepth<TRoundData, TMatchData> = Map<\n number,\n {\n left: BracketRound<TRoundData, TMatchData> | null;\n right: BracketRound<TRoundData, TMatchData> | null;\n /** The round at this depth that was never folded - the middle of a mirrored bracket. */\n single: BracketRound<TRoundData, TMatchData> | null;\n }\n>;\n\nconst buildRoundsByDepth = <TRoundData, TMatchData>(\n rounds: BracketRound<TRoundData, TMatchData>[],\n): BracketRoundsByDepth<TRoundData, TMatchData> => {\n const byDepth: BracketRoundsByDepth<TRoundData, TMatchData> = new Map();\n\n for (const round of rounds) {\n const slot = byDepth.get(round.logicalIndex) ?? { left: null, right: null, single: null };\n\n if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT) slot.left = round;\n else if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT) slot.right = round;\n else slot.single = round;\n\n byDepth.set(round.logicalIndex, slot);\n }\n\n return byDepth;\n};\n\n/**\n * The round one depth along on the same side of the fold - or, where the fold has closed because that\n * depth was too small to halve, the whole round sitting in the middle.\n */\nconst roundAtDepth = <TRoundData, TMatchData>(params: {\n byDepth: BracketRoundsByDepth<TRoundData, TMatchData>;\n depth: number;\n side: BracketRound<TRoundData, TMatchData>['mirrorRoundType'];\n}) => {\n const slot = params.byDepth.get(params.depth);\n\n if (!slot) return null;\n\n const sameSide = params.side === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? slot.right : slot.left;\n\n return sameSide ?? slot.single ?? null;\n};\n\nconst getNavigationContext = <TRoundData, TMatchData>(params: {\n upperRounds: BracketRound<TRoundData, TMatchData>[];\n upperRoundsByDepth: BracketRoundsByDepth<TRoundData, TMatchData>;\n currentUpperRoundIndex: number;\n}) => {\n const { upperRounds, upperRoundsByDepth, currentUpperRoundIndex } = params;\n const currentUpperRound = upperRounds[currentUpperRoundIndex];\n\n if (!currentUpperRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, 'currentUpperRound is null');\n\n const isLeftToRight =\n !currentUpperRound.mirrorRoundType || currentUpperRound.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT;\n\n // A folded half follows the fold, not the array. Its neighbours are the rounds one depth away on its\n // own side, because the array puts a right half next to whatever happened to be emitted beside it -\n // in a double elimination that is the grand final rather than the round it actually feeds.\n const isFolded = !!currentUpperRound.mirrorRoundType;\n const side = currentUpperRound.mirrorRoundType;\n const depth = currentUpperRound.logicalIndex;\n\n const relativePrevious = isFolded\n ? roundAtDepth({ byDepth: upperRoundsByDepth, depth: depth - 1, side })\n : upperRounds[currentUpperRoundIndex - 1] || null;\n const relativeNext = isFolded\n ? roundAtDepth({ byDepth: upperRoundsByDepth, depth: depth + 1, side })\n : upperRounds[currentUpperRoundIndex + 1] || null;\n\n // A folded half already resolved its own direction, so the swap that turns array order into flow\n // order for a right-hand round must not be applied twice.\n const previousUpperRound = isFolded || isLeftToRight ? relativePrevious : relativeNext;\n const flowNext = isFolded || isLeftToRight ? relativeNext : relativePrevious;\n\n // An unfolded round sits in the middle of the fold, so a right half beside it in the array feeds it\n // rather than following it.\n const nextUpperRound = !isFolded && flowNext?.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? null : flowNext;\n\n const isLastUpperRound = !nextUpperRound;\n\n const isFinal = currentUpperRound.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n return {\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n isLastUpperRound,\n isFinal,\n };\n};\n\nconst handleFinalRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData> | null;\n /** The lower bracket as it is played, one round per depth - see `lowerFlow`. */\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n lastLowerRound: BracketRound<TRoundData, TMatchData>;\n}) => {\n const {\n relations,\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n lowerRounds,\n firstUpperRound,\n firstLowerRound,\n lastLowerRound,\n } = params;\n\n const finalLowerRound = lastLowerRound;\n const isAsyncBracket = nextUpperRound?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL;\n\n if (nextUpperRound) {\n relations.push(\n createTwoToOneRelation({\n currentRound: currentUpperRound,\n previousUpperRound,\n previousLowerRound: finalLowerRound,\n nextRound: nextUpperRound,\n firstUpperRound,\n firstLowerRound,\n }),\n );\n } else {\n relations.push(\n createTwoToNothingRelation({\n currentRound: currentUpperRound,\n previousUpperRound,\n previousLowerRound: finalLowerRound,\n firstUpperRound,\n firstLowerRound,\n }),\n );\n }\n\n const preFinalLowerRound = lowerRounds[lowerRounds.length - 2] || null;\n\n if (!preFinalLowerRound) {\n relations.push(createNothingToOneRelation({ currentRound: finalLowerRound, nextRound: currentUpperRound }));\n\n return;\n }\n\n relations.push(\n createOneToOneRelation({\n currentRound: finalLowerRound,\n previousRound: preFinalLowerRound,\n nextRound: currentUpperRound,\n rootRound: firstLowerRound,\n }),\n );\n\n if (!isAsyncBracket) return;\n\n const prePreFinalLowerRound = lowerRounds[lowerRounds.length - 3] || null;\n\n relations.push(\n prePreFinalLowerRound\n ? createOneToOneRelation({\n currentRound: preFinalLowerRound,\n previousRound: prePreFinalLowerRound,\n nextRound: finalLowerRound,\n rootRound: firstLowerRound,\n })\n : createNothingToOneRelation({ currentRound: preFinalLowerRound, nextRound: finalLowerRound }),\n );\n};\n\nconst handleFirstRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData>;\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n}) => {\n const { relations, currentUpperRound, nextUpperRound, lowerRounds, currentUpperRoundIndex } = params;\n\n relations.push(\n createNothingToOneRelation({\n currentRound: currentUpperRound,\n nextRound: nextUpperRound,\n }),\n );\n\n const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;\n const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;\n\n // Pairing \"upper round at index i\" with \"lower round at index i\" only means something while the upper\n // array is the outbound flow. A round on the way back from a fold sits past the finals in that array,\n // so its index would claim a lower round in the middle of the bracket and wire it as an opening round -\n // the loop at the end of `generateRoundRelations` reaches it by depth instead.\n if (currentLowerRound && nextLowerRound && !isFoldedBackRound(currentUpperRound)) {\n relations.push(\n createNothingToOneRelation({\n currentRound: currentLowerRound,\n nextRound: nextLowerRound,\n }),\n );\n }\n};\n\nconst handleRegularRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData>;\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData> | null;\n}) => {\n const {\n relations,\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n lowerRounds,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n } = params;\n\n relations.push(\n createOneToOneRelation({\n currentRound: currentUpperRound,\n previousRound: previousUpperRound,\n nextRound: nextUpperRound,\n rootRound: firstUpperRound,\n }),\n );\n\n const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;\n const previousLowerRound = lowerRounds[currentUpperRoundIndex - 1] || null;\n const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;\n\n if (\n currentLowerRound &&\n currentUpperRound.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET &&\n previousLowerRound &&\n nextLowerRound &&\n firstLowerRound &&\n // See `handleFirstRound`: an index into the outbound flow says nothing about a folded-back round.\n !isFoldedBackRound(currentUpperRound)\n ) {\n relations.push(\n createOneToOneRelation({\n currentRound: currentLowerRound,\n previousRound: previousLowerRound,\n nextRound: nextLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n};\n\nexport const generateRoundRelationsNew = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n): BracketRoundRelation<TRoundData, TMatchData>[] => {\n const relations: BracketRoundRelation<TRoundData, TMatchData>[] = [];\n\n // A relation may never name a round with no matches: every position in it comes from a ratio of match\n // counts, so a zero puts each neighbour's match at a position nothing occupies. A round whose matches\n // are not drawn yet is treated as absent instead, and its neighbours wired to each other.\n // A third place match is fed by losers, so it is no step in the chain that ends in the final.\n const allRounds = [...bracketData.rounds.values()].filter(\n (round) => round.matchCount > 0 && round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,\n );\n const upperRounds = allRounds.filter((r) => r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);\n const lowerRounds = allRounds.filter((r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);\n\n const upperRoundsByDepth = buildRoundsByDepth(upperRounds);\n const lowerRoundsByDepth = buildRoundsByDepth(lowerRounds);\n\n // The lower bracket as it is *played*: one round per depth, taking the left half of a folded round.\n // A fold draws each early round twice, so the raw array holds two entries per depth and its last\n // element is a first-round half rather than the round that feeds the grand final. Unfolded, this is\n // the array itself.\n const lowerFlow = Array.from(lowerRoundsByDepth.keys())\n .sort((a, b) => a - b)\n .map((depth) => roundAtDepth({ byDepth: lowerRoundsByDepth, depth, side: null }))\n .filter((round) => !!round);\n\n const firstUpperRound = upperRounds[0];\n const firstLowerRound = lowerFlow[0] || null;\n const lastLowerRound = lowerFlow[lowerFlow.length - 1] || null;\n\n // Nothing is drawn yet, so there is nothing to relate - not a malformed structure.\n if (allRounds.length === 0) return relations;\n\n const hasLowerRounds = lowerRounds.length > 0;\n\n if (firstUpperRound) {\n for (const [currentUpperRoundIndex] of upperRounds.entries()) {\n const nav = getNavigationContext({\n upperRounds,\n upperRoundsByDepth,\n currentUpperRoundIndex,\n });\n\n if (nav.isFinal && hasLowerRounds && lastLowerRound && firstLowerRound && nav.previousUpperRound) {\n handleFinalRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n previousUpperRound: nav.previousUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n lastLowerRound,\n });\n } else if (nav.isLastUpperRound && nav.previousUpperRound) {\n relations.push(\n createOneToNothingRelation({\n currentRound: nav.currentUpperRound,\n previousRound: nav.previousUpperRound,\n rootRound: firstUpperRound,\n }),\n );\n } else if (nav.currentUpperRound.isFirstRound && nav.nextUpperRound) {\n handleFirstRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n });\n } else if (nav.nextUpperRound && !nav.previousUpperRound) {\n relations.push(\n createNothingToOneRelation({\n currentRound: nav.currentUpperRound,\n nextRound: nav.nextUpperRound,\n }),\n );\n } else if (nav.previousUpperRound && nav.nextUpperRound) {\n handleRegularRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n previousUpperRound: nav.previousUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n });\n }\n }\n }\n\n if (hasLowerRounds && firstLowerRound) {\n const assignedRoundIds = new Set(relations.map((r) => r.currentRound.id));\n\n // By depth and side rather than by array position: in a folded bracket the array holds two rounds\n // per depth, so its neighbours are whatever was emitted alongside - for an unfolded one the two are\n // the same thing.\n for (const lowerRound of lowerRounds) {\n if (assignedRoundIds.has(lowerRound.id)) continue;\n\n const side = lowerRound.mirrorRoundType;\n const depth = lowerRound.logicalIndex;\n const prevLowerRound = roundAtDepth({ byDepth: lowerRoundsByDepth, depth: depth - 1, side });\n const nextLowerRound = roundAtDepth({ byDepth: lowerRoundsByDepth, depth: depth + 1, side });\n\n if (nextLowerRound) {\n if (!prevLowerRound) {\n relations.push(createNothingToOneRelation({ currentRound: lowerRound, nextRound: nextLowerRound }));\n } else {\n relations.push(\n createOneToOneRelation({\n currentRound: lowerRound,\n previousRound: prevLowerRound,\n nextRound: nextLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n } else if (prevLowerRound) {\n // Truncated bracket: the last lower round has no final round to feed into, so it terminates here.\n // In a complete bracket this round is wired up by handleFinalRound and already in assignedRoundIds.\n relations.push(\n createOneToNothingRelation({\n currentRound: lowerRound,\n previousRound: prevLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n }\n }\n\n return relations;\n};\n","import {\n BracketMap,\n BracketMatchId,\n BracketRoundId,\n BracketRoundType,\n createBracketBase,\n CreateBracketOptions,\n MatchParticipantId,\n BracketMatchBase,\n BracketMatchParticipantBase,\n BracketParticipantBase,\n BracketRoundBase,\n TournamentMode,\n} from '../core';\nimport { BracketDataSource } from '../integrations';\nimport { BracketMatchRelation, BracketMatchRelationNone, generateMatchRelationsNew } from './match-relations';\nimport { BracketRoundRelation, BracketRoundRelationNone, generateRoundRelationsNew } from './round-relations';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type Bracket<TRoundData, TMatchData> = {\n rounds: BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>;\n roundsByType: BracketMap<BracketRoundType, BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>>;\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n participants: BracketMap<MatchParticipantId, BracketParticipant<TRoundData, TMatchData>>;\n mode: TournamentMode;\n};\n\nexport type BracketRound<TRoundData, TMatchData> = BracketRoundBase<TRoundData> & {\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n relation: BracketRoundRelation<TRoundData, TMatchData>;\n};\n\nexport type BracketMatch<TRoundData, TMatchData> = BracketMatchBase<TMatchData> & {\n round: BracketRound<TRoundData, TMatchData>;\n home: BracketMatchParticipant<TRoundData, TMatchData> | null;\n away: BracketMatchParticipant<TRoundData, TMatchData> | null;\n winner: BracketMatchParticipant<TRoundData, TMatchData> | null;\n relation: BracketMatchRelation<TRoundData, TMatchData>;\n};\n\nexport type BracketParticipantMatch<TRoundData, TMatchData> = BracketMatch<TRoundData, TMatchData> & {\n me: BracketMatchParticipant<TRoundData, TMatchData>;\n opponent: BracketMatchParticipant<TRoundData, TMatchData> | null;\n};\n\nexport type BracketParticipant<TRoundData, TMatchData> = BracketParticipantBase & {\n matches: BracketMap<BracketMatchId, BracketParticipantMatch<TRoundData, TMatchData>>;\n};\n\nexport type BracketMatchParticipant<TRoundData, TMatchData> = BracketMatchParticipantBase & {\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n};\n\nexport const createBracket = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: CreateBracketOptions<TMatchData>,\n) => {\n if (!source.rounds.length)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, 'The bracket source has no rounds to render');\n\n const bracketNewBase = createBracketBase(source, options);\n\n const rounds = new BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>();\n const roundsByType = new BracketMap<\n BracketRoundType,\n BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>\n >();\n\n for (const roundBase of bracketNewBase.rounds.values()) {\n const relation = { type: 'none' } as BracketRoundRelationNone<TRoundData, TMatchData>;\n const newRound: BracketRound<TRoundData, TMatchData> = { ...roundBase, matches: new BracketMap(), relation };\n relation.currentRound = newRound;\n rounds.set(roundBase.id, newRound);\n if (!roundsByType.has(roundBase.type)) {\n roundsByType.set(roundBase.type, new BracketMap());\n }\n roundsByType.getOrThrow(roundBase.type).set(roundBase.id, newRound);\n }\n\n const participants = new BracketMap<MatchParticipantId, BracketParticipant<TRoundData, TMatchData>>();\n\n for (const participantBase of bracketNewBase.participants.values()) {\n participants.set(participantBase.id, {\n ...participantBase,\n matches: new BracketMap(),\n });\n }\n\n const matches = new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>();\n\n for (const matchBase of bracketNewBase.matches.values()) {\n const round = rounds.getOrThrow(matchBase.roundId as BracketRoundId);\n\n const homeParticipant = matchBase.home\n ? { ...matchBase.home, matches: new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>() }\n : null;\n const awayParticipant = matchBase.away\n ? { ...matchBase.away, matches: new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>() }\n : null;\n\n const relation = { type: 'none', currentRound: round } as BracketMatchRelationNone<TRoundData, TMatchData>;\n const newMatch: BracketMatch<TRoundData, TMatchData> = {\n ...matchBase,\n home: homeParticipant,\n away: awayParticipant,\n winner: null,\n round,\n relation,\n };\n relation.currentMatch = newMatch;\n\n if (matchBase.winner) {\n const winnerParticipant = homeParticipant?.id === matchBase.winner.id ? homeParticipant : awayParticipant;\n if (!winnerParticipant)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.WINNER_NOT_FOUND,\n `Winner participant with id ${matchBase.winner.id} not found in match base`,\n );\n newMatch.winner = winnerParticipant;\n }\n\n matches.set(matchBase.id, newMatch);\n round.matches.set(matchBase.id, newMatch);\n }\n\n const newBracket: Bracket<TRoundData, TMatchData> = {\n matches,\n participants,\n rounds,\n roundsByType,\n mode: bracketNewBase.mode,\n };\n\n const roundRelations = generateRoundRelationsNew(newBracket);\n\n for (const roundRelation of roundRelations) {\n roundRelation.currentRound.relation = roundRelation;\n }\n\n const matchRelations = generateMatchRelationsNew(newBracket, {\n source,\n previousMatchIds: options.previousMatchIds,\n onWarning: options.onWarning,\n });\n\n for (const matchRelation of matchRelations) {\n matchRelation.currentMatch.relation = matchRelation;\n }\n\n // After the relations, never before: a participant's view of a match is a copy of it, so building it\n // any earlier would freeze the placeholder relation into every copy.\n for (const match of matches.values()) {\n if (match.home) {\n participants.getOrThrow(match.home.id).matches.set(match.id, { ...match, me: match.home, opponent: match.away });\n }\n if (match.away) {\n participants.getOrThrow(match.away.id).matches.set(match.id, { ...match, me: match.away, opponent: match.home });\n }\n }\n\n for (const participant of participants.values()) {\n for (const match of participant.matches.values()) {\n if (match.home?.id === participant.id) match.home.matches = participant.matches;\n if (match.away?.id === participant.id) match.away.matches = participant.matches;\n if (match.winner?.id === participant.id) match.winner.matches = participant.matches;\n }\n }\n\n return newBracket;\n};\n","import { BracketMatchId, MatchParticipantSide } from '../core';\nimport { BracketMatchOutcomeSlotSource, BracketSlotSource } from '../integrations';\nimport { Bracket, BracketMatch } from './bracket';\n\n/** The table position a `standing-rank` slot asks about, and the slot that asks. */\nexport type BracketStandingRankPickQuery = {\n standingId: string;\n rank: number;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n};\n\nexport type BracketPickSet = {\n /** The participant the viewer picked to win a match. */\n matchWinner: (matchId: string) => string | null;\n /** The participant the viewer put on a table position. */\n standingRank: (options: BracketStandingRankPickQuery) => string | null;\n};\n\nexport const isBracketSlotPredictable = (source: BracketSlotSource | null): boolean =>\n source?.kind === 'match-outcome' || source?.kind === 'standing-rank' || source?.kind === 'seed';\n\n/** How a resolution weighs a prediction against what is already known. Both parts default to the stricter answer. */\nexport type BracketSlotResolutionPolicy = {\n /**\n * Whether the participant really standing on a slot of the given match outranks whatever the picks\n * predict for it. Must answer from the match alone, and answer the same way throughout one\n * resolution: the walk memoizes per slot.\n *\n * `true` answers with the real participant wherever one is known - the pairing a pick was made\n * against, which is what an open round should show. `false`, the default, answers with the\n * prediction even where reality already disagrees, which is what a locked round should show: the\n * record of the guess.\n */\n realParticipantOutranksPick?: (match: BracketMatch<unknown, unknown>) => boolean;\n\n /**\n * Whether a predicted winner still counts while one side of the match it was made on is unknown.\n * `false`, the default, drops it until both sides resolve. `true` keeps it until both sides are\n * known and it is neither of them - until then nothing contradicts it.\n */\n keepPickWhileFeederSideIsOpen?: boolean;\n\n /**\n * Whether a `match-outcome` or `standing-rank` slot the picks leave empty answers with the\n * participant really standing there. `false`, the default, leaves it empty.\n */\n fallBackToRealParticipant?: boolean;\n};\n\ntype BracketSlotResolverOptions = BracketSlotResolutionPolicy & {\n bracket: Bracket<unknown, unknown>;\n picks: BracketPickSet;\n /**\n * Earlier stages a `match-outcome` slot of `bracket` may point into. A feeder is looked up in\n * `bracket` first, then in these in order, so match ids must be unique across all of them.\n */\n linkedBrackets?: readonly Bracket<unknown, unknown>[];\n};\n\ntype ResolveBracketSlotOptions = BracketSlotResolverOptions & {\n matchId: string;\n side: MatchParticipantSide;\n};\n\nconst sourceFor = (match: BracketMatch<unknown, unknown>, side: MatchParticipantSide) =>\n side === 'home' ? match.homeSource : match.awaySource;\n\nconst participantIdFor = (match: BracketMatch<unknown, unknown>, side: MatchParticipantSide) => match[side]?.id ?? null;\n\ntype ResolveWalk = {\n lookupMatch: (matchId: string) => BracketMatch<unknown, unknown> | undefined;\n picks: BracketPickSet;\n realParticipantOutranksPick: (match: BracketMatch<unknown, unknown>) => boolean;\n keepPickWhileFeederSideIsOpen: boolean;\n fallBackToRealParticipant: boolean;\n visitDepths: Map<string, number>;\n resolved: Map<string, string | null>;\n shallowestCycleHit: number;\n};\n\nconst resolveMatchOutcome = (options: { walk: ResolveWalk; source: BracketMatchOutcomeSlotSource }): string | null => {\n const { walk, source } = options;\n\n const feeder = walk.lookupMatch(source.matchId);\n\n if (!feeder) return null;\n\n const homeSource = sourceFor(feeder, 'home');\n const awaySource = sourceFor(feeder, 'away');\n const home = resolveSlot({ walk, match: feeder, side: 'home' });\n const away = resolveSlot({ walk, match: feeder, side: 'away' });\n\n if (homeSource?.kind === 'bye' && awaySource?.kind !== 'bye') {\n return source.role !== 'loser' ? away : null;\n }\n\n if (awaySource?.kind === 'bye' && homeSource?.kind !== 'bye') {\n return source.role !== 'loser' ? home : null;\n }\n\n if (!home || !away) {\n return walk.keepPickWhileFeederSideIsOpen && source.role !== 'loser' ? walk.picks.matchWinner(feeder.id) : null;\n }\n\n const pickedWinner = walk.picks.matchWinner(feeder.id);\n\n if (pickedWinner !== home && pickedWinner !== away) return null;\n\n return source.role !== 'loser' ? pickedWinner : pickedWinner === home ? away : home;\n};\n\nconst resolveSource = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n source: BracketSlotSource;\n}): string | null => {\n const { walk, match, side, source } = options;\n\n switch (source.kind) {\n case 'match-outcome':\n return resolveMatchOutcome({ walk, source });\n case 'standing-rank':\n return walk.picks.standingRank({ standingId: source.standingId, rank: source.rank, match, side });\n case 'seed':\n case 'swiss-bucket':\n case 'external':\n case 'unknown':\n return participantIdFor(match, side);\n case 'bye':\n return null;\n }\n};\n\nconst resolveSlotOccupant = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n}): string | null => {\n const { walk, match, side } = options;\n const real = participantIdFor(match, side);\n\n if (real !== null && walk.realParticipantOutranksPick(match)) return real;\n\n const source = sourceFor(match, side);\n\n if (!source) return real;\n\n const resolved = resolveSource({ walk, match, side, source });\n\n if (resolved !== null || !walk.fallBackToRealParticipant) return resolved;\n\n return source.kind === 'match-outcome' || source.kind === 'standing-rank' ? real : null;\n};\n\nconst resolveSlot = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n}): string | null => {\n const { walk, match, side } = options;\n const visitKey = `${match.id}:${side}`;\n const openDepth = walk.visitDepths.get(visitKey);\n\n if (openDepth !== undefined) {\n walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, openDepth);\n\n return null;\n }\n\n const resolved = walk.resolved.get(visitKey);\n\n if (resolved !== undefined) return resolved;\n\n const depth = walk.visitDepths.size;\n const shallowestCycleHitBefore = walk.shallowestCycleHit;\n\n walk.visitDepths.set(visitKey, depth);\n walk.shallowestCycleHit = Infinity;\n\n try {\n const result = resolveSlotOccupant({ walk, match, side });\n\n // A result whose cycle guard only fired on this slot or below it is a function of the slot alone.\n // One that hit a slot above it depends on the path that reached it, so caching it would answer a\n // later path with a cycle's `null`.\n if (walk.shallowestCycleHit >= depth) walk.resolved.set(visitKey, result);\n\n return result;\n } finally {\n walk.visitDepths.delete(visitKey);\n walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, shallowestCycleHitBefore);\n }\n};\n\nconst matchLookupFor = (brackets: readonly Bracket<unknown, unknown>[]) => (matchId: string) => {\n for (const bracket of brackets) {\n const match = bracket.matches.get(matchId as BracketMatchId);\n\n if (match) return match;\n }\n\n return undefined;\n};\n\nconst createResolveWalk = (options: BracketSlotResolverOptions): ResolveWalk => ({\n lookupMatch: matchLookupFor([options.bracket, ...(options.linkedBrackets ?? [])]),\n picks: options.picks,\n realParticipantOutranksPick: options.realParticipantOutranksPick ?? (() => false),\n keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen ?? false,\n fallBackToRealParticipant: options.fallBackToRealParticipant ?? false,\n visitDepths: new Map(),\n resolved: new Map(),\n shallowestCycleHit: Infinity,\n});\n\n/**\n * @internal A {@link resolveBracketSlot} that shares one memo across its calls. Valid only while the\n * picks it was created with do not change.\n */\nexport const createBracketSlotResolver = (options: BracketSlotResolverOptions) => {\n const walk = createResolveWalk(options);\n\n return (matchId: string, side: MatchParticipantSide): string | null => {\n const match = options.bracket.matches.get(matchId as BracketMatchId);\n\n return match ? resolveSlot({ walk, match, side }) : null;\n };\n};\n\n/** Who the viewer's own picks put in a slot, or `null` while their picks do not reach it. */\nexport const resolveBracketSlot = (options: ResolveBracketSlotOptions): string | null =>\n createBracketSlotResolver(options)(options.matchId, options.side);\n","import { BracketMatchId } from '../core';\nimport { Bracket, BracketMatch } from './bracket';\nimport {\n BracketPickSet,\n BracketSlotResolutionPolicy,\n BracketStandingRankPickQuery,\n createBracketSlotResolver,\n} from './resolve-bracket-slot';\n\nexport type BracketPickMigrationOptions = BracketSlotResolutionPolicy & {\n bracket: Bracket<unknown, unknown>;\n /**\n * Earlier stages a `match-outcome` slot of `bracket` may point into. Their picks are read from\n * {@link pickAsMade} as given, so migrate an earlier stage first and answer with its result.\n */\n linkedBrackets?: readonly Bracket<unknown, unknown>[];\n /** The participant the viewer picked on a match, on the match they picked it on. */\n pickAsMade: (matchId: string) => string | null;\n /** The participant the viewer put on a table position, for the `standing-rank` slots a round resolves from. */\n standingRank?: (options: BracketStandingRankPickQuery) => string | null;\n /** Matches whose picks the backend already keeps. Their picks neither travel out nor take one in. */\n lockedMatchIds?: ReadonlySet<string>;\n};\n\nexport type BracketPickMigration = {\n /** The pick that counts on a match: the one made on it, or the one that followed its participant here. */\n pickByMatchId: Record<string, string | undefined>;\n /** For a match that took a pick in, the match that pick was made on. */\n movedFromByMatchId: Record<string, string | undefined>;\n /** For a match whose pick nothing in its round can honour, that pick. Such a match holds no selection. */\n strandedByMatchId: Record<string, string | undefined>;\n};\n\n// Grouped by type and depth rather than by round id: a mirrored layout splits one round into two\n// half-rounds to draw either side of the fold, and a pick has to be able to travel across it. Ordered\n// topologically over the declared provenance, because a round is settled against the ones feeding it.\nconst roundsOf = (bracket: Bracket<unknown, unknown>): BracketMatch<unknown, unknown>[][] => {\n const matchesByKey = new Map<string, BracketMatch<unknown, unknown>[]>();\n const keyByMatchId = new Map<string, string>();\n\n for (const round of bracket.rounds.values()) {\n const key = `${round.type}:${round.logicalIndex}`;\n const matches = matchesByKey.get(key) ?? [];\n\n for (const match of round.matches.values()) {\n matches.push(match);\n keyByMatchId.set(match.id, key);\n }\n\n matchesByKey.set(key, matches);\n }\n\n const unsettledFeedersByKey = new Map<string, Set<string>>();\n\n for (const [key, matches] of matchesByKey) {\n const feeders = new Set<string>();\n\n for (const match of matches) {\n for (const source of [match.homeSource, match.awaySource]) {\n if (source?.kind !== 'match-outcome' || !source.matchId) continue;\n\n const feederKey = keyByMatchId.get(source.matchId);\n\n if (feederKey !== undefined && feederKey !== key) feeders.add(feederKey);\n }\n }\n\n unsettledFeedersByKey.set(key, feeders);\n }\n\n const ordered: BracketMatch<unknown, unknown>[][] = [];\n\n while (unsettledFeedersByKey.size) {\n const keys = [...unsettledFeedersByKey.keys()];\n // A malformed graph can leave a cycle in which nothing is ready, so fall back to the first\n // round left rather than looping forever.\n const key = keys.find((candidate) => !unsettledFeedersByKey.get(candidate)?.size) ?? keys[0];\n\n if (key === undefined) break;\n\n ordered.push(matchesByKey.get(key) ?? []);\n unsettledFeedersByKey.delete(key);\n\n for (const feeders of unsettledFeedersByKey.values()) feeders.delete(key);\n }\n\n return ordered;\n};\n\n/**\n * Where every pick stands once each one has followed its participant into whichever match of its own\n * round that participant now plays. A pick nothing in the round can honour comes back stranded.\n */\nexport const migrateBracketPicks = (options: BracketPickMigrationOptions): BracketPickMigration => {\n const { bracket, pickAsMade } = options;\n const locked = options.lockedMatchIds ?? new Set<string>();\n const pickByMatchId: Record<string, string | undefined> = {};\n const movedFromByMatchId: Record<string, string | undefined> = {};\n const strandedByMatchId: Record<string, string | undefined> = {};\n\n const settled: BracketPickSet = {\n matchWinner: (matchId) =>\n bracket.matches.has(matchId as BracketMatchId) ? (pickByMatchId[matchId] ?? null) : pickAsMade(matchId),\n standingRank: options.standingRank ?? (() => null),\n };\n\n for (const round of roundsOf(bracket)) {\n const sidesByMatchId = new Map<string, [string | null, string | null]>();\n const travelling: { matchId: string; pick: string }[] = [];\n const strandedHere = new Set<string>();\n const sidesOf = (matchId: string) => sidesByMatchId.get(matchId) ?? [null, null];\n\n const resolve = createBracketSlotResolver({\n bracket,\n linkedBrackets: options.linkedBrackets,\n picks: settled,\n realParticipantOutranksPick: options.realParticipantOutranksPick,\n keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen,\n fallBackToRealParticipant: options.fallBackToRealParticipant,\n });\n\n for (const match of round) {\n sidesByMatchId.set(match.id, [resolve(match.id, 'home'), resolve(match.id, 'away')]);\n }\n\n for (const match of round) {\n const pick = pickAsMade(match.id);\n\n if (!pick) continue;\n\n const [home, away] = sidesOf(match.id);\n\n if (pick === home || pick === away) {\n pickByMatchId[match.id] = pick;\n\n continue;\n }\n\n if (locked.has(match.id)) {\n pickByMatchId[match.id] = pick;\n strandedByMatchId[match.id] = pick;\n\n continue;\n }\n\n travelling.push({ matchId: match.id, pick });\n }\n\n for (const { matchId, pick } of travelling) {\n const target = round.find((candidate) => {\n if (candidate.id === matchId || locked.has(candidate.id) || pickByMatchId[candidate.id]) return false;\n if (strandedHere.has(candidate.id)) return false;\n\n const [home, away] = sidesOf(candidate.id);\n\n return pick === home || pick === away;\n });\n\n if (!target) {\n strandedByMatchId[matchId] = pick;\n strandedHere.add(matchId);\n\n continue;\n }\n\n pickByMatchId[target.id] = pick;\n movedFromByMatchId[target.id] = matchId;\n }\n\n // After the travelling, not during it: a match that carries the stranded note holds no selection\n // at all, even where a pick reached it in the meantime.\n for (const matchId of strandedHere) delete pickByMatchId[matchId];\n }\n\n return { pickByMatchId, movedFromByMatchId, strandedByMatchId };\n};\n","import {\n BracketMap,\n BracketMatchId,\n BracketMatchParticipantBase,\n BracketRoundId,\n SWISS_ADVANCE_WINS,\n SWISS_ELIMINATE_LOSSES,\n TOURNAMENT_MODE,\n TournamentMode,\n isSwissMode,\n} from '../core';\nimport { Bracket, BracketMatch } from './bracket';\n\nexport type BracketRoundSwissGroupId = string & { _brand: 'BracketRoundSwissGroupId' };\n\nexport type BracketRoundSwissGroup<TRoundData, TMatchData> = {\n id: BracketRoundSwissGroupId;\n name: string;\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n allowedMatchCount: number;\n /** The record tone of the group - see {@link getSwissGroupColorType}. */\n colorType: BracketSwissGroupColorType;\n};\n\nexport type BracketRoundSwissGroupMap<TRoundData, TMatchData> = Map<\n BracketRoundSwissGroupId,\n BracketRoundSwissGroup<TRoundData, TMatchData>\n>;\n\nexport type BracketRoundSwissData<TRoundData, TMatchData> = {\n groups: BracketRoundSwissGroupMap<TRoundData, TMatchData>;\n};\n\nexport type BracketRoundMapWithSwissData<TRoundData, TMatchData> = Map<\n BracketRoundId,\n BracketRoundSwissData<TRoundData, TMatchData>\n>;\n\nexport const BRACKET_SWISS_GROUP_COLOR_TYPE = {\n /** The starting group (0-0) */\n NEUTRAL: 'neutral',\n\n /** The group has more wins than losses */\n POSITIVE: 'positive',\n\n /** The group is one loss away from elimination */\n NEGATIVE: 'negative',\n\n /** Everything in between */\n WARNING: 'warning',\n} as const;\n\nexport type BracketSwissGroupColorType =\n (typeof BRACKET_SWISS_GROUP_COLOR_TYPE)[keyof typeof BRACKET_SWISS_GROUP_COLOR_TYPE];\n\n/**\n * Colors for the swiss group borders and connection lines, keyed by the group color type\n * (see {@link getSwissGroupColorType}). Connection lines are drawn in the neutral color and fade\n * into the target group color on the last portion before touching its border.\n * Any CSS color value is allowed. Missing entries fall back to the connector/border color\n * (the `--et-bracket-line-color` / `--et-bracket-swiss-group-border-color` custom properties,\n * which default to `--et-surface-border`).\n */\nexport type BracketSwissColors = Partial<Record<BracketSwissGroupColorType, string>>;\n\n/** The record tone of a swiss group. A `'swiss'` stage eliminates nobody, so it has no negative tone. */\nexport const getSwissGroupColorType = (\n wins: number,\n losses: number,\n mode: TournamentMode = TOURNAMENT_MODE.SWISS_WITH_ELIMINATION,\n // eslint-disable-next-line max-params -- public (wins, losses) signature; the mode is an optional third fact\n): BracketSwissGroupColorType => {\n if (wins === 0 && losses === 0) return BRACKET_SWISS_GROUP_COLOR_TYPE.NEUTRAL;\n if (mode !== TOURNAMENT_MODE.SWISS && losses === SWISS_ELIMINATE_LOSSES - 1)\n return BRACKET_SWISS_GROUP_COLOR_TYPE.NEGATIVE;\n if (wins > losses) return BRACKET_SWISS_GROUP_COLOR_TYPE.POSITIVE;\n\n return BRACKET_SWISS_GROUP_COLOR_TYPE.WARNING;\n};\n\nconst factorialCache = /* @__PURE__ */ new Map<number, number>();\n\nexport const getAvailableSwissGroupsForRound = (\n roundNumber: number,\n totalMatchesInRound: number,\n mode: TournamentMode = TOURNAMENT_MODE.SWISS_WITH_ELIMINATION,\n // eslint-disable-next-line max-params -- public (round, match count) signature; the mode is an optional third fact\n) => {\n const limited = mode !== TOURNAMENT_MODE.SWISS;\n const advanceWins = limited ? SWISS_ADVANCE_WINS : Infinity;\n const eliminateLosses = limited ? SWISS_ELIMINATE_LOSSES : Infinity;\n\n const getFactorial = (n: number): number => {\n if (n <= 1) return 1;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (factorialCache.has(n)) return factorialCache.get(n)!;\n\n const result = n * getFactorial(n - 1);\n factorialCache.set(n, result);\n return result;\n };\n\n const roundFactorial = getFactorial(roundNumber);\n\n let totalCombinations = 0;\n const validGroups: { wins: number; losses: number; combinations: number }[] = [];\n\n for (let wins = roundNumber; wins >= 0; wins--) {\n const losses = roundNumber - wins;\n const remainingGames = advanceWins + eliminateLosses - (wins + losses) - 1;\n const notYetEliminated = losses < eliminateLosses;\n const canStillAdvance = wins < advanceWins && remainingGames >= 0;\n\n if (!canStillAdvance || !notYetEliminated) continue;\n\n const combinations = roundFactorial / (getFactorial(wins) * getFactorial(losses));\n totalCombinations += combinations;\n validGroups.push({ wins, losses, combinations });\n }\n\n return validGroups.map(({ wins, losses, combinations }) => ({\n wins,\n losses,\n id: `${wins}-${losses}` as BracketRoundSwissGroupId,\n name: `${wins}-${losses}`,\n matchesInGroup: Math.round((combinations / totalCombinations) * totalMatchesInRound),\n }));\n};\n\n/** The group an undrawn match falls into when its round has no win/loss record to group by. */\nconst UNDRAWN_SWISS_GROUP_ID = 'undrawn' as BracketRoundSwissGroupId;\n\nconst getRecordBeforeMatch = (participant: BracketMatchParticipantBase) => ({\n wins: participant.winCount - (participant.result === 'win' ? 1 : 0),\n losses: participant.lossCount - (participant.result === 'loss' ? 1 : 0),\n});\n\nexport const generateBracketRoundSwissGroupMaps = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n) => {\n if (!isSwissMode(bracketData.mode)) {\n return null;\n }\n\n const roundsWithSwissGroups: BracketRoundMapWithSwissData<TRoundData, TMatchData> = new Map();\n\n let roundNumber = 0;\n for (const bracketRound of bracketData.rounds.values()) {\n const availableGroups = getAvailableSwissGroupsForRound(roundNumber, bracketRound.matchCount, bracketData.mode);\n const colorTypeOf = (wins: number, losses: number) => getSwissGroupColorType(wins, losses, bracketData.mode);\n\n const roundSwissData: BracketRoundSwissData<TRoundData, TMatchData> = {\n groups: new Map(),\n };\n\n for (const group of availableGroups) {\n const subGroup: BracketRoundSwissGroup<TRoundData, TMatchData> = {\n id: group.id,\n name: group.name,\n matches: new BracketMap(),\n allowedMatchCount: group.matchesInGroup,\n colorType: colorTypeOf(group.wins, group.losses),\n };\n\n roundSwissData.groups.set(group.id, subGroup);\n }\n\n const emptyMatchIds: BracketMatchId[] = [];\n\n for (const match of bracketRound.matches.values()) {\n const anyParticipant = match.home || match.away;\n\n if (!anyParticipant) {\n emptyMatchIds.push(match.id);\n continue;\n }\n\n const { wins, losses } = getRecordBeforeMatch(anyParticipant);\n const groupId = `${wins}-${losses}` as BracketRoundSwissGroupId;\n\n // The table above enumerates the records of somebody who played every round. A bye, a walkover or\n // an uneven field leaves a participant with fewer games than the round index, so their group is\n // real but not in the table - create it rather than losing the whole bracket over one match.\n let group = roundSwissData.groups.get(groupId);\n\n if (!group) {\n group = {\n id: groupId,\n name: `${wins}-${losses}`,\n matches: new BracketMap(),\n allowedMatchCount: 0,\n colorType: colorTypeOf(wins, losses),\n };\n roundSwissData.groups.set(groupId, group);\n }\n\n group.matches.set(match.id, match);\n }\n\n for (const emptyMatchId of emptyMatchIds) {\n const match = bracketRound.matches.getOrThrow(emptyMatchId);\n const groups = [...roundSwissData.groups.values()];\n let group =\n groups.find((candidate) => candidate.matches.size < candidate.allowedMatchCount) ??\n groups.reduce<BracketRoundSwissGroup<TRoundData, TMatchData> | null>(\n (fewest, candidate) => (!fewest || candidate.matches.size < fewest.matches.size ? candidate : fewest),\n null,\n );\n\n // A round past the last one a 3-3 swiss can reach - the elimination rounds of a\n // swiss-with-elimination stage - has no record groups, and an undrawn match carries no record to\n // build one from. A nameless group keeps the round drawn instead of losing the whole bracket.\n if (!group) {\n group = {\n id: UNDRAWN_SWISS_GROUP_ID,\n name: '',\n matches: new BracketMap(),\n allowedMatchCount: 0,\n colorType: BRACKET_SWISS_GROUP_COLOR_TYPE.NEUTRAL,\n };\n roundSwissData.groups.set(group.id, group);\n }\n\n group.matches.set(match.id, match);\n }\n\n for (const [groupId, group] of roundSwissData.groups) {\n if (!group.matches.size) roundSwissData.groups.delete(groupId);\n }\n\n // The map is drawn top to bottom in insertion order, so a group created on demand has to be sorted\n // back into the best-record-first order the table was built in.\n const orderedGroups = [...roundSwissData.groups.entries()].sort(([a], [b]) => {\n const [aWins = 0, aLosses = 0] = a.split('-').map(Number);\n const [bWins = 0, bLosses = 0] = b.split('-').map(Number);\n\n return bWins - aWins || aLosses - bLosses;\n });\n\n roundSwissData.groups = new Map(orderedGroups);\n\n roundsWithSwissGroups.set(bracketRound.id, roundSwissData);\n\n roundNumber++;\n }\n\n return roundsWithSwissGroups;\n};\n","import { BracketMatchId, MatchParticipantSide } from '../core';\nimport { Bracket } from './bracket';\n\nexport type BracketStandingRankSide = {\n side: MatchParticipantSide;\n standingId: string;\n rank: number;\n standingName: string | null;\n /** The participant really standing on the side, or `null` while the standing is not decided. */\n participantId: string | null;\n};\n\n/** The sides of a match whose source is a `standing-rank` slot, home first. Empty for an unknown match. */\nexport const standingRankSides = (options: {\n bracket: Bracket<unknown, unknown>;\n matchId: string;\n}): BracketStandingRankSide[] => {\n const match = options.bracket.matches.get(options.matchId as BracketMatchId);\n\n if (!match) return [];\n\n return (['home', 'away'] as const).flatMap((side) => {\n const source = side === 'home' ? match.homeSource : match.awaySource;\n\n if (source?.kind !== 'standing-rank') return [];\n\n return [\n {\n side,\n standingId: source.standingId,\n rank: source.rank,\n standingName: source.standingName ?? null,\n participantId: match[side]?.id ?? null,\n },\n ];\n });\n};\n","import { CreateBracketOptions } from '../core';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BracketDataSource } from '../integrations';\nimport { createBracket } from './bracket';\n\n/**\n * Runs {@link createBracket} on `source` and returns the `BracketRuntimeError` it would throw, or `null` for a\n * usable source. Any other error is rethrown.\n */\nexport const validateBracketSource = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: CreateBracketOptions<TMatchData>,\n): BracketRuntimeError | null => {\n try {\n createBracket(source, options);\n\n return null;\n } catch (error) {\n if (error instanceof BracketRuntimeError) return error;\n\n throw error;\n }\n};\n","import { BracketRoundSwissData, generateBracketRoundSwissGroupMaps, Bracket } from '../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport { createBracketGapMasterColumn } from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\ntype SwissColumnMetrics = {\n naturalHeight: number;\n stretchableGapCount: number;\n};\n\nconst getSwissGroupBoxPadding = (options: CreateBracketGridConfig) =>\n options.swissGroupPadding + options.swissGroupBorderWidth;\n\nconst calculateSwissColumnMetrics = <TRoundData, TMatchData>(\n groupMap: BracketRoundSwissData<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n): SwissColumnMetrics => {\n const includeHeaders = options.roundHeaderHeight > 0;\n const boxPadding = getSwissGroupBoxPadding(options);\n\n let naturalHeight = 0;\n let stretchableGapCount = 0;\n\n for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {\n if (groupIndex !== 0) {\n // The gap section between two groups\n naturalHeight += options.rowRoundGap;\n stretchableGapCount++;\n }\n\n // The round header gap is not stretchable: the first match should always sit directly\n // below it, no matter how much a column gets stretched.\n if (includeHeaders) {\n naturalHeight += options.roundHeaderHeight + options.roundHeaderGap;\n }\n\n const matchGapCount = Math.max(0, group.matches.size - 1);\n\n naturalHeight += boxPadding * 2 + group.matches.size * options.matchHeight + matchGapCount * options.rowGap;\n stretchableGapCount += matchGapCount;\n }\n\n return { naturalHeight, stretchableGapCount };\n};\n\n// The naturally tallest master column (the round with the most groups) keeps the original\n// gaps (rowGap, rowRoundGap, roundHeaderGap) and defines the total bracket height.\n// The master cols before it are stretched to that height by distributing the missing\n// height evenly across all of their gap elements.\n// The master cols after it keep the original gaps, resulting in a top alignment. They get\n// one more gap element at the end of the column to fill the remaining space if any.\nexport const createSwissGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const swissGroupMaps = generateBracketRoundSwissGroupMaps(bracketData);\n\n if (!swissGroupMaps)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.SWISS_GROUPING_FAILED,\n 'Unable to generate Swiss groups for the provided bracket data',\n );\n\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n\n const groupMaps = Array.from(swissGroupMaps.values());\n const columnMetrics = groupMaps.map((groupMap) => calculateSwissColumnMetrics(groupMap, options));\n\n const totalHeight = Math.max(...columnMetrics.map((metrics) => metrics.naturalHeight));\n const longestColumnIndex = columnMetrics.findIndex((metrics) => metrics.naturalHeight === totalHeight);\n\n for (const [groupMapIndex, groupMap] of groupMaps.entries()) {\n const isLastGroupMap = groupMapIndex === swissGroupMaps.size - 1;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const metrics = columnMetrics[groupMapIndex]!;\n const heightToFill = totalHeight - metrics.naturalHeight;\n const isStretched = groupMapIndex < longestColumnIndex && metrics.stretchableGapCount > 0;\n const gapStretch = isStretched ? heightToFill / metrics.stretchableGapCount : 0;\n\n const rowGap = options.rowGap + gapStretch;\n const rowRoundGap = options.rowRoundGap + gapStretch;\n\n // The border and group padding are part of the column width (the match elements\n // shrink by them), so the column footprint stays at columnWidth and the group borders\n // drawn around the matches don't overflow the bracket container. The padding lives on\n // the match list sections, the header and gap sections stay unpadded and span the\n // whole column width.\n const boxPadding = getSwissGroupBoxPadding(options);\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {\n const isLastGroup = groupIndex === groupMap.groups.size - 1;\n\n if (options.roundHeaderHeight > 0) {\n const firstMatchRound = group.matches.first()?.round;\n\n if (!firstMatchRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SWISS_GROUP_EMPTY, 'No rounds found in Swiss group');\n\n const headerColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const headerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const headerElement = createBracketElement<TRoundData, TMatchData>({\n type: 'header',\n area: `h${group.id}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: components.roundHeader,\n round: firstMatchRound,\n roundSwissGroup: group,\n });\n\n const headerGapElement = createBracketElement<TRoundData, TMatchData>({\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [options.roundHeaderGap],\n elementHeight: options.roundHeaderGap,\n });\n\n headerSubColumn.pushElement(headerElement, headerGapElement);\n headerColumnSection.pushSubColumn(headerSubColumn.subColumn);\n pushSection(headerColumnSection.masterColumnSection);\n }\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n padding: {\n bottom: boxPadding,\n left: boxPadding,\n right: boxPadding,\n top: boxPadding,\n },\n });\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n for (const [matchIndex, match] of Array.from(group.matches.values()).entries()) {\n const isLastMatch = matchIndex === group.matches.size - 1;\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: [options.matchHeight],\n elementHeight: options.matchHeight,\n component: components.match,\n match,\n round: match.round,\n roundSwissGroup: group,\n });\n\n if (!isLastMatch) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [rowGap],\n elementHeight: rowGap,\n });\n }\n }\n\n for (const elementData of elementsToCreate) {\n const element = createBracketElement(elementData);\n\n pushElement(element);\n }\n\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n\n if (!isLastGroup) {\n const groupGapColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const groupGapSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const groupGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: rowRoundGap,\n partHeights: [rowRoundGap],\n });\n\n groupGapSubColumn.pushElement(groupGapElement);\n\n groupGapColumnSection.pushSubColumn(groupGapSubColumn.subColumn);\n\n pushSection(groupGapColumnSection.masterColumnSection);\n }\n }\n\n // Top aligned columns end above the total height, so we fill the remaining space with\n // one last gap element.\n const fillerHeight = isStretched ? 0 : heightToFill;\n\n if (fillerHeight > 0) {\n const fillerColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const fillerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const fillerElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: fillerHeight,\n partHeights: [fillerHeight],\n });\n\n fillerSubColumn.pushElement(fillerElement);\n fillerColumnSection.pushSubColumn(fillerSubColumn.subColumn);\n pushSection(fillerColumnSection.masterColumnSection);\n }\n\n grid.pushMasterColumn(masterColumn);\n\n if (!isLastGroupMap) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n","import {\n BracketByeSlotSource,\n BracketExternalSlotSource,\n BracketMatchOutcomeSlotSource,\n BracketSeedSlotSource,\n BracketStandingRankSlotSource,\n BracketSwissBucketSlotSource,\n BracketUnknownSlotSource,\n} from './base';\n\n/**\n * Constructors for every {@link BracketSlotSource} kind, each taking an optional competition `label`.\n *\n * @example\n * homeSource: bracketSlot.matchOutcome('semi-final-1', 'winner'),\n * awaySource: bracketSlot.standingRank('group-a', 2, 'Group A'),\n */\nexport const bracketSlot = {\n // eslint-disable-next-line max-params -- positional slot constructors read like the slot they build\n matchOutcome: (\n matchId: string,\n role: 'winner' | 'loser' | null,\n label: string | null = null,\n ): BracketMatchOutcomeSlotSource => ({ kind: 'match-outcome', matchId, role, label }),\n // eslint-disable-next-line max-params -- positional slot constructors read like the slot they build\n standingRank: (\n standingId: string,\n rank: number,\n standingName: string | null = null,\n label: string | null = null,\n ): BracketStandingRankSlotSource => ({ kind: 'standing-rank', standingId, rank, standingName, label }),\n seed: (seed: number, label: string | null = null): BracketSeedSlotSource => ({ kind: 'seed', seed, label }),\n swissBucket: (label: string | null = null): BracketSwissBucketSlotSource => ({ kind: 'swiss-bucket', label }),\n bye: (label: string | null = null): BracketByeSlotSource => ({ kind: 'bye', label }),\n external: (label: string): BracketExternalSlotSource => ({ kind: 'external', label }),\n unknown: (label: string | null = null): BracketUnknownSlotSource => ({ kind: 'unknown', label }),\n} as const;\n","import { BRACKET_ERROR_CODES } from './bracket-errors';\nimport { BracketRuntimeError } from './bracket-runtime-error';\nimport { TournamentMode } from './core';\n\nexport type BracketLayoutRegistration = {\n name: string;\n mode: TournamentMode;\n extraModes?: readonly TournamentMode[];\n};\n\nconst LAYOUT_FACTORY_SUGGESTION: Record<TournamentMode, string> = {\n 'single-elimination': 'singleEliminationBracketLayout()',\n 'double-elimination': 'doubleEliminationBracketLayout()',\n 'swiss-with-elimination': 'swissBracketLayout()',\n swiss: 'swissBracketLayout()',\n};\n\n/** Returns the first registered layout matching the tournament mode. */\nexport const resolveBracketLayout = <TLayout extends BracketLayoutRegistration>(\n layouts: readonly TLayout[] | undefined,\n mode: TournamentMode,\n): TLayout => {\n const layout = layouts?.find((candidate) => candidate.mode === mode || candidate.extraModes?.includes(mode));\n\n if (!layout) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.LAYOUT_NOT_REGISTERED,\n `No bracket layout registered for mode \"${mode}\". Add ${LAYOUT_FACTORY_SUGGESTION[mode]} to provideBracketConfig({ layouts: [...] }) or to the layouts input.`,\n );\n }\n\n return layout;\n};\n","import { BRACKET_ERROR_CODES } from './bracket-errors';\nimport { BracketRuntimeError } from './bracket-runtime-error';\nimport {\n BracketRoundType,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n SINGLE_ELIMINATION_BRACKET_ROUND_TYPE,\n SWISS_BRACKET_ROUND_TYPE,\n} from './core/round';\nimport { TOURNAMENT_MODE } from './core/tournament';\nimport { BracketDataSource, BracketMatchSource, BracketRoundSource } from './integrations/base';\n\nexport type SingleEliminationPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.SINGLE_ELIMINATION;\n /** A power of two, at least 2. */\n participantCount: number;\n /** @default false */\n includeThirdPlace?: boolean;\n};\n\nexport type DoubleEliminationPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.DOUBLE_ELIMINATION;\n /** A power of two, at least 4. */\n participantCount: number;\n /** @default true */\n includeFinal?: boolean;\n /** Ignored when `includeFinal` is false. @default true */\n includeReverseFinal?: boolean;\n /** @default false */\n includeThirdPlace?: boolean;\n};\n\nexport type SwissPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.SWISS;\n /** An even number, at least 4. Every participant plays each round. */\n participantCount: number;\n /** The scheduled number of rounds, from 1 through 171. */\n roundCount: number;\n};\n\n/** The structure a placeholder bracket is drawn with - see {@link createPlaceholderBracketSource}. */\nexport type PlaceholderBracketShape =\n SingleEliminationPlaceholderShape | DoubleEliminationPlaceholderShape | SwissPlaceholderShape;\n\nconst MIN_PARTICIPANTS: Record<Exclude<PlaceholderBracketShape, SwissPlaceholderShape>['mode'], number> = {\n 'single-elimination': 2,\n 'double-elimination': 4,\n};\n\n// The Swiss grouping uses factorials of the zero-based round index. 171! overflows a number.\nconst MAX_SWISS_ROUNDS = 171;\n\nconst assertPlaceholderShape = (shape: PlaceholderBracketShape) => {\n const { participantCount, mode } = shape;\n\n if (mode === TOURNAMENT_MODE.SWISS) {\n if (!Number.isSafeInteger(participantCount) || participantCount < 4 || participantCount % 2 !== 0) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A Swiss placeholder bracket needs an even participantCount of at least 4, got ${participantCount}.`,\n );\n }\n\n const { roundCount } = shape;\n if (!Number.isInteger(roundCount) || roundCount < 1 || roundCount > MAX_SWISS_ROUNDS) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A Swiss placeholder bracket needs an integer roundCount from 1 through ${MAX_SWISS_ROUNDS}, got ${roundCount}.`,\n );\n }\n\n return;\n }\n\n const min = MIN_PARTICIPANTS[mode];\n const isPowerOfTwo = Number.isInteger(participantCount) && (participantCount & (participantCount - 1)) === 0;\n\n if (participantCount < min || !isPowerOfTwo) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A ${mode} placeholder bracket needs a power-of-two participantCount of at least ${min}, got ${participantCount}.`,\n );\n }\n};\n\nconst halvingCounts = (from: number) => {\n const counts: number[] = [];\n\n for (let n = from; n >= 1; n = n / 2) {\n counts.push(n);\n }\n\n return counts;\n};\n\n/**\n * An empty bracket of the given shape - every match `pending`, both sides `null` - for drawing a loading\n * state with the real layout before the data arrives. Throws `ET3415` for invalid shape counts.\n *\n * @example\n * const source = createPlaceholderBracketSource({ mode: 'single-elimination', participantCount: 16 });\n */\nexport const createPlaceholderBracketSource = (shape: PlaceholderBracketShape): BracketDataSource<null, null> => {\n assertPlaceholderShape(shape);\n\n const rounds: BracketRoundSource<null>[] = [];\n const matches: BracketMatchSource<null>[] = [];\n\n const addRound = (round: { id: string; type: BracketRoundType; matchCount: number }) => {\n const { id, type, matchCount } = round;\n\n rounds.push({ id, type, name: '', data: null });\n\n for (let index = 0; index < matchCount; index++) {\n matches.push({\n id: `${id}-m${index}`,\n roundId: id,\n home: null,\n away: null,\n winner: null,\n status: 'pending',\n data: null,\n });\n }\n };\n\n const { participantCount } = shape;\n\n if (shape.mode === TOURNAMENT_MODE.SWISS) {\n for (let index = 0; index < shape.roundCount; index++) {\n addRound({ id: `r${index}`, type: SWISS_BRACKET_ROUND_TYPE.SWISS, matchCount: participantCount / 2 });\n }\n\n return { mode: shape.mode, rounds, matches };\n }\n\n if (shape.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION) {\n const counts = halvingCounts(participantCount / 2);\n\n counts.forEach((matchCount, index) => {\n const isFinal = index === counts.length - 1;\n\n addRound({\n id: isFinal ? 'final' : `r${index}`,\n type: isFinal\n ? COMMON_BRACKET_ROUND_TYPE.FINAL\n : SINGLE_ELIMINATION_BRACKET_ROUND_TYPE.SINGLE_ELIMINATION_BRACKET,\n matchCount,\n });\n });\n\n if (shape.includeThirdPlace) {\n addRound({ id: 'third-place', type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE, matchCount: 1 });\n }\n\n return { mode: TOURNAMENT_MODE.SINGLE_ELIMINATION, rounds, matches };\n }\n\n const { includeFinal = true, includeReverseFinal = true, includeThirdPlace = false } = shape;\n\n halvingCounts(participantCount / 2).forEach((matchCount, index) =>\n addRound({ id: `ub-r${index}`, type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET, matchCount }),\n );\n\n halvingCounts(participantCount / 4)\n .flatMap((matchCount) => [matchCount, matchCount])\n .forEach((matchCount, index) =>\n addRound({ id: `lb-r${index}`, type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET, matchCount }),\n );\n\n if (includeFinal) {\n addRound({ id: 'final', type: COMMON_BRACKET_ROUND_TYPE.FINAL, matchCount: 1 });\n\n if (includeReverseFinal) {\n addRound({ id: 'reverse-final', type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL, matchCount: 1 });\n }\n }\n\n if (includeThirdPlace) {\n addRound({ id: 'third-place', type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE, matchCount: 1 });\n }\n\n return { mode: TOURNAMENT_MODE.DOUBLE_ELIMINATION, rounds, matches };\n};\n","/** How a group-table prediction scored on one position, once the real order is in. */\nexport const STANDING_PICK_OUTCOME = {\n /** The participant finished on exactly the predicted position. */\n EXACT: 'exact',\n /** They finished on the predicted side of the advancing line, on another position. */\n PARTIAL: 'partial',\n /** They finished on the other side of the advancing line. */\n WRONG: 'wrong',\n} as const;\n\nexport type StandingPickOutcome = (typeof STANDING_PICK_OUTCOME)[keyof typeof STANDING_PICK_OUTCOME];\n\n/**\n * How the participant predicted on `predictedPosition` scored, given where they really finished.\n *\n * `advancingCount` is how many positions advance, so a position is on the advancing side while it is\n * `<= advancingCount`. Ending up on the other side of that line is `WRONG` whatever the distance; the\n * predicted side of it is `EXACT` on the predicted position and `PARTIAL` on any other.\n *\n * `EXACT` is awarded below the line as well. An app whose API stores only the advancing positions holds no\n * prediction for the rest - the order there is whatever its UI happened to draw - and should narrow the\n * result to `PARTIAL`/`WRONG` itself for those positions.\n *\n * Returns the outcome and no points: what an outcome is worth is a rule of the competition, and\n * `POINTS[outcome]` is a lookup the app already owns.\n */\nexport const standingPickOutcome = (options: {\n /** The position the participant was predicted to finish on, 1-based. */\n predictedPosition: number;\n /** The position they really finished on, 1-based. */\n actualPosition: number;\n /** How many positions advance. */\n advancingCount: number;\n}): StandingPickOutcome => {\n const { predictedPosition, actualPosition, advancingCount } = options;\n const predictedToAdvance = predictedPosition <= advancingCount;\n\n if (predictedToAdvance !== actualPosition <= advancingCount) return STANDING_PICK_OUTCOME.WRONG;\n if (predictedPosition === actualPosition) return STANDING_PICK_OUTCOME.EXACT;\n\n return STANDING_PICK_OUTCOME.PARTIAL;\n};\n","/** A prediction already stored for one position of a group table. */\nexport type StandingPick = {\n /** The position it was stored on, 1-based. */\n position: number;\n /** The participant predicted to finish there. */\n participantId: string;\n};\n\n/**\n * The order to show a group table in before anyone moves a row: every stored pick takes the position it was\n * stored on, and the participants without one follow in the order the backend listed them, filling the gaps.\n *\n * A pick the field cannot hold is dropped rather than drawn - a position that is not an integer in\n * `1..participantIds.length`, an id that is not in the field, a second pick for a position or for a\n * participant already placed (the lowest position keeps it). The result is therefore always a permutation\n * of `participantIds`.\n */\nexport const standingPickStartOrder = (options: {\n /** The participants, in the order the backend listed them. */\n participantIds: readonly string[];\n /** What is already stored, in any order. */\n picks: readonly StandingPick[];\n}): string[] => {\n const { participantIds, picks } = options;\n const field = new Set(participantIds);\n const byPosition = new Map<number, string>();\n const placed = new Set<string>();\n\n for (const pick of [...picks].sort((left, right) => left.position - right.position)) {\n const holds =\n Number.isInteger(pick.position) &&\n pick.position >= 1 &&\n pick.position <= participantIds.length &&\n field.has(pick.participantId) &&\n !placed.has(pick.participantId) &&\n !byPosition.has(pick.position);\n\n if (!holds) continue;\n\n byPosition.set(pick.position, pick.participantId);\n placed.add(pick.participantId);\n }\n\n const rest = participantIds.filter((id) => !placed.has(id));\n const order: string[] = [];\n\n for (let position = 1; position <= participantIds.length; position++) {\n const id = byPosition.get(position) ?? rest.shift();\n\n if (id !== undefined) order.push(id);\n }\n\n return order;\n};\n","/**\n * Puts `participantId` on `rank` (1-based) of a standing order by swapping it with whoever stood there. Always\n * returns a new array; it equals `order` when the participant is not in it or `rank` is outside the order.\n */\nexport const swapStandingRank = (options: {\n order: readonly string[];\n rank: number;\n participantId: string;\n}): string[] => {\n const { order, rank, participantId } = options;\n const next = [...order];\n const to = rank - 1;\n const from = next.indexOf(participantId);\n\n if (from < 0 || !Number.isInteger(rank) || to < 0 || to >= next.length) return next;\n\n [next[from], next[to]] = [next[to] as string, participantId];\n\n return next;\n};\n"],"mappings":"AAAA,MAAa,sBAAsB;CAEjC,cAAc;CAEd,kBAAkB;CAElB,iBAAiB;CAEjB,iBAAiB;CAEjB,wBAAwB;CAExB,wBAAwB;CAExB,cAAc;CAEd,uBAAuB;CAEvB,mBAAmB;CAEnB,kBAAkB;CAElB,oBAAoB;CAEpB,0BAA0B;CAE1B,uBAAuB;CAEvB,qBAAqB;CAErB,2BAA2B;AACnB;AC3BV,IAAa,sBAAb,cAAyC,MAAK;CAG5C,YAAY,MAAc,SAAe;EACvC,MAAM,KAAK,KAAI,IAAK,SAAS;EAC7B,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACD;ACVD,IAAa,aAAb,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ACb,MAAM,EAAE,gBAAgB,UAAU;CAClC,MAAM,QAAQ,IAAI,IAAI,cAAc;CACpC,MAAM,6BAAa,IAAI,IAAG;CAC1B,MAAM,yBAAS,IAAI,IAAG;CAEtB,KAAK,MAAM,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,MAAM,MAAM,UAAU,KAAK,WAAW,MAAM,QAAQ,GAAG;EASnF,IAAI,EAPF,OAAO,UAAU,KAAK,QAAQ,KAC9B,KAAK,YAAY,KACjB,KAAK,YAAY,eAAe,UAChC,MAAM,IAAI,KAAK,aAAa,KAC5B,CAAC,OAAO,IAAI,KAAK,aAAa,KAC9B,CAAC,WAAW,IAAI,KAAK,QAAQ,IAEnB;EAEZ,WAAW,IAAI,KAAK,UAAU,KAAK,aAAa;EAChD,OAAO,IAAI,KAAK,aAAa;CAC/B;CAEA,MAAM,OAAO,eAAe,QAAQ,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC;CAC1D,MAAM,QAAkB,CAAA;CAExB,KAAK,IAAI,WAAW,GAAG,YAAY,eAAe,QAAQ,YAAY;EACpE,MAAM,KAAK,WAAW,IAAI,QAAQ,KAAK,KAAK,MAAK;EAEjD,IAAI,OAAO,QAAW,MAAM,KAAK,EAAE;CACrC;CAEA,OAAO;AACT;ACjDA,MAAa,oBAAoB,YAIlB;CACb,MAAM,EAAE,OAAO,MAAM,kBAAkB;CACvC,MAAM,OAAO,CAAC,GAAG,KAAK;CACtB,MAAM,KAAK,OAAO;CAClB,MAAM,OAAO,KAAK,QAAQ,aAAa;CAEvC,IAAI,OAAO,KAAK,CAAC,OAAO,UAAU,IAAI,KAAK,KAAK,KAAK,MAAM,KAAK,QAAQ,OAAO;CAE/E,CAAC,KAAK,OAAO,KAAK,OAAO,CAAC,KAAK,KAAe,aAAa;CAE3D,OAAO;AACT"}
1
+ {"version":3,"file":"ethlete-components-bracket.mjs","names":["createNothingToOneRelation","createTwoToOneRelation","createTwoToNothingRelation"],"sources":["../../../../libs/components/bracket/lib/bracket-errors.ts","../../../../libs/components/bracket/lib/bracket-runtime-error.ts","../../../../libs/components/bracket/lib/core/bracket-map.ts","../../../../libs/components/bracket/lib/core/layout.ts","../../../../libs/components/bracket/lib/core/tournament.ts","../../../../libs/components/bracket/lib/core/round.ts","../../../../libs/components/bracket/lib/core/match-participant.ts","../../../../libs/components/bracket/lib/core/match.ts","../../../../libs/components/bracket/lib/core/participant.ts","../../../../libs/components/bracket/lib/core/bracket.ts","../../../../libs/components/bracket/lib/drawing/path.ts","../../../../libs/components/bracket/lib/drawing/curve.ts","../../../../libs/components/bracket/lib/drawing/grid/types.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-element-part.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-element.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-finalizer.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-grid.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-master-column.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-master-column-section.ts","../../../../libs/components/bracket/lib/drawing/grid/core/bracket-sub-column.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-continue-master-column.ts","../../../../libs/components/bracket/lib/drawing/line.ts","../../../../libs/components/bracket/lib/drawing/draw-man.ts","../../../../libs/components/bracket/lib/drawing/draw-man-swiss.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination-utils.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-sub-column-relative-to-first-round.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-folded-third-place-section.ts","../../../../libs/components/bracket/lib/drawing/grid/prebuild/bracket-gap-master-column.ts","../../../../libs/components/bracket/lib/drawing/grid/row-span.ts","../../../../libs/components/bracket/lib/drawing/grid/single-elimination.ts","../../../../libs/components/bracket/lib/drawing/grid/sections.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination.ts","../../../../libs/components/bracket/lib/drawing/grid/double-elimination-stacked.ts","../../../../libs/components/bracket/lib/linked/match-relations.ts","../../../../libs/components/bracket/lib/linked/round-relations.ts","../../../../libs/components/bracket/lib/linked/bracket.ts","../../../../libs/components/bracket/lib/linked/resolve-bracket-slot.ts","../../../../libs/components/bracket/lib/linked/migrate-bracket-picks.ts","../../../../libs/components/bracket/lib/linked/swiss.ts","../../../../libs/components/bracket/lib/linked/standing-rank-sides.ts","../../../../libs/components/bracket/lib/linked/validate-bracket-source.ts","../../../../libs/components/bracket/lib/drawing/grid/swiss.ts","../../../../libs/components/bracket/lib/integrations/bracket-slot.ts","../../../../libs/components/bracket/lib/layout-registry.ts","../../../../libs/components/bracket/lib/placeholder-source.ts","../../../../libs/components/bracket/lib/standings/standing-pick.ts","../../../../libs/components/bracket/lib/standings/standing-pick-order.ts","../../../../libs/components/bracket/lib/standings/swap-standing-rank.ts"],"sourcesContent":["export const BRACKET_ERROR_CODES = {\n /** The source has no rounds/matches to render. */\n SOURCE_EMPTY: 3401,\n /** An integration received a tournament mode it does not support. */\n MODE_UNSUPPORTED: 3402,\n /** Two rounds in the source share an id. */\n DUPLICATE_ROUND: 3403,\n /** Two matches in the source share an id. */\n DUPLICATE_MATCH: 3404,\n /** A round-to-round relation could not be resolved (malformed round structure). */\n ROUND_RELATION_INVALID: 3405,\n /** A match-to-match relation could not be resolved (match counts don't line up). */\n MATCH_RELATION_INVALID: 3406,\n /** The computed layout grid is in an inconsistent state. */\n GRID_INVALID: 3407,\n /** Swiss groups could not be generated from the source. */\n SWISS_GROUPING_FAILED: 3408,\n /** A Swiss group ended up without any matches while headers are enabled. */\n SWISS_GROUP_EMPTY: 3409,\n /** A match's resolved winner id is not among its participants. */\n WINNER_NOT_FOUND: 3410,\n /** A required key was missing from an internal bracket lookup map. */\n DATA_LOOKUP_FAILED: 3411,\n /** The default cards are rendering but no `matchNormalizer` was registered to feed them. */\n MISSING_MATCH_NORMALIZER: 3412,\n /** No registered {@link BracketLayout} matches the source's tournament `mode`. */\n LAYOUT_NOT_REGISTERED: 3413,\n /** A cell the bracket draws has no card - neither an input, the layout, nor the config names one. */\n CARD_NOT_REGISTERED: 3414,\n /** `createPlaceholderBracketSource` got an invalid participant or round count for its mode. */\n PLACEHOLDER_SHAPE_INVALID: 3415,\n} as const;\n","/**\n * The error every `@ethlete/components/bracket` engine function throws for a malformed source. `code` is one of\n * {@link BRACKET_ERROR_CODES}; the message starts with `ET<code>: `.\n */\nexport class BracketRuntimeError extends Error {\n public readonly code: number;\n\n constructor(code: number, message: string) {\n super(`ET${code}: ${message}`);\n this.name = 'BracketRuntimeError';\n this.code = code;\n }\n}\n","import { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\nexport class BracketMap<TKey, TValue> extends Map<TKey, TValue> {\n constructor() {\n super();\n }\n\n getOrThrow(key: TKey): TValue {\n const value = super.get(key);\n\n if (value === undefined) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.DATA_LOOKUP_FAILED,\n `Value for key ${key} not found in bracket map`,\n );\n }\n\n return value;\n }\n\n first(): TValue | undefined {\n return this.values().next().value;\n }\n\n last(): TValue | undefined {\n const values = Array.from(this.values());\n return values.length > 0 ? values[values.length - 1] : undefined;\n }\n}\n","export const BRACKET_DATA_LAYOUT = {\n LEFT_TO_RIGHT: 'left-to-right',\n\n /**\n * Folded in half: each round up to the first one too small to halve is drawn twice, once on each\n * side, converging on that round and the ones after it. Halves the height and roughly doubles the\n * width, which is what a poster or a broadcast graphic wants.\n *\n * Carried by the mirrored layout factories - a layout that has no fold to make (swiss) simply has no\n * mirrored variant.\n */\n MIRRORED: 'mirrored',\n} as const;\n\nexport type BracketDataLayout = (typeof BRACKET_DATA_LAYOUT)[keyof typeof BRACKET_DATA_LAYOUT];\n","export const TOURNAMENT_MODE = {\n SINGLE_ELIMINATION: 'single-elimination',\n DOUBLE_ELIMINATION: 'double-elimination',\n SWISS_WITH_ELIMINATION: 'swiss-with-elimination',\n SWISS: 'swiss',\n} as const;\n\nexport type TournamentMode = (typeof TOURNAMENT_MODE)[keyof typeof TOURNAMENT_MODE];\n\n/** Whether a stage is drawn as swiss record groups: `'swiss-with-elimination'` or `'swiss'`, which eliminates nobody. */\nexport const isSwissMode = (mode: TournamentMode) =>\n mode === TOURNAMENT_MODE.SWISS_WITH_ELIMINATION || mode === TOURNAMENT_MODE.SWISS;\n\n/** Wins that advance a participant out of a swiss stage. */\nexport const SWISS_ADVANCE_WINS = 3;\n\n/** Losses that eliminate a participant from a swiss stage. */\nexport const SWISS_ELIMINATE_LOSSES = 3;\n","import { BracketDataSource } from '../integrations';\nimport { GenerateBracketDataOptions } from './bracket';\nimport { BracketMap } from './bracket-map';\nimport { BRACKET_DATA_LAYOUT } from './layout';\nimport { BracketMatchId } from './match';\nimport { TOURNAMENT_MODE } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketRoundId = string & { _brand: 'BracketRoundId' };\nexport type BracketRoundShortId = string & { _brand: 'BracketRoundShortId' };\nexport type BracketRoundPosition = number & { _brand: 'BracketRoundPosition' };\nexport type BracketRoundMirrorType = (typeof BRACKET_ROUND_MIRROR_TYPE)[keyof typeof BRACKET_ROUND_MIRROR_TYPE];\n\nexport const BRACKET_ROUND_MIRROR_TYPE = {\n LEFT: 'left',\n RIGHT: 'right',\n} as const;\n\nexport const COMMON_BRACKET_ROUND_TYPE = {\n THIRD_PLACE: 'third-place',\n FINAL: 'final',\n} as const;\n\nexport const SINGLE_ELIMINATION_BRACKET_ROUND_TYPE = {\n SINGLE_ELIMINATION_BRACKET: 'single-elimination-bracket',\n} as const;\n\nexport const DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE = {\n UPPER_BRACKET: 'upper-bracket',\n LOWER_BRACKET: 'lower-bracket',\n REVERSE_FINAL: 'reverse-final',\n} as const;\n\nexport const SWISS_BRACKET_ROUND_TYPE = {\n SWISS: 'swiss',\n} as const;\n\nexport const GROUP_BRACKET_ROUND_TYPE = {\n GROUP: 'group',\n} as const;\n\nexport type CommonBracketRoundType = (typeof COMMON_BRACKET_ROUND_TYPE)[keyof typeof COMMON_BRACKET_ROUND_TYPE];\nexport type SingleEliminationBracketRoundType =\n | CommonBracketRoundType\n | (typeof SINGLE_ELIMINATION_BRACKET_ROUND_TYPE)[keyof typeof SINGLE_ELIMINATION_BRACKET_ROUND_TYPE];\nexport type DoubleEliminationBracketRoundType =\n | CommonBracketRoundType\n | (typeof DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE)[keyof typeof DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE];\nexport type SwissBracketRoundType = (typeof SWISS_BRACKET_ROUND_TYPE)[keyof typeof SWISS_BRACKET_ROUND_TYPE];\nexport type GroupBracketRoundType = (typeof GROUP_BRACKET_ROUND_TYPE)[keyof typeof GROUP_BRACKET_ROUND_TYPE];\n\nexport type BracketRoundType =\n SingleEliminationBracketRoundType | DoubleEliminationBracketRoundType | SwissBracketRoundType | GroupBracketRoundType;\n\nexport const TERMINAL_ROUND_SORT_PRIORITY: Partial<Record<string, number>> = {\n final: 1,\n 'reverse-final': 2,\n 'third-place': 3,\n};\n\nexport type BracketRoundBase<TRoundData> = {\n /**\n * How deep this round sits in its own bracket - 0 for the opening round, counted separately for the\n * upper and lower halves of a double elimination.\n *\n * **Both halves of a mirrored round share it.** That is what makes it the fold's coordinate: a\n * mirrored layout draws each depth twice, once on each side, so the depth is the only thing that says\n * which right-hand column belongs opposite which left-hand one.\n */\n logicalIndex: number;\n type: BracketRoundType;\n id: BracketRoundId;\n shortId: BracketRoundShortId;\n data: TRoundData;\n position: BracketRoundPosition;\n name: string;\n matchCount: number;\n mirrorRoundType: BracketRoundMirrorType | null;\n isFirstRound: boolean;\n isLastRound: boolean;\n isFirstOfType: boolean;\n isLastOfType: boolean;\n};\n\nexport type BracketRoundWithRelationsBase<TRoundData> = BracketRoundBase<TRoundData> & {\n matchIds: BracketMatchId[];\n};\n\nexport const createRoundsMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: GenerateBracketDataOptions,\n) => {\n const map = new BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>();\n\n const shouldSplitRoundsInTwo = options.layout === BRACKET_DATA_LAYOUT.MIRRORED;\n const isDoubleElimination = source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION;\n\n let currentUpperBracketIndex = 0;\n let currentLowerBracketIndex = 0;\n\n // A fold converges once, on the first round it cannot halve, and every later round stays whole -\n // otherwise a bye (`[6, 3, 2, 1]`) reopens the fold past its middle and draws a round on both sides\n // of one that has no side. Tracked per bracket half, because the two converge separately.\n const foldClosed = { upper: false, lower: false };\n\n const splitRoundsRest: BracketRoundWithRelationsBase<TRoundData>[] = [];\n\n const orderedRounds = [...source.rounds].sort(\n (a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0),\n );\n\n for (const [roundIndex, round] of orderedRounds.entries()) {\n const isUpperBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET;\n const isLowerBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET;\n const isCommonDoubleEliminationRound = !isUpperBracket && !isLowerBracket && isDoubleElimination;\n\n const matches = source.matches.filter((m) => m.roundId === round.id);\n const roundId = round.id as BracketRoundId;\n const foldSide = isLowerBracket || isCommonDoubleEliminationRound ? 'lower' : 'upper';\n const canHalveRound = matches.length >= 2 && matches.length % 2 === 0;\n const shouldSplitRound = shouldSplitRoundsInTwo && canHalveRound && !foldClosed[foldSide];\n\n if (!canHalveRound) foldClosed[foldSide] = true;\n\n const isFirstRound = roundIndex === 0;\n const isLastRound = roundIndex === orderedRounds.length - 1;\n\n const isFirstOfType = orderedRounds.findIndex((r) => r.type === round.type) === roundIndex;\n const isLastOfType =\n orderedRounds\n .slice()\n .reverse()\n .findIndex((r) => r.type === round.type) ===\n orderedRounds.length - roundIndex - 1;\n\n const depth =\n isLowerBracket || isCommonDoubleEliminationRound ? currentLowerBracketIndex : currentUpperBracketIndex;\n\n if (shouldSplitRound) {\n const firstHalfRoundId = `${roundId}--half-1` as BracketRoundId;\n const secondHalfRoundId = `${roundId}--half-2` as BracketRoundId;\n const firstHalfMatchesMaxIndex = matches.length / 2 - 1;\n\n // Both halves are the same round at the same depth, drawn on either side of the fold - so they\n // carry the same `logicalIndex`, which is what pairs a right-hand column with its left-hand twin.\n const halfBase = {\n type: round.type,\n logicalIndex: depth,\n data: round.data,\n position: (depth + 1) as BracketRoundPosition,\n name: round.name,\n matchCount: matches.length / 2,\n isFirstRound,\n isLastRound,\n isFirstOfType,\n isLastOfType,\n };\n\n const bracketRoundFirstHalf: BracketRoundWithRelationsBase<TRoundData> = {\n ...halfBase,\n id: firstHalfRoundId,\n shortId: `${roundIndex}-left` as BracketRoundShortId,\n matchIds: matches.slice(0, firstHalfMatchesMaxIndex + 1).map((m) => m.id as BracketMatchId),\n mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.LEFT,\n };\n\n const bracketRoundSecondHalf: BracketRoundWithRelationsBase<TRoundData> = {\n ...halfBase,\n id: secondHalfRoundId,\n shortId: `${roundIndex}-right` as BracketRoundShortId,\n matchIds: matches.slice(firstHalfMatchesMaxIndex + 1).map((m) => m.id as BracketMatchId),\n mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.RIGHT,\n };\n\n map.set(firstHalfRoundId, bracketRoundFirstHalf);\n\n splitRoundsRest.unshift(bracketRoundSecondHalf);\n } else {\n const bracketRound: BracketRoundWithRelationsBase<TRoundData> = {\n type: round.type,\n id: roundId,\n shortId: `${roundIndex}` as BracketRoundShortId,\n logicalIndex: depth,\n data: round.data,\n position: (depth + 1) as BracketRoundPosition,\n name: round.name,\n matchCount: matches.length,\n matchIds: matches.map((m) => m.id as BracketMatchId),\n mirrorRoundType: null,\n isFirstRound,\n isLastRound,\n isFirstOfType,\n isLastOfType,\n };\n\n map.set(roundId, bracketRound);\n }\n\n if (isLowerBracket || isCommonDoubleEliminationRound) {\n currentLowerBracketIndex++;\n } else {\n currentUpperBracketIndex++;\n }\n }\n\n // The right halves close the map, deepest first, so walking it in order walks the fold: out along the\n // left side, through the rounds too small to halve, and back along the right. `splitRoundsRest` was\n // built by unshifting, so it is already in that order - and each half keeps the depth of its twin\n // rather than being renumbered past the last round, which is what lets a builder pair the two sides.\n if (splitRoundsRest.length) {\n if (!map.last()) throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, 'Last round not found');\n\n for (const splitRound of splitRoundsRest) {\n map.set(splitRound.id, splitRound);\n }\n }\n\n return map;\n};\n","import { BracketDataSource, BracketMatchSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketMatchId } from './match';\nimport { MatchParticipantId, BracketParticipantBase, BracketParticipantWithRelationsBase } from './participant';\nimport {\n BracketRoundId,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n BracketRoundWithRelationsBase,\n} from './round';\nimport { SWISS_ELIMINATE_LOSSES, TOURNAMENT_MODE } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type ParticipantMatchResult = 'win' | 'loss' | 'tie';\nexport type MatchParticipantSide = 'home' | 'away';\n\nexport type BracketMatchParticipantBase = BracketParticipantBase & {\n result: ParticipantMatchResult | null;\n isEliminated: boolean;\n isEliminationMatch: boolean;\n tieCount: number;\n winCount: number;\n lossCount: number;\n side: MatchParticipantSide;\n};\n\nexport type BracketMatchParticipantWithRelationsBase = BracketMatchParticipantBase &\n BracketParticipantWithRelationsBase;\n\nconst thirdPlaceFeederRoundId = <TRoundData, TMatchData>(source: BracketDataSource<TRoundData, TMatchData>) => {\n if (!source.rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)) return null;\n\n const chain = source.rounds.filter((round) => round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE);\n const finalIndex = chain.findIndex((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL);\n\n return finalIndex > 0 ? (chain[finalIndex - 1]?.id ?? null) : null;\n};\n\nexport const createNewMatchParticipantBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n participantId: MatchParticipantId | null,\n match: BracketMatchSource<TMatchData>,\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>,\n matchRoundId: BracketRoundId,\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>,\n sourceMatchesById?: ReadonlyMap<string, BracketMatchSource<TMatchData>>,\n // eslint-disable-next-line max-params -- builder maps one source participant to a bracket node; its lookups are distinct positional inputs\n) => {\n if (!participantId) return null;\n\n const findSourceMatch = (matchId: string | undefined) =>\n matchId === undefined\n ? undefined\n : sourceMatchesById\n ? sourceMatchesById.get(matchId)\n : source.matches.find((m) => m.id === matchId);\n\n const participantBase = participants.getOrThrow(participantId);\n const roundBase = rounds.getOrThrow(matchRoundId as BracketRoundId);\n\n const matchIndex = participantBase.matchIds.indexOf(match.id as BracketMatchId);\n if (matchIndex === -1)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match with id ${match.id} not found in participant with id ${participantId}`,\n );\n\n const participantSide = match.home === participantId ? 'home' : 'away';\n const isWinner = match.winner === participantSide;\n const isLooser = match.winner && match.winner !== participantSide;\n const isTie = match.status === 'completed' && !match.winner;\n\n let winsTilNow = isWinner ? 1 : 0;\n let lossesTilNow = isLooser ? 1 : 0;\n let tiesTilNow = isTie ? 1 : 0;\n\n for (let i = 0; i < matchIndex; i++) {\n const previousMatchId = participantBase.matchIds[i];\n const previousMatch = findSourceMatch(previousMatchId);\n const myPreviousMatchSide =\n previousMatch?.home === participantId ? 'home' : previousMatch?.away === participantId ? 'away' : null;\n\n if (!previousMatch || !myPreviousMatchSide) continue;\n\n const previousIsWinner = previousMatch.winner === myPreviousMatchSide;\n const previousIsLooser = previousMatch.winner && previousMatch.winner !== myPreviousMatchSide;\n const previousIsTie = previousMatch.status === 'completed' && !previousMatch.winner;\n\n if (previousIsWinner) {\n winsTilNow++;\n } else if (previousIsLooser) {\n lossesTilNow++;\n } else if (previousIsTie) {\n tiesTilNow++;\n }\n }\n\n const hasElimination =\n source.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION ||\n source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION ||\n source.mode === TOURNAMENT_MODE.SWISS_WITH_ELIMINATION;\n\n let isEliminated = false;\n let isEliminationMatch = false;\n\n if (hasElimination) {\n switch (source.mode) {\n case TOURNAMENT_MODE.SINGLE_ELIMINATION: {\n isEliminationMatch = match.roundId !== thirdPlaceFeederRoundId(source);\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n break;\n }\n case TOURNAMENT_MODE.DOUBLE_ELIMINATION: {\n isEliminationMatch =\n roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET ||\n roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL ||\n roundBase.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE;\n\n // Final is only an elimination match if there is no reverse final or there is one and this participant came from the lower bracket\n if (roundBase.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {\n const hasReverseFinal = source.rounds.some(\n (r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL,\n );\n\n if (!hasReverseFinal) {\n isEliminationMatch = true;\n isEliminated = isLooser ?? false;\n break;\n }\n\n isEliminationMatch = participantBase.matchIds.some((matchId) => {\n const playedMatch = findSourceMatch(matchId);\n\n return (\n !!playedMatch &&\n source.rounds.find((round) => round.id === playedMatch.roundId)?.type ===\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET\n );\n });\n }\n\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n break;\n }\n case TOURNAMENT_MODE.SWISS_WITH_ELIMINATION: {\n // `lossesTilNow` counts this match too, so the losses carried *into* it are one fewer for a\n // loser - it is those that decide whether losing here is what puts the participant out.\n const priorLosses = lossesTilNow - (isLooser ? 1 : 0);\n\n isEliminationMatch = priorLosses >= SWISS_ELIMINATE_LOSSES - 1;\n\n isEliminated = (isEliminationMatch && isLooser) ?? false;\n }\n }\n }\n\n const matchParticipantBase: BracketMatchParticipantWithRelationsBase = {\n ...participantBase,\n isEliminated,\n isEliminationMatch,\n lossCount: lossesTilNow,\n tieCount: tiesTilNow,\n winCount: winsTilNow,\n result: isWinner ? 'win' : isLooser ? 'loss' : isTie ? 'tie' : null,\n side: participantSide,\n };\n\n return matchParticipantBase;\n};\n","import { BracketDataSource, BracketSlotSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport {\n MatchParticipantSide,\n BracketMatchParticipantWithRelationsBase,\n createNewMatchParticipantBase,\n} from './match-participant';\nimport { MatchParticipantId, BracketParticipantWithRelationsBase } from './participant';\nimport { BracketRoundId, BracketRoundWithRelationsBase } from './round';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketMatchId = string & { _brand: 'BracketMatchId' };\nexport type BracketMatchShortId = string & { _brand: 'BracketMatchShortId' };\nexport type BracketMatchPosition = number & { _brand: 'BracketMatchPosition' };\n\nexport type BracketMatchStatus = 'completed' | 'pending';\n\nexport type BracketMatchBase<TMatchData> = {\n data: TMatchData;\n indexInRound: number;\n id: BracketMatchId;\n shortId: BracketMatchShortId;\n position: BracketMatchPosition;\n winnerSide: MatchParticipantSide | null;\n status: BracketMatchStatus;\n homeSource: BracketSlotSource | null;\n awaySource: BracketSlotSource | null;\n};\n\nexport type BracketMatchWithRelationsBase<TMatchData> = BracketMatchBase<TMatchData> & {\n roundId: BracketRoundId;\n home: BracketMatchParticipantWithRelationsBase | null;\n away: BracketMatchParticipantWithRelationsBase | null;\n winner: BracketMatchParticipantWithRelationsBase | null;\n};\n\nexport const createMatchesMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>,\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>,\n // eslint-disable-next-line max-params -- builder threads the source plus its round and participant lookup maps\n) => {\n const map: BracketMap<BracketMatchId, BracketMatchWithRelationsBase<TMatchData>> = new BracketMap();\n const sourceMatchesById = new Map(source.matches.map((match) => [match.id, match]));\n\n for (const match of source.matches) {\n const genericRound = rounds.get(match.roundId as BracketRoundId);\n const splitRound = rounds.get(`${match.roundId}--half-1` as BracketRoundId);\n const splitRound2 = rounds.get(`${match.roundId}--half-2` as BracketRoundId);\n\n const genericRoundMatchIndex = genericRound?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n const splitRoundMatchIndex = splitRound?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n const splitRound2MatchIndex = splitRound2?.matchIds.indexOf(match.id as BracketMatchId) ?? -1;\n\n const roundToUse =\n genericRoundMatchIndex !== -1\n ? genericRound\n : splitRoundMatchIndex !== -1\n ? splitRound\n : splitRound2MatchIndex !== -1\n ? splitRound2\n : null;\n\n if (!roundToUse)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match \"${match.id}\" names round \"${match.roundId}\", which is not in source.rounds (known: ${source.rounds.map((round) => round.id).join(', ')})`,\n );\n\n const indexInRound =\n genericRoundMatchIndex !== -1\n ? genericRoundMatchIndex\n : splitRoundMatchIndex !== -1\n ? splitRoundMatchIndex\n : splitRound2MatchIndex !== -1\n ? splitRound2MatchIndex\n : -1;\n\n if (indexInRound === -1)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match with id ${match.id} not found in round with id ${roundToUse.id}`,\n );\n\n const home = createNewMatchParticipantBase(\n source,\n match.home as MatchParticipantId | null,\n match,\n rounds,\n roundToUse.id,\n participants,\n sourceMatchesById,\n );\n const away = createNewMatchParticipantBase(\n source,\n match.away as MatchParticipantId | null,\n match,\n rounds,\n roundToUse.id,\n participants,\n sourceMatchesById,\n );\n const winner = match.winner === 'home' ? home : match.winner === 'away' ? away : null;\n\n const matchBase: BracketMatchWithRelationsBase<TMatchData> = {\n home,\n away,\n data: match.data,\n shortId: `${roundToUse.shortId}-${indexInRound}` as BracketMatchShortId,\n id: match.id as BracketMatchId,\n indexInRound,\n position: (indexInRound + 1) as BracketMatchPosition,\n roundId: roundToUse?.id,\n status: match.status,\n homeSource: match.homeSource ?? null,\n awaySource: match.awaySource ?? null,\n winner,\n winnerSide: match.winner,\n };\n\n map.set(matchBase.id, matchBase);\n }\n\n return map;\n};\n","import { BracketDataSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketMatchId } from './match';\n\nexport type MatchParticipantId = string & { _brand: 'MatchParticipantId' };\nexport type MatchParticipantShortId = string & { _brand: 'MatchParticipantShortId' };\n\nexport type BracketParticipantBase = {\n id: MatchParticipantId;\n shortId: MatchParticipantShortId;\n};\n\nexport type BracketParticipantWithRelationsBase = BracketParticipantBase & {\n matchIds: BracketMatchId[];\n};\n\nexport const createParticipantsMapBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n) => {\n const map: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase> = new BracketMap();\n\n const participantIds = source.matches\n .map((m) => [m.home, m.away])\n .flat()\n .filter((p) => !!p) as MatchParticipantId[];\n\n const matchIdsByParticipant = new Map<string, BracketMatchId[]>();\n\n for (const match of source.matches) {\n for (const participantId of new Set([match.home, match.away])) {\n if (!participantId) continue;\n\n const matchIds = matchIdsByParticipant.get(participantId) ?? [];\n\n matchIds.push(match.id as BracketMatchId);\n matchIdsByParticipant.set(participantId, matchIds);\n }\n }\n\n for (const [index, participantId] of participantIds.entries()) {\n const participantBase: BracketParticipantWithRelationsBase = {\n id: participantId as MatchParticipantId,\n shortId: `p${index}` as MatchParticipantShortId,\n matchIds: matchIdsByParticipant.get(participantId) ?? [],\n };\n\n map.set(participantId, participantBase);\n }\n\n return map;\n};\n","import { BracketDataSource, BracketMatchSource } from '../integrations';\nimport { BracketMap } from './bracket-map';\nimport { BracketDataLayout } from './layout';\nimport { BracketMatchId, BracketMatchWithRelationsBase, createMatchesMapBase } from './match';\nimport { BracketParticipantWithRelationsBase, createParticipantsMapBase, MatchParticipantId } from './participant';\nimport {\n BracketRoundId,\n BracketRoundWithRelationsBase,\n createRoundsMapBase,\n TERMINAL_ROUND_SORT_PRIORITY,\n} from './round';\nimport { TournamentMode } from './tournament';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type BracketBase<TRoundData, TMatchData> = {\n rounds: BracketMap<BracketRoundId, BracketRoundWithRelationsBase<TRoundData>>;\n matches: BracketMap<BracketMatchId, BracketMatchWithRelationsBase<TMatchData>>;\n participants: BracketMap<MatchParticipantId, BracketParticipantWithRelationsBase>;\n mode: TournamentMode;\n};\n\nexport type GenerateBracketDataOptions = {\n layout: BracketDataLayout;\n};\n\n/**\n * Something in a source `createBracket` accepted but probably did not mean: a feeder id that names no\n * match, or a match the declared graph links to nothing because it carries no provenance.\n */\nexport type BracketWarning =\n | { type: 'unknown-feeder'; matchId: string; feederId: string; message: string }\n | { type: 'unlinked-match'; matchId: string; message: string };\n\nexport type CreateBracketOptions<TMatchData> = GenerateBracketDataOptions & {\n /** The matches feeding this one, upper arm first. Slot provenance is used when omitted. */\n previousMatchIds?: (match: BracketMatchSource<TMatchData>) => string[];\n /** Called once per {@link BracketWarning} while the bracket is linked from a declared graph. */\n onWarning?: (warning: BracketWarning) => void;\n};\n\nconst sortSourceMatchesByRoundOrder = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n): BracketDataSource<TRoundData, TMatchData> => {\n const orderedRoundIds = [...source.rounds]\n .sort((a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0))\n .map((r) => r.id);\n\n const roundIndexMap = new Map(orderedRoundIds.map((id, i) => [id, i]));\n\n const sortedMatches = [...source.matches].sort(\n (a, b) => (roundIndexMap.get(a.roundId) ?? 0) - (roundIndexMap.get(b.roundId) ?? 0),\n );\n\n return { ...source, matches: sortedMatches };\n};\n\nconst assertUniqueIds = (options: { ids: string[]; code: number; kind: string }) => {\n const seen = new Set<string>();\n\n for (const id of options.ids) {\n if (seen.has(id)) {\n throw new BracketRuntimeError(options.code, `${options.kind} with id ${id} exists more than once in the source.`);\n }\n\n seen.add(id);\n }\n};\n\nexport const createBracketBase = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: GenerateBracketDataOptions,\n) => {\n assertUniqueIds({\n ids: source.rounds.map((round) => round.id),\n code: BRACKET_ERROR_CODES.DUPLICATE_ROUND,\n kind: 'Round',\n });\n assertUniqueIds({\n ids: source.matches.map((match) => match.id),\n code: BRACKET_ERROR_CODES.DUPLICATE_MATCH,\n kind: 'Match',\n });\n\n const normalizedSource = sortSourceMatchesByRoundOrder(source);\n\n const participants = createParticipantsMapBase(normalizedSource);\n const rounds = createRoundsMapBase(normalizedSource, options);\n const matches = createMatchesMapBase(normalizedSource, rounds, participants);\n\n const bracketData: BracketBase<TRoundData, TMatchData> = {\n matches,\n rounds,\n participants,\n mode: source.mode,\n };\n\n return bracketData;\n};\n","import { BracketEdge } from './shapes';\n\nexport type PathOptions = {\n /** Unique within one drawing - see {@link BracketEdge.id}. */\n id: string;\n width: number;\n dashArray: number;\n dashOffset: number;\n className: string;\n stroke?: string;\n};\n\nexport const path = (d: string, options: PathOptions): BracketEdge => {\n const commands = d.replace(/\\s+/g, ' ').trim();\n\n return {\n id: options.id,\n d: commands,\n cssPath: `path(\"${commands}\")`,\n cssClass: options.className,\n strokeWidth: options.width,\n dashArray: options.dashArray,\n dashOffset: options.dashOffset,\n stroke: options.stroke ?? 'currentColor',\n };\n};\n","import { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\n\nexport type CurveOptions = {\n lineStartingCurveAmount: number;\n lineEndingCurveAmount: number;\n path: PathOptions;\n inverted?: boolean;\n /**\n * Where the vertical part of the connector sits, in px from the feeding card. `null` or omitted turns\n * it at the middle of the gap.\n */\n turnOffset?: number | null;\n /**\n * Where the closing straight run stops, as an inline coordinate. Omitted, it runs into the target card;\n * a merge stops both arms where they meet and draws the rest once.\n */\n endInline?: number;\n};\n\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nconst curveGeometry = (from: BracketPosition, to: BracketPosition, options: CurveOptions) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.end : to.inline.start;\n const fromBlock = from.block.center;\n const toBlock = to.block.center;\n\n // Both bends have to fit inside the block and the inline distance between the two cards, or the line\n // turns past its target and comes back. Scaling them down instead - to nothing, for two cards on the\n // same row - is also what keeps the six commands below identical for every connector: a CSS `d`\n // transition interpolates only between two paths of the same shape.\n const requestedCurve = options.lineStartingCurveAmount + options.lineEndingCurveAmount;\n const totalInline = Math.abs(toInline - fromInline);\n const room = Math.min(Math.abs(toBlock - fromBlock), totalInline);\n const curveScale = requestedCurve > room ? room / requestedCurve : 1;\n\n const startCurve = options.lineStartingCurveAmount * curveScale;\n const endCurve = options.lineEndingCurveAmount * curveScale;\n const straightTotal = totalInline - startCurve - endCurve;\n const turnOffset = options.turnOffset ?? null;\n const leadingStraight =\n turnOffset === null ? straightTotal / 2 : Math.max(0, Math.min(turnOffset - startCurve, straightTotal));\n const trailingStraight = straightTotal - leadingStraight;\n\n const straightEnd = inverted ? fromInline - leadingStraight : fromInline + leadingStraight;\n const straightStart = inverted ? toInline + trailingStraight : toInline - trailingStraight;\n\n return { inverted, fromInline, toInline, fromBlock, toBlock, startCurve, endCurve, straightEnd, straightStart };\n};\n\n/** The inline coordinate where a curve's closing straight run into its target card begins. */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const curveStraightStart = (from: BracketPosition, to: BracketPosition, options: CurveOptions) =>\n curveGeometry(from, to, options).straightStart;\n\nexport const curvePath = (\n from: BracketPosition,\n to: BracketPosition,\n direction: 'up' | 'down',\n options: CurveOptions,\n // eslint-disable-next-line max-params -- geometry helper: (from, to, direction, options) reads naturally positional\n) => {\n const { inverted, fromInline, toInline, fromBlock, toBlock, startCurve, endCurve, straightEnd, straightStart } =\n curveGeometry(from, to, options);\n\n const firstCurveEndX = inverted ? straightEnd - startCurve : straightEnd + startCurve;\n const firstCurveEndY = direction === 'down' ? fromBlock + startCurve : fromBlock - startCurve;\n\n const secondCurveStartY = direction === 'down' ? toBlock - endCurve : toBlock + endCurve;\n const secondCurveEndX = straightStart;\n const secondCurveEndY = toBlock;\n const secondCurveBezierX = inverted ? straightStart + endCurve : straightStart - endCurve;\n\n const d = [\n `M ${fromInline} ${fromBlock}`,\n `H ${straightEnd}`,\n `Q ${firstCurveEndX} ${fromBlock}, ${firstCurveEndX} ${firstCurveEndY}`,\n `V ${secondCurveStartY}`,\n `Q ${secondCurveBezierX} ${toBlock}, ${secondCurveEndX} ${secondCurveEndY}`,\n `H ${options.endInline ?? toInline}`,\n ].join(' ');\n\n return path(d, options.path);\n};\n","import { BracketDataLayout } from '../../core';\nimport { FinalizedBracketColumn, FinalizedBracketMatchElementMap, MutableBracketGrid } from './core';\nimport { BracketGridSection } from './sections';\n\nexport type ComputedBracketGrid<TRoundData, TMatchData> = {\n raw: MutableBracketGrid<TRoundData, TMatchData>;\n columns: FinalizedBracketColumn<TRoundData, TMatchData>[];\n matchElementMap: FinalizedBracketMatchElementMap<TRoundData, TMatchData>;\n /** The parts of the bracket and where they sit. Only the left-to-right double elimination grid sets it. */\n sections?: BracketGridSection<TRoundData, TMatchData>[];\n /** @internal Set when the finals were moved off the upper bracket final's row. */\n finalAlignment?: BracketFinalAlignment;\n};\n\n/** Returns the width needed to render a computed bracket grid without horizontal clipping. */\nexport const bracketGridNaturalWidth = <TRoundData, TMatchData>(\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n): number => grid.raw.grid.dimensions.width;\n\nexport const BRACKET_FINAL_ALIGNMENT = {\n UPPER: 'upper',\n CENTER: 'center',\n} as const;\n\n/**\n * Where a left-to-right double elimination puts its finals: `'upper'` level with the upper bracket final,\n * `'center'` on the midpoint between the centres of the upper bracket final and the lower bracket final.\n */\nexport type BracketFinalAlignment = (typeof BRACKET_FINAL_ALIGNMENT)[keyof typeof BRACKET_FINAL_ALIGNMENT];\n\nexport type CreateBracketGridConfig = {\n includeRoundHeaders: boolean;\n columnWidth: number;\n matchHeight: number;\n roundHeaderHeight: number;\n roundHeaderGap: number;\n columnGap: number;\n rowRoundGap: number;\n rowGap: number;\n rowSpanRoundId: string | null;\n /** @internal Resolved by a grid builder from `rowSpanRoundId`. */\n rowSpanMatchCount?: number;\n finalMatchHeight: number;\n finalColumnWidth: number;\n\n /**\n * What the final keeps between its round header and its card, in px, where that is more than\n * `roundHeaderGap`. The room goes to the final's column alone. Unset gives it the same gap as every\n * other round.\n */\n finalRoundHeaderGap?: number | null;\n\n /**\n * How far below the top of the final's card a third place match sits, in px, when the two share a\n * column. Unset (or `null`) gives the third place a column of its own, except in a mirrored layout,\n * which folds it one `rowGap` below the final's card.\n */\n thirdPlaceTopOffset?: number | null;\n swissGroupPadding: number;\n swissGroupBorderWidth: number;\n\n /**\n * The band reserved above each section for its title, in px. Only the left-to-right double elimination\n * grid reserves it; unset or `0` reserves none.\n */\n sectionTitleHeight?: number;\n\n /** The space between a section title band and the first row of its section, in px. Unset reserves none. */\n sectionTitleGap?: number;\n\n /**\n * Where the left-to-right double elimination grid puts the final and the bracket reset, see\n * {@link BracketFinalAlignment}. Unset means `'upper'`; a centred final never overlaps a third place below it.\n */\n finalAlignment?: BracketFinalAlignment;\n layout: BracketDataLayout;\n continueElement?: {\n columnWidth: number;\n elementHeight: number;\n } | null;\n};\n","import { Dimensions } from './types';\n\nexport type CreateBracketElementPartConfig = {\n elementPartHeight: number;\n};\n\nexport type BracketElementPart = {\n dimensions: Dimensions;\n};\n\nexport const createBracketElementPart = (config: CreateBracketElementPartConfig): BracketElementPart => ({\n dimensions: {\n width: 0,\n height: config.elementPartHeight,\n top: 0,\n left: 0,\n },\n});\n","import { BracketRoundSwissGroup, BracketMatch, BracketRound } from '../../../linked';\nimport { BracketElementPart, createBracketElementPart } from './bracket-element-part';\nimport { BracketContinueComponent, BracketMatchComponent, BracketRoundHeaderComponent, Dimensions } from './types';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport type BracketElementBase = {\n area: string;\n dimensions: Dimensions;\n containerDimensions: Dimensions;\n\n parts: ReadonlyArray<BracketElementPart>;\n\n span?: BracketElementSpanCoordinates;\n};\n\nexport type HeaderBracketElement<TRoundData, TMatchData> = BracketElementBase &\n HeaderBracketElementDetails<TRoundData, TMatchData>;\n\nexport type MatchBracketElement<TRoundData, TMatchData> = BracketElementBase &\n MatchBracketElementDetails<TRoundData, TMatchData>;\n\nexport type GapBracketElement = BracketElementBase & GapBracketElementDetails;\n\nexport type ContinueBracketElement<TRoundData, TMatchData> = BracketElementBase &\n ContinueBracketElementDetails<TRoundData, TMatchData>;\n\nexport type BracketElement<TRoundData, TMatchData> =\n | HeaderBracketElement<TRoundData, TMatchData>\n | MatchBracketElement<TRoundData, TMatchData>\n | GapBracketElement\n | ContinueBracketElement<TRoundData, TMatchData>;\n\nexport type BracketElementSpanCoordinates = {\n masterColumnStart: number;\n masterColumnEnd: number;\n sectionStart: number;\n sectionEnd: number;\n subColumnStart: number;\n subColumnEnd: number;\n};\n\nexport type BracketElementToCreateBase = {\n area: string;\n partHeights: number[];\n elementHeight: number;\n};\n\nexport type HeaderBracketElementDetails<TRoundData, TMatchData> = {\n type: 'header';\n component: BracketRoundHeaderComponent<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type HeaderBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n HeaderBracketElementDetails<TRoundData, TMatchData>;\n\ntype MatchBracketElementDetails<TRoundData, TMatchData> = {\n type: 'match';\n component: BracketMatchComponent<TRoundData, TMatchData>;\n match: BracketMatch<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type MatchBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n MatchBracketElementDetails<TRoundData, TMatchData>;\n\nexport type GapBracketElementDetails = {\n type: 'matchGap' | 'roundHeaderGap' | 'roundGap' | 'colGap';\n};\n\nexport type GapBracketElementToCreate = BracketElementToCreateBase & GapBracketElementDetails;\n\nexport type ContinueBracketElementDetails<TRoundData, TMatchData> = {\n type: 'continue';\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport type ContinueBracketElementToCreate<TRoundData, TMatchData> = BracketElementToCreateBase &\n ContinueBracketElementDetails<TRoundData, TMatchData>;\n\nexport type BracketElementToCreate<TRoundData, TMatchData> =\n | HeaderBracketElementToCreate<TRoundData, TMatchData>\n | MatchBracketElementToCreate<TRoundData, TMatchData>\n | GapBracketElementToCreate\n | ContinueBracketElementToCreate<TRoundData, TMatchData>;\n\nexport const createBracketElement = <TRoundData, TMatchData>(\n config: BracketElementToCreate<TRoundData, TMatchData>,\n): BracketElement<TRoundData, TMatchData> => {\n const { type, area, elementHeight, partHeights } = config;\n\n const parts: BracketElementPart[] = [];\n\n const newElementBase: BracketElementBase = {\n dimensions: {\n width: 0,\n height: elementHeight,\n top: 0,\n left: 0,\n },\n containerDimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n parts,\n area,\n };\n\n const newElement: BracketElement<TRoundData, TMatchData> = (() => {\n switch (type) {\n case 'header':\n return {\n ...newElementBase,\n type,\n component: config.component,\n round: config.round,\n roundSwissGroup: config.roundSwissGroup,\n } satisfies HeaderBracketElement<TRoundData, TMatchData>;\n case 'match':\n return {\n ...newElementBase,\n type,\n component: config.component,\n match: config.match,\n round: config.round,\n roundSwissGroup: config.roundSwissGroup,\n } satisfies MatchBracketElement<TRoundData, TMatchData>;\n case 'matchGap':\n case 'roundHeaderGap':\n case 'roundGap':\n case 'colGap':\n return {\n ...newElementBase,\n type,\n } satisfies GapBracketElement;\n case 'continue':\n return {\n ...newElementBase,\n type,\n component: config.component,\n matches: config.matches,\n } satisfies ContinueBracketElement<TRoundData, TMatchData>;\n default:\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n `Unknown element type: ${type as unknown as string}`,\n );\n }\n })();\n\n for (const partHeight of partHeights) {\n parts.push(createBracketElementPart({ elementPartHeight: partHeight }));\n }\n\n return newElement;\n};\n","import { BracketMap } from '../../../core';\nimport { BracketRoundSwissGroup, BracketMatch, BracketRound } from '../../../linked';\nimport { MutableBracketGrid } from './bracket-grid';\nimport { BracketContinueComponent, BracketMatchComponent, BracketRoundHeaderComponent, Dimensions } from './types';\n\nexport type FinalizedBracketColumn<TRoundData = unknown, TMatchData = unknown> = {\n dimensions: Dimensions;\n elements: FinalizedBracketElement<TRoundData, TMatchData>[];\n};\n\nexport type FinalizedHeaderBracketElement<TRoundData, TMatchData> = {\n type: 'header';\n dimensions: Dimensions;\n component: BracketRoundHeaderComponent<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n};\n\nexport type FinalizedMatchBracketElement<TRoundData, TMatchData> = {\n type: 'match';\n dimensions: Dimensions;\n component: BracketMatchComponent<TRoundData, TMatchData>;\n match: BracketMatch<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n roundSwissGroup: BracketRoundSwissGroup<TRoundData, TMatchData> | null;\n classes: string;\n};\n\nexport type FinalizedContinueBracketElement<TRoundData, TMatchData> = {\n type: 'continue';\n dimensions: Dimensions;\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport type FinalizedBracketElement<TRoundData = unknown, TMatchData = unknown> =\n | FinalizedHeaderBracketElement<TRoundData, TMatchData>\n | FinalizedMatchBracketElement<TRoundData, TMatchData>\n | FinalizedContinueBracketElement<TRoundData, TMatchData>;\n\nexport type FinalizedBracketMatchElementMap<TRoundData, TMatchData> = BracketMap<\n string,\n FinalizedMatchBracketElement<TRoundData, TMatchData>\n>;\n\nexport const finalizeBracketGrid = <TRoundData, TMatchData>(grid: MutableBracketGrid<TRoundData, TMatchData>) => {\n const finalizedColumns: FinalizedBracketColumn<TRoundData, TMatchData>[] = [];\n const finalizedElementMap: FinalizedBracketMatchElementMap<TRoundData, TMatchData> = new BracketMap();\n\n const ignoredSections: { masterColumnIndex: number; sectionIndex: number }[] = [];\n\n for (const [masterColumnIndex, masterColumn] of grid.grid.masterColumns.entries()) {\n for (const [sectionIndex, section] of masterColumn.sections.entries()) {\n if (ignoredSections.some((s) => s.masterColumnIndex === masterColumnIndex && s.sectionIndex === sectionIndex)) {\n continue;\n }\n\n const elements: FinalizedBracketElement<TRoundData, TMatchData>[] = [];\n const firstSubColumn = section.subColumns[0];\n const lastSubColumn = section.subColumns[section.subColumns.length - 1];\n\n if (!firstSubColumn || !lastSubColumn) continue;\n\n let sectionWidth = section.dimensions.width;\n\n for (const element of firstSubColumn.elements) {\n if (element.type === 'header') {\n elements.push({\n type: 'header',\n dimensions: element.dimensions,\n component: element.component,\n round: element.round,\n roundSwissGroup: element.roundSwissGroup,\n });\n } else if (element.type === 'match') {\n const matchEl: FinalizedMatchBracketElement<TRoundData, TMatchData> = {\n type: 'match',\n dimensions: element.dimensions,\n component: element.component,\n match: element.match,\n round: element.round,\n classes: [element.match.home?.shortId, element.match.away?.shortId].filter((v) => !!v).join(' '),\n roundSwissGroup: element.roundSwissGroup,\n };\n\n elements.push(matchEl);\n finalizedElementMap.set(element.match.id, matchEl);\n } else if (element.type === 'continue') {\n elements.push({\n type: 'continue',\n dimensions: element.dimensions,\n component: element.component,\n matches: element.matches,\n });\n }\n }\n\n if (!lastSubColumn.span.isEnd) {\n for (let index = masterColumnIndex + 1; index < grid.grid.masterColumns.length; index++) {\n const nextMaster = grid.grid.masterColumns[index];\n const nextSection = nextMaster?.sections[sectionIndex];\n\n if (!nextSection) break;\n\n sectionWidth += nextSection.dimensions.width;\n ignoredSections.push({ masterColumnIndex: index, sectionIndex });\n\n if (nextSection.subColumns.some((sc) => sc.span.isEnd)) {\n break;\n }\n }\n }\n\n if (!elements.length) continue;\n\n finalizedColumns.push({\n dimensions: {\n ...section.dimensions,\n width: sectionWidth,\n },\n elements,\n });\n }\n }\n\n return {\n columns: finalizedColumns,\n elementMap: finalizedElementMap,\n };\n};\n","import { DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../../core';\nimport { BracketElementSpanCoordinates } from './bracket-element';\nimport { BracketMasterColumn } from './bracket-master-column';\nimport { Dimensions } from './types';\n\nexport type BracketGrid<TRoundData, TMatchData> = {\n masterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n};\n\nexport type MutableBracketGrid<TRoundData, TMatchData> = {\n grid: BracketGrid<TRoundData, TMatchData>;\n pushMasterColumn: (...masterColumns: BracketMasterColumn<TRoundData, TMatchData>[]) => void;\n calculateDimensions: () => void;\n setupElementSpans: () => void;\n};\n\nexport const createBracketGrid = <TRoundData, TMatchData>(config: {\n spanElementWidth: number;\n}): MutableBracketGrid<TRoundData, TMatchData> => {\n const masterColumns: BracketMasterColumn<TRoundData, TMatchData>[] = [];\n const contentWidths = new WeakMap<BracketMasterColumn<TRoundData, TMatchData>, number>();\n\n const newGrid: BracketGrid<TRoundData, TMatchData> = {\n dimensions: { width: 0, height: 0, top: 0, left: 0 },\n masterColumns,\n };\n\n const pushMasterColumn = (...newMasterColumns: BracketMasterColumn<TRoundData, TMatchData>[]) => {\n masterColumns.push(...newMasterColumns);\n };\n\n const calculateDimensions = () => {\n let currentMasterColumnLeft = 0;\n let maxGridHeight = 0;\n const masterCols = newGrid.masterColumns;\n\n for (const masterColumn of masterCols) {\n const { padding } = masterColumn;\n\n masterColumn.dimensions.left = currentMasterColumnLeft;\n masterColumn.dimensions.top = 0;\n const contentWidth = contentWidths.get(masterColumn) ?? masterColumn.dimensions.width;\n\n contentWidths.set(masterColumn, contentWidth);\n masterColumn.dimensions.width = contentWidth + padding.left + padding.right;\n\n const sections = masterColumn.sections;\n let runningTop = 0;\n\n const firstElement = sections[0]?.subColumns[0]?.elements[0];\n const firstSectionIsHeader = firstElement?.type === 'header';\n\n for (const [secIdx, section] of sections.entries()) {\n const sectionPadding = section.padding ?? padding;\n\n let sectionPaddingTop: number;\n if (secIdx === 0) {\n sectionPaddingTop = firstSectionIsHeader ? 0 : sectionPadding.top;\n } else {\n sectionPaddingTop = sectionPadding.top;\n }\n\n section.dimensions.width = masterColumn.dimensions.width;\n section.dimensions.left = masterColumn.dimensions.left;\n section.dimensions.top = runningTop;\n\n runningTop += sectionPaddingTop;\n\n const sectionContentWidth = masterColumn.dimensions.width - sectionPadding.left - sectionPadding.right;\n const subColumns = section.subColumns;\n const totalSubColumns = subColumns.length;\n const subColumnWidth = sectionContentWidth / totalSubColumns;\n let currentSubColumnLeft = masterColumn.dimensions.left + sectionPadding.left;\n let maxSectionHeight = 0;\n\n for (const subColumn of subColumns) {\n subColumn.dimensions.width = subColumnWidth;\n subColumn.dimensions.left = currentSubColumnLeft;\n subColumn.dimensions.top = section.dimensions.top + sectionPaddingTop;\n\n let totalSubColumnHeight = 0;\n const elements = subColumn.elements;\n\n for (const element of elements) {\n let totalElementHeight = 0;\n const parts = element.parts;\n\n for (const part of parts) {\n part.dimensions.width = subColumnWidth;\n part.dimensions.left = currentSubColumnLeft;\n part.dimensions.top = subColumn.dimensions.top + totalSubColumnHeight + totalElementHeight;\n totalElementHeight += part.dimensions.height;\n }\n\n element.containerDimensions.height = totalElementHeight;\n element.containerDimensions.width = subColumnWidth;\n element.containerDimensions.left = currentSubColumnLeft;\n element.containerDimensions.top = subColumn.dimensions.top + totalSubColumnHeight;\n\n element.dimensions.width = subColumnWidth;\n element.dimensions.left = currentSubColumnLeft;\n element.dimensions.top =\n element.containerDimensions.top + (totalElementHeight - element.dimensions.height) * 0.5;\n\n totalSubColumnHeight += totalElementHeight;\n }\n\n subColumn.dimensions.height = totalSubColumnHeight;\n if (totalSubColumnHeight > maxSectionHeight) maxSectionHeight = totalSubColumnHeight;\n currentSubColumnLeft += subColumnWidth;\n }\n\n // Never negative: a section may start above where it would stack (a folded third place asks for\n // that with a negative padding), but its own box still has to be a box.\n section.dimensions.height = Math.max(0, sectionPaddingTop + maxSectionHeight + sectionPadding.bottom);\n\n runningTop += maxSectionHeight + sectionPadding.bottom;\n }\n\n masterColumn.dimensions.height = runningTop;\n if (masterColumn.dimensions.height > maxGridHeight) maxGridHeight = masterColumn.dimensions.height;\n currentMasterColumnLeft += masterColumn.dimensions.width;\n }\n\n newGrid.dimensions.width = currentMasterColumnLeft;\n newGrid.dimensions.height = maxGridHeight;\n\n calculateSpanningElementDimensions();\n };\n\n const calculateSpanningElementDimensions = () => {\n const spanDimensions = new Map<string, { width: number; left: number }>();\n const masterCols = newGrid.masterColumns;\n\n for (const [mcIdx, masterColumn] of masterCols.entries()) {\n const sections = masterColumn.sections;\n\n for (const [secIdx, section] of sections.entries()) {\n const subColumns = section.subColumns;\n\n for (const [scIdx, subColumn] of subColumns.entries()) {\n const elements = subColumn.elements;\n\n for (const element of elements) {\n if (!element.span) continue;\n\n const span = element.span;\n const isStartPosition =\n mcIdx === span.masterColumnStart && secIdx === span.sectionStart && scIdx === span.subColumnStart;\n\n const spanKey = `${span.masterColumnStart}-${span.masterColumnEnd}-${span.sectionStart}-${span.sectionEnd}-${span.subColumnStart}-${span.subColumnEnd}`;\n\n if (isStartPosition && !spanDimensions.has(spanKey)) {\n const { left: spanStartLeft, width: totalSpannedWidth } = calculateSpanExtent(span, masterCols);\n const width = config.spanElementWidth;\n\n // Winner bracket rounds span two lower bracket columns. Left-align them within that\n // span (factor 0) instead of centering (factor 0.5) so each winner round n sits above\n // the lower bracket round its losers drop into (round 2n-2) - the round whose matches\n // merge into the next one. That makes the participant's drop target unambiguous. Every\n // other spanning round (e.g. lower rounds split across sub-columns) stays centered.\n const round = element.type === 'header' || element.type === 'match' ? element.round : null;\n const alignFactor = round?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET ? 0 : 0.5;\n\n spanDimensions.set(spanKey, { width, left: spanStartLeft + (totalSpannedWidth - width) * alignFactor });\n }\n\n const storedDimensions = spanDimensions.get(spanKey);\n if (storedDimensions) {\n element.dimensions.width = storedDimensions.width;\n element.dimensions.left = storedDimensions.left;\n }\n }\n }\n }\n }\n };\n\n const calculateSpanExtent = (\n span: BracketElementSpanCoordinates,\n masterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>,\n ) => {\n const start = masterColumns[span.masterColumnStart]?.sections[span.sectionStart]?.subColumns[span.subColumnStart];\n const end = masterColumns[span.masterColumnEnd]?.sections[span.sectionEnd]?.subColumns[span.subColumnEnd];\n\n if (!start || !end) return { left: start?.dimensions.left ?? 0, width: 0 };\n\n return { left: start.dimensions.left, width: end.dimensions.left + end.dimensions.width - start.dimensions.left };\n };\n\n const setupElementSpans = () => {\n const masterCols = newGrid.masterColumns;\n for (const [mcIdx, masterColumn] of masterCols.entries()) {\n const sections = masterColumn.sections;\n\n for (const [secIdx, section] of sections.entries()) {\n const subColumns = section.subColumns;\n\n for (const [scIdx, subColumn] of subColumns.entries()) {\n if (subColumn.span.isStart && subColumn.span.isEnd) continue;\n\n let spanStart = { masterColumnIndex: mcIdx, sectionIndex: secIdx, subColumnIndex: scIdx };\n if (!subColumn.span.isStart) {\n outer: for (let m = mcIdx; m >= 0; m--) {\n const mc = masterCols[m];\n if (!mc) continue;\n const sec = mc.sections[secIdx];\n if (!sec) continue;\n const end = m === mcIdx ? scIdx : sec.subColumns.length - 1;\n for (let s = end; s >= 0; s--) {\n if (sec.subColumns[s]?.span.isStart) {\n spanStart = { masterColumnIndex: m, sectionIndex: secIdx, subColumnIndex: s };\n break outer;\n }\n }\n }\n }\n\n let spanEnd = { masterColumnIndex: mcIdx, sectionIndex: secIdx, subColumnIndex: scIdx };\n if (!subColumn.span.isEnd) {\n outer: for (let m = mcIdx; m < masterCols.length; m++) {\n const mc = masterCols[m];\n if (!mc) continue;\n const sec = mc.sections[secIdx];\n if (!sec) continue;\n const start = m === mcIdx ? scIdx : 0;\n for (let s = start; s < sec.subColumns.length; s++) {\n if (sec.subColumns[s]?.span.isEnd) {\n spanEnd = { masterColumnIndex: m, sectionIndex: secIdx, subColumnIndex: s };\n break outer;\n }\n }\n }\n }\n\n const elements = subColumn.elements;\n for (const element of elements) {\n element.span = {\n masterColumnStart: spanStart.masterColumnIndex,\n masterColumnEnd: spanEnd.masterColumnIndex,\n sectionStart: spanStart.sectionIndex,\n sectionEnd: spanEnd.sectionIndex,\n subColumnStart: spanStart.subColumnIndex,\n subColumnEnd: spanEnd.subColumnIndex,\n };\n }\n }\n }\n }\n };\n\n return {\n grid: newGrid,\n pushMasterColumn,\n calculateDimensions,\n setupElementSpans,\n };\n};\n","import { BracketMasterColumnSection } from './bracket-master-column-section';\nimport { Dimensions, Spacing } from './types';\n\nexport type BracketMasterColumn<TRoundData, TMatchData> = {\n sections: ReadonlyArray<BracketMasterColumnSection<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n padding: Spacing;\n};\n\nexport type CreateBracketMasterColumnConfig = {\n columnWidth: number;\n padding: Spacing;\n};\n\nexport type MutableBracketMasterColumn<TRoundData, TMatchData> = {\n masterColumn: BracketMasterColumn<TRoundData, TMatchData>;\n pushSection: (...sections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketMasterColumnConfig,\n): MutableBracketMasterColumn<TRoundData, TMatchData> => {\n const { columnWidth, padding } = config;\n\n const sections: BracketMasterColumnSection<TRoundData, TMatchData>[] = [];\n\n const newMasterColumn: BracketMasterColumn<TRoundData, TMatchData> = {\n dimensions: {\n width: columnWidth,\n height: 0,\n top: 0,\n left: 0,\n },\n padding,\n sections,\n };\n\n const pushSection = (...newSections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => {\n sections.push(...newSections);\n };\n\n return {\n masterColumn: newMasterColumn,\n pushSection,\n };\n};\n","import { BracketSubColumn } from './bracket-sub-column';\nimport { Dimensions, Spacing } from './types';\n\nexport type BracketMasterColumnSectionType = 'round' | 'gap';\n\nexport type BracketMasterColumnSection<TRoundData, TMatchData> = {\n subColumns: ReadonlyArray<BracketSubColumn<TRoundData, TMatchData>>;\n dimensions: Dimensions;\n type: BracketMasterColumnSectionType;\n\n /** Overrides the master column padding for this section */\n padding?: Spacing;\n};\n\nexport type CreateBracketMasterColumnSectionConfig = {\n type: BracketMasterColumnSectionType;\n padding?: Spacing;\n};\n\nexport type MutableBracketMasterColumnSection<TRoundData, TMatchData> = {\n masterColumnSection: BracketMasterColumnSection<TRoundData, TMatchData>;\n pushSubColumn: (...subColumns: BracketSubColumn<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketMasterColumnSection = <TRoundData, TMatchData>(\n config: CreateBracketMasterColumnSectionConfig,\n): MutableBracketMasterColumnSection<TRoundData, TMatchData> => {\n const { type, padding } = config;\n\n const subColumns: BracketSubColumn<TRoundData, TMatchData>[] = [];\n\n const newMasterColumnSection: BracketMasterColumnSection<TRoundData, TMatchData> = {\n dimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n subColumns,\n type,\n padding,\n };\n\n const pushSubColumn = (...newSubColumns: BracketSubColumn<TRoundData, TMatchData>[]) => {\n subColumns.push(...newSubColumns);\n };\n\n return {\n masterColumnSection: newMasterColumnSection,\n pushSubColumn,\n };\n};\n","import { BracketElement } from './bracket-element';\nimport { Dimensions } from './types';\n\nexport type BracketSubColumn<TRoundData, TMatchData> = {\n dimensions: Dimensions;\n elements: ReadonlyArray<BracketElement<TRoundData, TMatchData>>;\n span: BracketSubColumnSpan;\n};\n\nexport type BracketSubColumnSpan = {\n isStart: boolean;\n isEnd: boolean;\n};\n\nexport type CreateBracketSubColumnConfig = {\n span: BracketSubColumnSpan;\n};\n\nexport type MutableBracketSubColumn<TRoundData, TMatchData> = {\n subColumn: BracketSubColumn<TRoundData, TMatchData>;\n pushElement: (...elements: BracketElement<TRoundData, TMatchData>[]) => void;\n};\n\nexport const createBracketSubColumn = <TRoundData, TMatchData>(\n config: CreateBracketSubColumnConfig,\n): MutableBracketSubColumn<TRoundData, TMatchData> => {\n const { span } = config;\n\n const elements: BracketElement<TRoundData, TMatchData>[] = [];\n\n const newSubColumn: BracketSubColumn<TRoundData, TMatchData> = {\n dimensions: {\n width: 0,\n height: 0,\n top: 0,\n left: 0,\n },\n elements,\n span,\n };\n\n const pushElement = (...newElements: BracketElement<TRoundData, TMatchData>[]) => {\n elements.push(...newElements);\n };\n\n return {\n subColumn: newSubColumn,\n pushElement,\n };\n};\n","import { COMMON_BRACKET_ROUND_TYPE } from '../../../core';\nimport { Bracket, BracketMatch } from '../../../linked';\nimport {\n BracketContinueComponent,\n BracketMasterColumn,\n createBracketElement,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n} from '../core';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport const isBracketContinueMatch = <TRoundData, TMatchData>(match: BracketMatch<TRoundData, TMatchData>) =>\n match.round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE &&\n (match.relation.type === 'one-to-nothing' || match.relation.type === 'two-to-nothing');\n\nexport const getBracketContinueMatches = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n): BracketMatch<TRoundData, TMatchData>[] =>\n Array.from(bracketData.matches.values()).filter((match) => isBracketContinueMatch(match));\n\nexport type CreateBracketContinueMasterColumnConfig<TRoundData, TMatchData> = {\n existingMasterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n columnWidth: number;\n elementHeight: number;\n\n /** Vertical space taken by the round header block (header + gap). 0 if headers are hidden. */\n headerOffset: number;\n component: BracketContinueComponent<TRoundData, TMatchData>;\n matches: BracketMatch<TRoundData, TMatchData>[];\n};\n\nexport const createBracketContinueMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketContinueMasterColumnConfig<TRoundData, TMatchData>,\n) => {\n const { existingMasterColumns, columnWidth, elementHeight, headerOffset, component, matches } = config;\n\n const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];\n\n if (!lastMasterColumn) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'No last master column found in existing master columns',\n );\n }\n\n // Dimensions are not calculated yet at this point, but all part heights are static, so the\n // total column height is the sum of the tallest sub column of every section plus its padding - the\n // same sum `calculateDimensions` makes, which skips the top padding of a leading header section.\n const firstSectionIsHeader = lastMasterColumn.sections[0]?.subColumns[0]?.elements[0]?.type === 'header';\n let totalHeight = 0;\n\n for (const [sectionIndex, section] of lastMasterColumn.sections.entries()) {\n const padding = section.padding ?? lastMasterColumn.padding;\n const paddingTop = sectionIndex === 0 && firstSectionIsHeader ? 0 : padding.top;\n const sectionHeight = Math.max(\n 0,\n ...section.subColumns.map((subColumn) =>\n subColumn.elements.reduce(\n (subColumnHeight, element) =>\n subColumnHeight + element.parts.reduce((sum, part) => sum + part.dimensions.height, 0),\n 0,\n ),\n ),\n );\n\n totalHeight += paddingTop + sectionHeight + padding.bottom;\n }\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n if (headerOffset > 0) {\n const headerGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: headerOffset,\n partHeights: [headerOffset],\n });\n\n pushElement(headerGapElement);\n }\n\n const containerHeight = Math.max(elementHeight, totalHeight - headerOffset);\n\n const continueElement = createBracketElement<TRoundData, TMatchData>({\n area: 'continue',\n type: 'continue',\n elementHeight,\n partHeights: [containerHeight],\n component,\n matches,\n });\n\n pushElement(continueElement);\n\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n\n return masterColumn;\n};\n","import { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\n\nexport type LineOptions = {\n path: PathOptions;\n\n /** Draw right to left - the flow direction of a mirrored bracket's way back. */\n inverted?: boolean;\n};\n\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const linePath = (from: BracketPosition, to: BracketPosition, options: LineOptions) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.end : to.inline.start;\n\n return path(`M ${fromInline} ${from.block.center} L ${toInline} ${to.block.center}`, options.path);\n};\n\n/**\n * The connector between two cards sharing a column, where {@link linePath} and `curvePath` both\n * degenerate to a zero-width horizontal run: straight down (or up) the column, edge to edge.\n */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const verticalPath = (from: BracketPosition, to: BracketPosition, options: LineOptions) => {\n const inline = (from.inline.center + to.inline.center) / 2;\n const isDownwards = to.block.center >= from.block.center;\n\n const fromBlock = isDownwards ? from.block.end : from.block.start;\n const toBlock = isDownwards ? to.block.start : to.block.end;\n\n return path(`M ${inline} ${fromBlock} V ${toBlock}`, options.path);\n};\n\nexport type GutterLineOptions = LineOptions & {\n /** How far past the column's edge the vertical run sits - half a column gap keeps it clear of both. */\n gutter: number;\n};\n\n/**\n * A same-column connector for two cards with others stacked between them: out sideways, along the\n * empty strip beside the column, and back in. {@link verticalPath} would run through everything in\n * its way.\n */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nexport const gutterPath = (from: BracketPosition, to: BracketPosition, options: GutterLineOptions) => {\n const inverted = options.inverted ?? false;\n\n const fromInline = inverted ? from.inline.start : from.inline.end;\n const toInline = inverted ? to.inline.start : to.inline.end;\n const runInline = inverted\n ? Math.min(fromInline, toInline) - options.gutter\n : Math.max(fromInline, toInline) + options.gutter;\n\n return path(`M ${fromInline} ${from.block.center} H ${runInline} V ${to.block.center} H ${toInline}`, options.path);\n};\n","import { BRACKET_ROUND_MIRROR_TYPE, COMMON_BRACKET_ROUND_TYPE } from '../core';\nimport { CurveOptions, curvePath, curveStraightStart } from './curve';\nimport { Dimensions } from './grid/core/types';\nimport { BRACKET_FINAL_ALIGNMENT, ComputedBracketGrid } from './grid/types';\nimport { isBracketContinueMatch } from './grid/prebuild/bracket-continue-master-column';\nimport { gutterPath, linePath, LineOptions, verticalPath } from './line';\nimport { BracketPosition } from './math';\nimport { path, PathOptions } from './path';\nimport { BracketDrawing, BracketEdge } from './shapes';\n\nexport type DrawManDimensions<TRoundData, TMatchData> = {\n columnWidth: number;\n matchHeight: number;\n roundHeaderHeight: number;\n columnGap: number;\n upperLowerGap: number;\n rowGap: number;\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>;\n path: Omit<PathOptions, 'className' | 'id'>;\n curve: Omit<CurveOptions, 'path' | 'inverted'>;\n\n /** Path options for the lines connecting the continuing matches to the continue element */\n continuePath?: Omit<PathOptions, 'className' | 'id'>;\n};\n\nconst makePos = (dimensions: Dimensions): BracketPosition => ({\n block: {\n start: dimensions.top,\n end: dimensions.top + dimensions.height,\n center: dimensions.top + dimensions.height / 2,\n },\n inline: {\n start: dimensions.left,\n end: dimensions.left + dimensions.width,\n center: dimensions.left + dimensions.width / 2,\n },\n});\n\n/**\n * Two cards in the same column - the shape a stacked layout's centre chain makes, where a round hangs\n * directly below the one that feeds it and every horizontal run has zero width.\n */\nconst isSameColumn = (from: BracketPosition, to: BracketPosition) =>\n Math.abs(from.inline.center - to.inline.center) < 1;\n\n/** A one-to-one connector, whichever way round the two cards sit. */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nconst straightPath = (from: BracketPosition, to: BracketPosition, options: LineOptions) =>\n isSameColumn(from, to) ? verticalPath(from, to, options) : linePath(from, to, options);\n\n/** One arm of a merge, bending towards its card, collapsing to a straight run when the two share a column. */\n// eslint-disable-next-line max-params -- geometry helper: (from, to, options) reads naturally positional\nconst mergePath = (from: BracketPosition, to: BracketPosition, options: CurveOptions) =>\n isSameColumn(from, to)\n ? verticalPath(from, to, { path: options.path })\n : curvePath(from, to, to.block.center >= from.block.center ? 'down' : 'up', options);\n\nconst edgeId = (fromMatchId: string, toMatchId: string) => `${fromMatchId}|${toMatchId}`;\n\nexport const drawMan = <TRoundData, TMatchData>(\n dimensions: DrawManDimensions<TRoundData, TMatchData>,\n): BracketDrawing => {\n const edges: BracketEdge[] = [];\n const takenIds = new Set<string>();\n\n // A repeated id would make the host's `@for` throw, and a mirrored fold can draw the same pair of\n // cards from both of its sides.\n const pushEdge = (edge: BracketEdge) => {\n let id = edge.id;\n\n for (let attempt = 2; takenIds.has(id); attempt++) id = `${edge.id}#${attempt}`;\n\n takenIds.add(id);\n edges.push(id === edge.id ? edge : { ...edge, id });\n };\n\n const continueElement = dimensions.bracketGrid.columns\n .flatMap((col) => col.elements)\n .find((el) => el.type === 'continue');\n const continuePos = continueElement ? makePos(continueElement.dimensions) : null;\n const continueSources: { pos: BracketPosition; className: string; matchId: string }[] = [];\n\n for (const col of dimensions.bracketGrid.columns) {\n for (const el of col.elements) {\n if (el.type !== 'match') continue;\n\n const currentMatchParticipantsShortIds = [el.match.home?.shortId, el.match.away?.shortId]\n .filter((id) => !!id)\n .join(' ');\n\n const currentPos = makePos(el.dimensions);\n\n if (el.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;\n\n if (continuePos && isBracketContinueMatch(el.match)) {\n continueSources.push({\n pos: currentPos,\n className: el.match.winner?.shortId || '',\n matchId: el.match.id,\n });\n }\n\n // Crossing the middle of a fold. Every other line here is drawn by the match it flows *into*, but a\n // round in the middle of a mirrored bracket is fed from both sides and its relation names only one\n // of them - so the round on the way back draws its own line. Deliberately outside the switch below:\n // which relation a match has says nothing about which side of a fold it sits on.\n if (el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT && 'nextMatch' in el.match.relation) {\n const { nextMatch, nextRound } = el.match.relation;\n\n if (nextRound.mirrorRoundType === null) {\n const next = dimensions.bracketGrid.matchElementMap.getOrThrow(nextMatch.id);\n\n // The winner's short id, not both participants': this line is somebody advancing along it, and\n // the journey highlight lights the path a participant actually travelled.\n pushEdge(\n straightPath(makePos(next.dimensions), currentPos, {\n path: {\n ...dimensions.path,\n id: edgeId(nextMatch.id, el.match.id),\n className: el.match.winner?.shortId || '',\n },\n }),\n );\n }\n }\n\n switch (el.match.relation.type) {\n case 'none':\n case 'nothing-to-one': {\n continue;\n }\n case 'one-to-nothing':\n case 'one-to-one': {\n const prev = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousMatch.id);\n const prevPos = makePos(prev.dimensions);\n\n // The winner of the match it comes from, like every other connector, or the journey highlight\n // lights the line for whoever arrived from somewhere else.\n pushEdge(\n straightPath(prevPos, currentPos, {\n path: {\n ...dimensions.path,\n id: edgeId(el.match.relation.previousMatch.id, el.match.id),\n className: el.match.relation.previousMatch.winner?.shortId || '',\n },\n // The way back runs right to left: the round it comes from sits on the *other* side.\n inverted: el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT,\n }),\n );\n\n break;\n }\n\n case 'two-to-nothing':\n case 'two-to-one': {\n const prevUpper = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousUpperMatch.id);\n const prevLower = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousLowerMatch.id);\n\n const prevUpperPos = makePos(prevUpper.dimensions);\n const prevLowerPos = makePos(prevLower.dimensions);\n\n const upperId = edgeId(el.match.relation.previousUpperMatch.id, el.match.id);\n const lowerId = edgeId(el.match.relation.previousLowerMatch.id, el.match.id);\n\n const isLowerUpperMerger =\n el.match.relation.previousLowerRound.id !== el.match.relation.previousUpperRound.id;\n\n const invertCurve = el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;\n\n const baseCurveOptions: CurveOptions = {\n ...dimensions.curve,\n inverted: invertCurve,\n path: { ...dimensions.path, id: upperId, className: '' },\n };\n\n const isUpperStraight =\n isLowerUpperMerger && dimensions.bracketGrid.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER;\n\n // A feeder directly *below* in the same column is the one connector a stacked layout has that\n // crosses its own cards - the losers champion coming up to the grand final, past everything\n // hanging under it. Every other same-column pair is adjacent, so a straight run is clear.\n const isBlockToBlock =\n isSameColumn(prevLowerPos, currentPos) && prevLowerPos.block.start > currentPos.block.end;\n\n const isSharedEnd =\n !isUpperStraight &&\n !isBlockToBlock &&\n !isSameColumn(prevUpperPos, currentPos) &&\n !isSameColumn(prevLowerPos, currentPos);\n\n // Both arms of a merge end on the same straight run into the card. Drawn by each arm, the\n // run is twice as bright as every other line, and fades with whichever arm the journey\n // highlight leaves out.\n const sharedEndInline = isSharedEnd\n ? (invertCurve ? Math.min : Math.max)(\n curveStraightStart(prevUpperPos, currentPos, baseCurveOptions),\n curveStraightStart(prevLowerPos, currentPos, baseCurveOptions),\n )\n : undefined;\n\n const curveOptions: CurveOptions = { ...baseCurveOptions, endInline: sharedEndInline };\n\n if (isUpperStraight) {\n pushEdge(\n straightPath(prevUpperPos, currentPos, {\n path: { ...dimensions.path, id: upperId, className: currentMatchParticipantsShortIds },\n inverted: invertCurve,\n }),\n );\n } else {\n pushEdge(\n mergePath(prevUpperPos, currentPos, {\n ...curveOptions,\n path: {\n ...curveOptions.path,\n className: el.match.relation.previousUpperMatch.winner?.shortId || '',\n },\n }),\n );\n }\n\n const lowerPathOptions = {\n ...curveOptions.path,\n id: lowerId,\n className: el.match.relation.previousLowerMatch.winner?.shortId || '',\n };\n\n pushEdge(\n isBlockToBlock\n ? gutterPath(prevLowerPos, currentPos, {\n // Dashed, like the continue column's: it runs the height of a block past cards it has\n // nothing to do with, and reads as a stray bracket edge if it looks like one.\n path: {\n ...(dimensions.continuePath ?? dimensions.path),\n id: lowerId,\n className: lowerPathOptions.className,\n },\n inverted: invertCurve,\n gutter: dimensions.columnGap / 2,\n })\n : mergePath(prevLowerPos, currentPos, { ...curveOptions, path: lowerPathOptions }),\n );\n\n if (sharedEndInline !== undefined) {\n const winners = [\n el.match.relation.previousUpperMatch.winner?.shortId,\n el.match.relation.previousLowerMatch.winner?.shortId,\n ].filter((shortId) => !!shortId);\n const toInline = invertCurve ? currentPos.inline.end : currentPos.inline.start;\n\n pushEdge(\n path(`M ${sharedEndInline} ${currentPos.block.center} H ${toInline}`, {\n ...dimensions.path,\n id: edgeId(el.match.id, 'in'),\n className: winners.join(' '),\n }),\n );\n }\n\n break;\n }\n }\n }\n }\n\n if (continuePos && continueSources.length) {\n const continuePathOptions = dimensions.continuePath ?? dimensions.path;\n const curveAmount = dimensions.curve.lineStartingCurveAmount;\n const trunkInline = continuePos.inline.start - dimensions.columnGap / 2;\n const continueBlockCenter = continuePos.block.center;\n const sourceBlocks = continueSources.map((source) => source.pos.block.center);\n const firstSourceBlock = Math.min(...sourceBlocks);\n const lastSourceBlock = Math.max(...sourceBlocks);\n const trunkBlocks: number[] = [continueBlockCenter];\n\n for (const source of continueSources) {\n const sourceBlockCenter = source.pos.block.center;\n const blockDistance = continueBlockCenter - sourceBlockCenter;\n const sourcePathOptions: PathOptions = {\n ...continuePathOptions,\n id: edgeId(source.matchId, 'continue'),\n className: source.className,\n };\n\n const isTrunkCorner =\n (sourceBlockCenter === firstSourceBlock && blockDistance > 0.5) ||\n (sourceBlockCenter === lastSourceBlock && blockDistance < -0.5);\n\n // The straight run into the trunk is the same three commands with a zero-radius corner, so that a\n // source turning into a corner as the rows move animates rather than jumping.\n const curve = isTrunkCorner ? Math.min(curveAmount, Math.abs(blockDistance)) : 0;\n const curveEndBlock = sourceBlockCenter + curve * Math.sign(blockDistance);\n\n pushEdge(\n path(\n `M ${source.pos.inline.end} ${sourceBlockCenter}\n H ${trunkInline - curve}\n Q ${trunkInline} ${sourceBlockCenter}, ${trunkInline} ${curveEndBlock}`,\n sourcePathOptions,\n ),\n );\n\n trunkBlocks.push(curveEndBlock);\n }\n\n const trunkBlockStart = Math.min(...trunkBlocks);\n const trunkBlockEnd = Math.max(...trunkBlocks);\n\n if (trunkBlockEnd - trunkBlockStart > 0.5) {\n pushEdge(\n path(`M ${trunkInline} ${trunkBlockStart} V ${trunkBlockEnd}`, {\n ...continuePathOptions,\n id: 'continue|trunk',\n className: '',\n }),\n );\n }\n\n pushEdge(\n path(`M ${trunkInline} ${continueBlockCenter} H ${continuePos.inline.start}`, {\n ...continuePathOptions,\n id: 'continue|element',\n className: '',\n }),\n );\n }\n\n return { edges, rects: [], gradients: [] };\n};\n","import { BracketRoundId } from '../core';\nimport { BracketSwissColors, BracketSwissGroupColorType } from '../linked/swiss';\nimport { curvePath } from './curve';\nimport { FinalizedBracketElement, FinalizedMatchBracketElement } from './grid/core/bracket-finalizer';\nimport { ComputedBracketGrid } from './grid/types';\nimport { BracketPosition } from './math';\nimport { PathOptions } from './path';\nimport { BracketDrawing, BracketEdge, BracketGradient, BracketRect } from './shapes';\n\nexport type DrawSwissManDimensions<TRoundData, TMatchData> = {\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>;\n path: Omit<PathOptions, 'className' | 'stroke' | 'id'>;\n\n // The swiss connection lines always bend twice with the same radius, so there is no\n // dedicated ending curve amount (it would make no sense here).\n curve: {\n lineStartingCurveAmount: number;\n };\n groupBorder: {\n padding: number;\n radius: number;\n width: number;\n };\n colors?: BracketSwissColors;\n\n /** Used to create document wide unique ids for the connection line gradients */\n idPrefix: string;\n};\n\ntype SwissGroupGeometry = {\n id: string;\n wins: number;\n losses: number;\n colorType: BracketSwissGroupColorType;\n position: BracketPosition;\n winnerShortIds: string[];\n loserShortIds: string[];\n};\n\ntype SwissRoundGeometry = {\n groups: Map<string, SwissGroupGeometry>;\n};\n\n// Every finalized column of a swiss grid is one group section. The connection lines run\n// from group to group instead of match to match: the winners of group (w-l) move to group\n// (w+1-l) inside the next round, the losers move to group (w-l+1).\nconst collectSwissRoundGeometries = <TRoundData, TMatchData>(\n bracketGrid: ComputedBracketGrid<TRoundData, TMatchData>,\n): SwissRoundGeometry[] => {\n const rounds = new Map<BracketRoundId, SwissRoundGeometry>();\n\n for (const column of bracketGrid.columns) {\n const matchElements = column.elements.filter(\n (\n element: FinalizedBracketElement<TRoundData, TMatchData>,\n ): element is FinalizedMatchBracketElement<TRoundData, TMatchData> => element.type === 'match',\n );\n const group = matchElements[0]?.roundSwissGroup;\n const round = matchElements[0]?.round;\n\n if (!group || !round) continue;\n\n const [wins, losses] = group.id.split('-').map(Number);\n\n if (wins === undefined || losses === undefined || isNaN(wins) || isNaN(losses)) continue;\n\n const matchesTop = Math.min(...matchElements.map((element) => element.dimensions.top));\n const matchesBottom = Math.max(\n ...matchElements.map((element) => element.dimensions.top + element.dimensions.height),\n );\n\n const winnerShortIds: string[] = [];\n const loserShortIds: string[] = [];\n\n for (const element of matchElements) {\n if (!element.match.winner) continue;\n\n const winner = element.match.winner;\n const loser = element.match.home?.id === winner.id ? element.match.away : element.match.home;\n\n winnerShortIds.push(winner.shortId);\n if (loser) loserShortIds.push(loser.shortId);\n }\n\n // The lines attach to the group border, which wraps the matches plus the group\n // padding and therefore matches the section bounds horizontally.\n const position: BracketPosition = {\n block: {\n start: matchesTop,\n end: matchesBottom,\n center: (matchesTop + matchesBottom) / 2,\n },\n inline: {\n start: column.dimensions.left,\n end: column.dimensions.left + column.dimensions.width,\n center: column.dimensions.left + column.dimensions.width / 2,\n },\n };\n\n let roundGeometry = rounds.get(round.id);\n\n if (!roundGeometry) {\n roundGeometry = { groups: new Map() };\n rounds.set(round.id, roundGeometry);\n }\n\n roundGeometry.groups.set(group.id, {\n id: group.id,\n wins,\n losses,\n colorType: group.colorType,\n position,\n winnerShortIds,\n loserShortIds,\n });\n }\n\n // The finalized columns are ordered left to right, so first appearance equals round order\n return Array.from(rounds.values());\n};\n\nconst groupBorderRect = (\n group: SwissGroupGeometry,\n border: DrawSwissManDimensions<unknown, unknown>['groupBorder'],\n color: string | undefined,\n id: string,\n // eslint-disable-next-line max-params -- SVG geometry helper; (group, border, color, id) are distinct positional inputs\n): BracketRect => {\n // The group box wraps the matches plus the group padding plus the border itself. The\n // rect is inset by half the stroke width so the stroke renders fully inside the group\n // bounds instead of getting cut off at the edges of the bracket container.\n const boxPadding = border.padding + border.width;\n const strokeInset = border.width / 2;\n\n return {\n id,\n x: group.position.inline.start + strokeInset,\n y: group.position.block.start - boxPadding + strokeInset,\n width: group.position.inline.end - group.position.inline.start - border.width,\n height: group.position.block.end - group.position.block.start + boxPadding * 2 - border.width,\n radius: border.radius,\n stroke: color ?? 'currentColor',\n strokeWidth: border.width,\n tone: group.colorType,\n cssClass: `et-bracket-swiss-group-border et-bracket-swiss-group-border--${group.id} et-bracket-swiss-group-border--${group.colorType}`,\n };\n};\n\ntype SwissLineGradient = {\n id: string;\n fromX: number;\n toX: number;\n from: string;\n neutral: string;\n to: string;\n};\n\n// A horizontal gradient for the connection lines: they leave the source group in its\n// color, fade to the neutral color towards their vertical jog in the middle and fade into\n// the target group color on the second half. The connection lines always run from left to\n// right, so user space coordinates can be used (they also work for straight lines, where\n// the bounding box has no height).\nconst lineGradient = (config: SwissLineGradient): BracketGradient => ({\n id: config.id,\n fromX: config.fromX,\n toX: config.toX,\n stops: [\n { offset: '0%', color: config.from },\n { offset: '50%', color: config.neutral },\n { offset: '100%', color: config.to },\n ],\n});\n\nexport const drawSwissMan = <TRoundData, TMatchData>(\n dimensions: DrawSwissManDimensions<TRoundData, TMatchData>,\n): BracketDrawing => {\n const edges: BracketEdge[] = [];\n const rects: BracketRect[] = [];\n const gradients: BracketGradient[] = [];\n\n const roundGeometries = collectSwissRoundGeometries(dimensions.bracketGrid);\n const colors = dimensions.colors;\n\n for (const [roundIndex, roundGeometry] of roundGeometries.entries()) {\n for (const group of roundGeometry.groups.values()) {\n rects.push(\n groupBorderRect(group, dimensions.groupBorder, colors?.[group.colorType], `r${roundIndex}|${group.id}`),\n );\n }\n }\n\n const curveOptions = {\n lineStartingCurveAmount: dimensions.curve.lineStartingCurveAmount,\n lineEndingCurveAmount: dimensions.curve.lineStartingCurveAmount,\n };\n\n for (const [roundIndex, roundGeometry] of roundGeometries.entries()) {\n const nextRoundGeometry = roundGeometries[roundIndex + 1];\n\n if (!nextRoundGeometry) break;\n\n for (const group of roundGeometry.groups.values()) {\n const targets = [\n { geometry: nextRoundGeometry.groups.get(`${group.wins + 1}-${group.losses}`), shortIds: group.winnerShortIds },\n { geometry: nextRoundGeometry.groups.get(`${group.wins}-${group.losses + 1}`), shortIds: group.loserShortIds },\n ];\n\n for (const { geometry: target, shortIds } of targets) {\n if (!target) continue;\n\n const edgeId = `r${roundIndex}|${group.id}|${target.id}`;\n // Only URI characters: this ends up inside a `url(#…)` the `stroke` attribute has to resolve.\n const gradientId = `${dimensions.idPrefix}-swiss-line-r${roundIndex}-${group.id}-to-${target.id}`;\n const neutralColor = colors?.neutral;\n\n let stroke = neutralColor;\n\n if (neutralColor) {\n const from = colors?.[group.colorType] ?? neutralColor;\n const to = colors?.[target.colorType] ?? neutralColor;\n\n if (from !== neutralColor || to !== neutralColor) {\n gradients.push(\n lineGradient({\n id: gradientId,\n fromX: group.position.inline.end,\n toX: target.position.inline.start,\n from,\n neutral: neutralColor,\n to,\n }),\n );\n\n stroke = `url(#${gradientId})`;\n }\n }\n\n const pathOptions: PathOptions = {\n ...dimensions.path,\n id: edgeId,\n className: shortIds.join(' '),\n stroke,\n };\n const blockDelta = target.position.block.center - group.position.block.center;\n\n // Always a curve, even between two groups on the same row, where the bends collapse to nothing\n // and it draws as a straight run - one shape per connector is what lets it animate.\n edges.push(\n curvePath(group.position, target.position, blockDelta < 0 ? 'up' : 'down', {\n ...curveOptions,\n path: pathOptions,\n }),\n );\n }\n }\n }\n\n return { edges, rects, gradients };\n};\n","export const calculateUpperLowerRatio = (upperRoundsCount: number, lowerRoundsCount: number) => {\n const remainingUpperRounds = upperRoundsCount - 1;\n const remainingLowerRounds = lowerRoundsCount - 1;\n\n if (remainingUpperRounds === 0) return 1;\n\n return remainingLowerRounds / remainingUpperRounds;\n};\n\nexport const calculateColumnSplitFactor = (upperToLowerRatio: number) => (upperToLowerRatio === 1.5 ? 2 : 1);\n\nexport const calculateLowerRoundIndex = (subColumnIndex: number, splitFactor: number) =>\n Math.floor(subColumnIndex / splitFactor);\n\n// eslint-disable-next-line max-params -- index math over positional grid coordinates\nexport const calculateUpperRoundIndex = (subColumnIndex: number, upperToLowerRatio: number, splitFactor: number) => {\n const completeColumnIndex = Math.floor(subColumnIndex / splitFactor);\n\n if (completeColumnIndex === 0) return 0;\n\n return Math.floor((completeColumnIndex - 1) / upperToLowerRatio) + 1;\n};\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../../core';\nimport { BracketRound } from '../../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n BracketSubColumnSpan,\n createBracketElement,\n createBracketSubColumn,\n} from '../core';\nimport { CreateBracketGridConfig } from '../types';\n\nexport type CreateRoundBracketSubColumnRelativeToFirstRoundConfig<TRoundData, TMatchData> = {\n firstRound: BracketRound<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n span: BracketSubColumnSpan;\n hasReverseFinal: boolean;\n options: CreateBracketGridConfig;\n components: BracketComponents<TRoundData, TMatchData>;\n\n /**\n * Reserved space below the last match, for a layout whose columns are taller than the first round\n * needs - a stacked bracket's centre chain hanging past the bottom of its block.\n */\n bottomPadding?: number;\n\n topPadding?: number;\n\n /**\n * How many first-round rows each of this round's matches owns. Derived from the round's own match\n * count when unset; a folded round is placed by its offset instead and takes `1`.\n */\n matchFactor?: number;\n};\n\nexport const createRoundBracketSubColumnRelativeToFirstRound = <TRoundData, TMatchData>(\n config: CreateRoundBracketSubColumnRelativeToFirstRoundConfig<TRoundData, TMatchData>,\n) => {\n const { firstRound, round, options, span, hasReverseFinal } = config;\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span,\n });\n\n const matchFactor =\n config.matchFactor ?? Math.max(1, (options.rowSpanMatchCount ?? firstRound.matchCount) / round.matchCount);\n const matches = Array.from(round.matches.values());\n\n const isFinalRound = hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n const roundHeaderGap = isFinalRound\n ? Math.max(options.roundHeaderGap, options.finalRoundHeaderGap ?? 0)\n : options.roundHeaderGap;\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n if (options.roundHeaderHeight > 0) {\n elementsToCreate.push(\n {\n type: 'header',\n area: `h${round.shortId}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: config.components.roundHeader,\n round,\n roundSwissGroup: null,\n },\n {\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [roundHeaderGap],\n elementHeight: roundHeaderGap,\n },\n );\n }\n\n if (config.topPadding) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [config.topPadding],\n elementHeight: config.topPadding,\n });\n }\n\n for (const [matchIndex, match] of matches.entries()) {\n const isLastMatch = matchIndex === matches.length - 1;\n\n // One row per match this one is fed by. A fractional factor has no whole feeder row to align to,\n // so floor it and let the block padding below absorb the remainder - rounding up instead emits a\n // row the block height cannot pay for, and the padding turns negative to compensate.\n const fedMatchCount = Math.floor(matchFactor);\n const matchRows: number[] = [];\n\n for (let factorIndex = 0; factorIndex < fedMatchCount; factorIndex++) {\n matchRows.push(options.matchHeight);\n\n if (factorIndex < fedMatchCount - 1) matchRows.push(options.rowGap);\n }\n\n const elementHeight = isFinalRound ? options.finalMatchHeight : options.matchHeight;\n const blockHeight = Math.max(elementHeight, matchFactor * options.matchHeight + (matchFactor - 1) * options.rowGap);\n const currentBlockHeight = matchRows.reduce((total, height) => total + height, 0);\n\n matchRows[matchRows.length - 1] = (matchRows[matchRows.length - 1] ?? 0) + blockHeight - currentBlockHeight;\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: matchRows,\n elementHeight,\n component: isFinalRound ? config.components.finalMatch : config.components.match,\n match,\n round,\n roundSwissGroup: null,\n });\n\n if (!isLastMatch) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [options.rowGap],\n elementHeight: options.rowGap,\n });\n }\n }\n\n if (config.bottomPadding) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [config.bottomPadding],\n elementHeight: config.bottomPadding,\n });\n }\n\n for (const elementData of elementsToCreate) {\n const element = createBracketElement(elementData);\n\n pushElement(element);\n }\n\n return subColumn;\n};\n","import { BracketRound } from '../../../linked';\nimport {\n BracketComponents,\n BracketElement,\n BracketMasterColumnSection,\n BracketSubColumn,\n createBracketMasterColumnSection,\n} from '../core';\nimport { CreateBracketGridConfig } from '../types';\nimport { createRoundBracketSubColumnRelativeToFirstRound } from './bracket-sub-column-relative-to-first-round';\n\nexport type CreateFoldedThirdPlaceSectionConfig<TRoundData, TMatchData> = {\n /** The sub column holding the final, which the folded round is placed relative to. */\n finalSubColumn: BracketSubColumn<TRoundData, TMatchData>;\n round: BracketRound<TRoundData, TMatchData>;\n /** How far below the top of the final's card the third place card sits, in px. */\n topOffset: number;\n options: CreateBracketGridConfig;\n components: BracketComponents<TRoundData, TMatchData>;\n};\n\nconst heightOfElement = <TRoundData, TMatchData>(element: BracketElement<TRoundData, TMatchData>) =>\n element.parts.reduce((total, part) => total + part.dimensions.height, 0);\n\nconst cardGeometry = <TRoundData, TMatchData>(subColumn: BracketSubColumn<TRoundData, TMatchData>) => {\n let height = 0;\n let cardTop: number | null = null;\n\n for (const element of subColumn.elements) {\n const elementHeight = heightOfElement(element);\n\n if (element.type === 'match' && cardTop === null) {\n cardTop = height + (elementHeight - element.dimensions.height) / 2;\n }\n\n height += elementHeight;\n }\n\n return { cardTop: cardTop ?? 0, height };\n};\n\n/**\n * The third place match as a second section of the final's master column: one card the given number of\n * px below the top of the final's, with its own round header above it.\n *\n * @internal\n */\nexport const createFoldedThirdPlaceSection = <TRoundData, TMatchData>(\n config: CreateFoldedThirdPlaceSectionConfig<TRoundData, TMatchData>,\n): BracketMasterColumnSection<TRoundData, TMatchData> => {\n const { options, round } = config;\n const final = cardGeometry(config.finalSubColumn);\n const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n\n // The section stacks below the final's, so what it has to make up is the offset less the room the\n // final's own section already takes. Negative when the fold lands inside that room, which is the\n // ordinary case: the final's block owns the rows of every round feeding it, so it is far taller\n // than its card.\n const paddingTop = final.cardTop + config.topOffset - final.height - headerOffset;\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n padding: { top: paddingTop, bottom: 0, left: 0, right: 0 },\n });\n\n pushSubColumn(\n createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: round,\n round,\n options,\n hasReverseFinal: false,\n // Placed by its offset, so it owns one row rather than the block a squeezed round would give it.\n matchFactor: 1,\n span: { isStart: true, isEnd: true },\n components: config.components,\n }),\n );\n\n return masterColumnSection;\n};\n","import {\n BracketElementToCreate,\n BracketMasterColumn,\n createBracketElement,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n} from '../core';\nimport { BracketRuntimeError } from '../../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../../bracket-errors';\n\nexport type CreateBracketGapMasterColumnConfig<TRoundData, TMatchData> = {\n existingMasterColumns: ReadonlyArray<BracketMasterColumn<TRoundData, TMatchData>>;\n columnGap: number;\n};\n\nexport const createBracketGapMasterColumn = <TRoundData, TMatchData>(\n config: CreateBracketGapMasterColumnConfig<TRoundData, TMatchData>,\n) => {\n const { existingMasterColumns, columnGap } = config;\n\n const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];\n\n if (!lastMasterColumn) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'No last master column found in existing master columns',\n );\n }\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: columnGap,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n for (const section of lastMasterColumn.sections) {\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n padding: section.padding && { ...section.padding, left: 0, right: 0 },\n });\n\n const lastSubColumn = section.subColumns[section.subColumns.length - 1];\n\n if (!lastSubColumn) {\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No last sub column found in section');\n }\n\n const { pushElement, subColumn } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: lastSubColumn.span.isEnd ? true : false,\n isEnd: lastSubColumn.span.isEnd ? true : false,\n },\n });\n\n for (const lastSubColumnElement of lastSubColumn.elements) {\n const partHeights = lastSubColumnElement.parts.map((part) => part.dimensions.height);\n\n const elementToCreate: BracketElementToCreate<TRoundData, TMatchData> = (() => {\n switch (lastSubColumnElement.type) {\n case 'matchGap':\n case 'roundHeaderGap':\n case 'roundGap':\n case 'colGap': {\n return {\n area: !lastSubColumn.span.isEnd ? lastSubColumnElement.area : `.`,\n type: !lastSubColumn.span.isEnd ? lastSubColumnElement.type : 'colGap',\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n };\n }\n case 'header':\n if (lastSubColumn.span.isEnd) break;\n\n return {\n area: lastSubColumnElement.area,\n type: lastSubColumnElement.type,\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n component: lastSubColumnElement.component,\n round: lastSubColumnElement.round,\n roundSwissGroup: lastSubColumnElement.roundSwissGroup,\n };\n\n case 'match':\n if (lastSubColumn.span.isEnd) break;\n\n return {\n area: lastSubColumnElement.area,\n type: lastSubColumnElement.type,\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n component: lastSubColumnElement.component,\n round: lastSubColumnElement.round,\n match: lastSubColumnElement.match,\n roundSwissGroup: lastSubColumnElement.roundSwissGroup,\n };\n }\n\n return {\n area: `.`,\n type: 'colGap',\n elementHeight: lastSubColumnElement.dimensions.height,\n partHeights,\n };\n })();\n\n pushElement(createBracketElement<TRoundData, TMatchData>(elementToCreate));\n }\n\n pushSubColumn(subColumn);\n\n pushSection(masterColumnSection);\n }\n\n return masterColumn;\n};\n","import { BracketRound } from '../../linked';\nimport { CreateBracketGridConfig } from './types';\n\nexport const resolveBracketGridRowSpan = <TRoundData, TMatchData>(\n bracket: { rounds: { values(): Iterable<BracketRound<TRoundData, TMatchData>> } },\n options: CreateBracketGridConfig,\n) => {\n if (!options.rowSpanRoundId) return options;\n\n const round = Array.from(bracket.rounds.values()).find(\n (candidate) =>\n candidate.id === options.rowSpanRoundId || candidate.id.startsWith(`${options.rowSpanRoundId}--half-`),\n );\n\n return round ? { ...options, rowSpanMatchCount: round.matchCount } : options;\n};\n","import { BRACKET_DATA_LAYOUT, COMMON_BRACKET_ROUND_TYPE } from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketSubColumn,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n BracketMasterColumnSection,\n finalizeBracketGrid,\n} from './core';\nimport {\n createBracketContinueMasterColumn,\n createBracketGapMasterColumn,\n createFoldedThirdPlaceSection,\n createRoundBracketSubColumnRelativeToFirstRound,\n getBracketContinueMatches,\n} from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\n// A mirrored grid has no free column for the third place: one between the final and a right half would\n// sit on the straight connector between them.\nconst resolveThirdPlaceTopOffset = (options: CreateBracketGridConfig) => {\n if (options.thirdPlaceTopOffset !== null && options.thirdPlaceTopOffset !== undefined) {\n return options.thirdPlaceTopOffset;\n }\n\n if (options.layout !== BRACKET_DATA_LAYOUT.MIRRORED) return null;\n\n const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n\n return options.finalMatchHeight + options.rowGap + headerOffset;\n};\n\nconst resolveFoldedThirdPlaceRound = <TRoundData, TMatchData>(\n rounds: BracketRound<TRoundData, TMatchData>[],\n topOffset: number | null,\n) => {\n if (topOffset === null) return null;\n if (!rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL)) return null;\n\n return rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null;\n};\n\nconst createSectionTitleBand = <TRoundData, TMatchData>(height: number) => {\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: height,\n partHeights: [height],\n }),\n );\n pushSubColumn(subColumn);\n\n return masterColumnSection;\n};\n\nexport const buildSingleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n titleSpace: number,\n // eslint-disable-next-line max-params -- grid builder signature plus the title band height\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n const rounds = Array.from(bracketData.rounds.values());\n const firstRound = bracketData.rounds.first();\n\n if (!firstRound) {\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, 'No rounds found in bracket data');\n }\n\n const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);\n const thirdPlaceTopOffset = resolveThirdPlaceTopOffset(options);\n const foldedThirdPlaceRound = resolveFoldedThirdPlaceRound(rounds, thirdPlaceTopOffset);\n const ownColumnThirdPlaceRound = foldedThirdPlaceRound\n ? null\n : (rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null);\n const chainRounds = rounds.filter((round) => round !== foldedThirdPlaceRound && round !== ownColumnThirdPlaceRound);\n\n let pushSectionToFinal: ((...sections: BracketMasterColumnSection<TRoundData, TMatchData>[]) => void) | null = null;\n let finalSubColumn: BracketSubColumn<TRoundData, TMatchData> | null = null;\n\n const pushGapColumn = () =>\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n const pushRoundColumn = (round: BracketRound<TRoundData, TMatchData>) => {\n const { masterColumn, ...mutableMasterColumn } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: round.type === COMMON_BRACKET_ROUND_TYPE.FINAL ? options.finalColumnWidth : options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const sub = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound,\n round,\n options: resolvedOptions,\n hasReverseFinal: false,\n span: {\n isStart: true,\n isEnd: true,\n },\n components,\n });\n pushSubColumn(sub);\n\n if (titleSpace) mutableMasterColumn.pushSection(createSectionTitleBand(titleSpace));\n\n mutableMasterColumn.pushSection(masterColumnSection);\n\n grid.pushMasterColumn(masterColumn);\n\n return { pushSection: mutableMasterColumn.pushSection, sub };\n };\n\n for (const [roundIndex, round] of chainRounds.entries()) {\n if (roundIndex > 0) pushGapColumn();\n\n const { pushSection, sub } = pushRoundColumn(round);\n\n if (round.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {\n pushSectionToFinal = pushSection;\n finalSubColumn = sub;\n }\n }\n\n // After the loop, so the gap column beside the final mirrors the final's section alone: the folded\n // round has nothing to its right to stay aligned with.\n if (foldedThirdPlaceRound && pushSectionToFinal && finalSubColumn) {\n pushSectionToFinal(\n createFoldedThirdPlaceSection({\n finalSubColumn,\n round: foldedThirdPlaceRound,\n topOffset: thirdPlaceTopOffset ?? 0,\n options: resolvedOptions,\n components,\n }),\n );\n }\n\n if (options.continueElement && components.continue) {\n const continueMatches = getBracketContinueMatches(bracketData);\n\n if (continueMatches.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n grid.pushMasterColumn(\n createBracketContinueMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnWidth: options.continueElement.columnWidth,\n elementHeight: options.continueElement.elementHeight,\n headerOffset:\n titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),\n component: components.continue,\n matches: continueMatches,\n }),\n );\n }\n }\n\n // After the continue column, so the line from the final to the continue element does not cross it.\n if (ownColumnThirdPlaceRound) {\n if (chainRounds.length) pushGapColumn();\n\n pushRoundColumn(ownColumnThirdPlaceRound);\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n\nexport const createSingleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => buildSingleEliminationGrid(bracketData, options, components, 0);\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../core';\nimport { BracketRound } from '../../linked';\nimport { Dimensions, FinalizedBracketColumn } from './core';\n\nexport const BRACKET_SECTION_KEY = {\n UPPER: 'upper',\n LOWER: 'lower',\n FINALS: 'finals',\n} as const;\n\nexport type BracketSectionKey = (typeof BRACKET_SECTION_KEY)[keyof typeof BRACKET_SECTION_KEY];\n\n/** The English name of each section, for a renderer that brings no labels of its own. */\nexport const BRACKET_SECTION_DEFAULT_NAMES: Record<BracketSectionKey, string> = {\n upper: 'Upper bracket',\n lower: 'Lower bracket',\n finals: 'Finals',\n};\n\n/**\n * One part of a bracket - double elimination's upper bracket, lower bracket or finals - as a grid builder\n * placed it.\n */\nexport type BracketGridSection<TRoundData = unknown, TMatchData = unknown> = {\n key: BracketSectionKey;\n name: string;\n rounds: BracketRound<TRoundData, TMatchData>[];\n /** The box around the section's round headers and matches, from the top of the grid rows it occupies. */\n dimensions: Dimensions;\n /** The band the grid reserved for the section's title, `sectionTitleHeight` high and `sectionTitleGap` above `dimensions`. */\n titleDimensions: Dimensions;\n};\n\n/** The section a double elimination round belongs to: the third place playoff counts as one of the finals. */\nexport const doubleEliminationRoundSection = (round: BracketRound<unknown, unknown>): BracketSectionKey => {\n switch (round.type) {\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET:\n return BRACKET_SECTION_KEY.UPPER;\n\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET:\n return BRACKET_SECTION_KEY.LOWER;\n\n case COMMON_BRACKET_ROUND_TYPE.FINAL:\n case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL:\n case COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE:\n default:\n return BRACKET_SECTION_KEY.FINALS;\n }\n};\n\n/**\n * Groups a finalized grid's headers and matches into sections and measures each one, with its title band\n * `titleHeight` px high, `titleGap` px above it. A section starts at its `tops` entry, where the grid builder gives one, so the\n * titles of sections that share a row line up; otherwise at its highest element. Sections come in\n * {@link BRACKET_SECTION_KEY} order; an empty one is left out.\n */\nexport const createBracketGridSections = <TRoundData, TMatchData>(config: {\n columns: FinalizedBracketColumn<TRoundData, TMatchData>[];\n sectionOf: (round: BracketRound<TRoundData, TMatchData>) => BracketSectionKey;\n titleHeight: number;\n titleGap?: number;\n tops?: Partial<Record<BracketSectionKey, number>>;\n}): BracketGridSection<TRoundData, TMatchData>[] => {\n const found = new Map<\n BracketSectionKey,\n { rounds: Set<BracketRound<TRoundData, TMatchData>>; top: number; left: number; right: number; bottom: number }\n >();\n\n for (const column of config.columns) {\n for (const element of column.elements) {\n if (element.type === 'continue') continue;\n\n const key = config.sectionOf(element.round);\n const { top, left, width, height } = element.dimensions;\n const box = found.get(key);\n\n if (!box) {\n found.set(key, { rounds: new Set([element.round]), top, left, right: left + width, bottom: top + height });\n continue;\n }\n\n box.rounds.add(element.round);\n box.top = Math.min(box.top, top);\n box.left = Math.min(box.left, left);\n box.right = Math.max(box.right, left + width);\n box.bottom = Math.max(box.bottom, top + height);\n }\n }\n\n return Object.values(BRACKET_SECTION_KEY).flatMap((key) => {\n const box = found.get(key);\n\n if (!box) return [];\n\n const width = box.right - box.left;\n const top = config.tops?.[key] ?? box.top;\n\n return [\n {\n key,\n name: BRACKET_SECTION_DEFAULT_NAMES[key],\n rounds: Array.from(box.rounds),\n dimensions: { top, left: box.left, width, height: box.bottom - top },\n titleDimensions: {\n top: top - (config.titleGap ?? 0) - config.titleHeight,\n left: box.left,\n width,\n height: config.titleHeight,\n },\n },\n ];\n });\n};\n","import { COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketMasterColumnSection,\n BracketSubColumnSpan,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport {\n calculateColumnSplitFactor,\n calculateLowerRoundIndex,\n calculateUpperLowerRatio,\n calculateUpperRoundIndex,\n} from './double-elimination-utils';\nimport {\n createBracketContinueMasterColumn,\n createBracketGapMasterColumn,\n createRoundBracketSubColumnRelativeToFirstRound,\n getBracketContinueMatches,\n} from './prebuild';\nimport { BRACKET_FINAL_ALIGNMENT, ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { buildSingleEliminationGrid } from './single-elimination';\nimport { createBracketGridSections, doubleEliminationRoundSection } from './sections';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\nconst sectionTitleSpace = (options: { sectionTitleHeight?: number; sectionTitleGap?: number }) =>\n options.sectionTitleHeight ? options.sectionTitleHeight + (options.sectionTitleGap ?? 0) : 0;\n\nconst hasBothSides = <TRoundData, TMatchData>(bracketData: Bracket<TRoundData, TMatchData>) =>\n !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.first() &&\n !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.first();\n\nconst createOneSidedGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const titleSpace = sectionTitleSpace(options);\n const grid = buildSingleEliminationGrid(bracketData, options, components, titleSpace);\n\n return {\n ...grid,\n sections: createBracketGridSections({\n columns: grid.columns,\n sectionOf: doubleEliminationRoundSection,\n titleHeight: options.sectionTitleHeight ?? 0,\n titleGap: options.sectionTitleGap,\n tops: { upper: titleSpace, lower: titleSpace, finals: titleSpace },\n }),\n };\n};\n\nexport const createDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n if (!hasBothSides(bracketData)) return createOneSidedGrid(bracketData, options, components);\n\n const grid = buildDoubleEliminationGrid(bracketData, options, components, new Map());\n\n if (options.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER) return grid;\n\n return {\n ...buildDoubleEliminationGrid(bracketData, options, components, centeredFinalOffsets(bracketData, grid, options)),\n finalAlignment: BRACKET_FINAL_ALIGNMENT.CENTER,\n };\n};\n\nconst matchBlock = <TRoundData, TMatchData>(\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n round: BracketRound<TRoundData, TMatchData> | null | undefined,\n) => {\n if (!round) return null;\n\n let top = Infinity;\n let bottom = -Infinity;\n\n for (const match of round.matches.values()) {\n const element = grid.matchElementMap.get(match.id);\n\n if (!element) continue;\n\n top = Math.min(top, element.dimensions.top);\n bottom = Math.max(bottom, element.dimensions.top + element.dimensions.height);\n }\n\n return top <= bottom ? { top, bottom, center: (top + bottom) / 2 } : null;\n};\n\nconst centeredFinalOffsets = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n grid: ComputedBracketGrid<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n // eslint-disable-next-line max-params -- (data, measured grid, options)\n) => {\n const offsets = new Map<string, number>();\n const upperFinal = matchBlock(\n grid,\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.last(),\n );\n const lowerFinal = matchBlock(\n grid,\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.last(),\n );\n\n if (!upperFinal || !lowerFinal) return offsets;\n\n const target = (upperFinal.center + lowerFinal.center) / 2;\n const thirdPlace = matchBlock(grid, bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first());\n const finalRounds = [\n ...(bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.FINAL)?.values() ?? []),\n ...(bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.values() ?? []),\n ];\n\n for (const round of finalRounds) {\n const final = matchBlock(grid, round);\n\n if (!final) continue;\n\n const offset = Math.max(0, target - final.center);\n const room = thirdPlace ? Math.max(0, thirdPlace.top - options.rowGap - final.bottom) : Infinity;\n\n offsets.set(round.id, Math.min(offset, room));\n }\n\n return offsets;\n};\n\nconst buildDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n finalOffsets: ReadonlyMap<string, number>,\n // eslint-disable-next-line max-params -- grid builder signature plus the measured final offsets\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: resolvedOptions.columnWidth });\n const titleSpace = sectionTitleSpace(options);\n\n const presentUpperBracketRounds = Array.from(\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.values() ?? [],\n );\n const lowerBracketRounds = Array.from(\n bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.values() ?? [],\n );\n\n // A complete winner bracket has (lowerRounds / 2) + 1 rounds. If fewer are present, the winner\n // bracket starts later than round 1 - e.g. a small double elimination where lower-round 1 is\n // seeded directly from a group phase and has no winner round feeding it. Pad the front of the\n // winner rounds with nulls so the column mapping keeps treating the winner bracket as complete:\n // the missing early rounds become empty slots above the lower rounds they never fed, and every\n // present winner round lines up above its real drop-in lower round.\n const fullUpperRoundCount = Math.floor(lowerBracketRounds.length / 2) + 1;\n const frontMissingUpperRounds = Math.max(0, fullUpperRoundCount - presentUpperBracketRounds.length);\n const upperBracketRounds: (BracketRound<TRoundData, TMatchData> | null)[] = [\n ...Array.from({ length: frontMissingUpperRounds }, () => null),\n ...presentUpperBracketRounds,\n ];\n\n const remainingRounds = Array.from(bracketData.rounds.values()).filter(\n (r) =>\n r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET &&\n r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET &&\n r.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,\n );\n\n const thirdPlaceRound = bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first() ?? null;\n const hasReverseFinal = !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.first();\n\n const firstUpperRound = presentUpperBracketRounds[0];\n const firstLowerRound = lowerBracketRounds[0];\n\n if (!firstUpperRound || !firstLowerRound) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.ROUND_RELATION_INVALID,\n 'No upper or lower rounds found in bracket data',\n );\n }\n\n const upperToLowerRatio = calculateUpperLowerRatio(upperBracketRounds.length, lowerBracketRounds.length);\n const columnSplitFactor = calculateColumnSplitFactor(upperToLowerRatio);\n\n /**\n * The winner-bracket half of one column, or the space it would have taken. A front-truncated winner\n * bracket has leading slots with no round in them; reserving their height keeps the lower rounds below\n * aligned with the winner rounds that do exist.\n */\n const createUpperBracketSubColumn = (config: {\n round: BracketRound<TRoundData, TMatchData> | null;\n span: BracketSubColumnSpan;\n }) => {\n if (config.round) {\n return createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstUpperRound,\n round: config.round,\n options: resolvedOptions,\n hasReverseFinal,\n span: config.span,\n components,\n });\n }\n\n const emptyUpperHeight =\n (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0) +\n firstUpperRound.matchCount * options.matchHeight +\n Math.max(0, firstUpperRound.matchCount - 1) * options.rowGap;\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({ span: config.span });\n const element = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: emptyUpperHeight,\n partHeights: [emptyUpperHeight],\n });\n\n pushElement(element);\n\n return subColumn;\n };\n\n /** The breathing room between the winner and loser halves of a column. */\n const createUpperLowerGapSubColumn = () => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n const element = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap + titleSpace,\n partHeights: [options.rowRoundGap + titleSpace],\n });\n\n pushElement(element);\n\n return subColumn;\n };\n\n /** The band above the upper bracket and the finals that holds their section titles. */\n const pushSectionTitleBand = (pushSection: (section: BracketMasterColumnSection<TRoundData, TMatchData>) => void) => {\n if (!titleSpace) return;\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: titleSpace,\n partHeights: [titleSpace],\n }),\n );\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n };\n\n let lastRoundLastSubColumnUpperIndex = -1;\n let lastRoundLastSubColumnLowerIndex = -1;\n\n for (const [lowerRoundIndex, lowerRound] of lowerBracketRounds.entries()) {\n const isLastLowerRound = lowerRoundIndex === lowerBracketRounds.length - 1;\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } =\n createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n for (let currentColumnSplitFactor = 1; currentColumnSplitFactor <= columnSplitFactor; currentColumnSplitFactor++) {\n const subColumnIndex = lowerRoundIndex * columnSplitFactor + (currentColumnSplitFactor - 1);\n\n const currentUpperRoundIndex = calculateUpperRoundIndex(subColumnIndex, upperToLowerRatio, columnSplitFactor);\n const currentLowerRoundIndex = lowerRoundIndex;\n\n const isFirstSubColumnInMasterColumn = currentColumnSplitFactor === 1;\n const isLastSubColumnInMasterColumn = currentColumnSplitFactor === columnSplitFactor;\n\n const previousSubColumnIndex = subColumnIndex - 1;\n const nextSubColumnIndex = subColumnIndex + 1;\n\n const previousUpperRoundIndex =\n previousSubColumnIndex >= 0\n ? calculateUpperRoundIndex(previousSubColumnIndex, upperToLowerRatio, columnSplitFactor)\n : -1;\n const nextUpperRoundIndex = calculateUpperRoundIndex(nextSubColumnIndex, upperToLowerRatio, columnSplitFactor);\n\n const previousLowerRoundIndex =\n previousSubColumnIndex >= 0 ? calculateLowerRoundIndex(previousSubColumnIndex, columnSplitFactor) : -1;\n const nextLowerRoundIndex = calculateLowerRoundIndex(nextSubColumnIndex, columnSplitFactor);\n\n if (currentUpperRoundIndex < 0 || currentUpperRoundIndex >= upperBracketRounds.length) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.GRID_INVALID,\n 'Upper round not found for subColumnIndex: ' + subColumnIndex,\n );\n }\n\n // May be null for a leading winner slot that does not exist (front-truncated winner bracket).\n const upperRound = upperBracketRounds[currentUpperRoundIndex];\n\n const isUpperSpanStart = isFirstSubColumnInMasterColumn\n ? lowerRoundIndex === 0 || lastRoundLastSubColumnUpperIndex !== currentUpperRoundIndex\n : previousUpperRoundIndex !== currentUpperRoundIndex;\n\n const isUpperSpanEnd = isLastSubColumnInMasterColumn\n ? isLastLowerRound ||\n calculateUpperRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, upperToLowerRatio, columnSplitFactor) !==\n currentUpperRoundIndex\n : nextUpperRoundIndex !== currentUpperRoundIndex;\n\n const isLowerSpanStart = isFirstSubColumnInMasterColumn\n ? lowerRoundIndex === 0 || lastRoundLastSubColumnLowerIndex !== currentLowerRoundIndex\n : previousLowerRoundIndex !== currentLowerRoundIndex;\n\n const isLowerSpanEnd = isLastSubColumnInMasterColumn\n ? isLastLowerRound ||\n calculateLowerRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, columnSplitFactor) !==\n currentLowerRoundIndex\n : nextLowerRoundIndex !== currentLowerRoundIndex;\n\n const upperSpan = { isStart: isUpperSpanStart, isEnd: isUpperSpanEnd };\n\n pushUpperSubColumn(createUpperBracketSubColumn({ round: upperRound ?? null, span: upperSpan }));\n pushUpperLowerSubColumn(createUpperLowerGapSubColumn());\n\n const lowerSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstLowerRound,\n round: lowerRound,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: isLowerSpanStart,\n isEnd: isLowerSpanEnd,\n },\n components,\n });\n\n pushLowerSubColumn(lowerSubColumn);\n\n if (isLastSubColumnInMasterColumn) {\n lastRoundLastSubColumnUpperIndex = currentUpperRoundIndex;\n lastRoundLastSubColumnLowerIndex = currentLowerRoundIndex;\n }\n }\n\n pushSectionTitleBand(pushSection);\n pushSection(upperSection, upperLowerGapSection, lowerSection);\n\n grid.pushMasterColumn(masterColumn);\n\n // Always separate consecutive lower rounds with a gap column. The trailing gap after the\n // last lower round is only needed to connect to the finals section (remainingRounds); in a\n // truncated bracket without a final we must still gap the intermediate rounds, otherwise the\n // rounds sit flush against each other and their connector lines collapse to zero width.\n if (!isLastLowerRound || remainingRounds.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n for (const [roundIndex, round] of remainingRounds.entries()) {\n const isLastRound = roundIndex === remainingRounds.length - 1;\n const isFirstRound = roundIndex === 0;\n\n const isAnyFinal = hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: isAnyFinal ? options.finalColumnWidth : options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const finalOffset = finalOffsets.get(round.id) ?? 0;\n\n const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } =\n createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n padding: finalOffset ? { top: -finalOffset, bottom: 0, left: 0, right: 0 } : undefined,\n });\n\n const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection<\n TRoundData,\n TMatchData\n >({\n type: 'round',\n });\n\n const upperSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstUpperRound,\n round,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: true,\n isEnd: true,\n },\n components,\n topPadding: finalOffset,\n });\n\n pushUpperSubColumn(upperSubColumn);\n\n const upperLowerGapSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const upperLowerGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap + titleSpace,\n partHeights: [options.rowRoundGap + titleSpace],\n });\n\n upperLowerGapSubColumn.pushElement(upperLowerGapElement);\n\n pushUpperLowerSubColumn(upperLowerGapSubColumn.subColumn);\n\n if (thirdPlaceRound) {\n const lowerSubColumn = createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: firstLowerRound,\n round: thirdPlaceRound,\n options: resolvedOptions,\n hasReverseFinal,\n span: {\n isStart: isFirstRound,\n isEnd: isLastRound,\n },\n components,\n });\n\n pushLowerSubColumn(lowerSubColumn);\n } else {\n const lowerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const firstMasterRound = grid.grid.masterColumns[0];\n\n if (!firstMasterRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No first master round found in grid');\n\n const lastMasterColumnSection = firstMasterRound.sections[firstMasterRound.sections.length - 1];\n\n if (!lastMasterColumnSection)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No last master column section found in grid');\n\n const firstSubColumn = lastMasterColumnSection.subColumns[0];\n\n if (!firstSubColumn)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, 'No first sub column found in grid');\n\n for (const element of firstSubColumn.elements) {\n const el = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: element.dimensions.height,\n partHeights: element.parts.map((p) => p.dimensions.height),\n });\n\n lowerSubColumn.pushElement(el);\n }\n\n pushLowerSubColumn(lowerSubColumn.subColumn);\n }\n\n pushSectionTitleBand(pushSection);\n pushSection(upperSection, upperLowerGapSection, lowerSection);\n\n grid.pushMasterColumn(masterColumn);\n\n if (!isLastRound) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n if (options.continueElement && components.continue) {\n const continueMatches = getBracketContinueMatches(bracketData);\n\n if (continueMatches.length) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n\n grid.pushMasterColumn(\n createBracketContinueMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnWidth: options.continueElement.columnWidth,\n elementHeight: options.continueElement.elementHeight,\n headerOffset:\n titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),\n component: components.continue,\n matches: continueMatches,\n }),\n );\n }\n }\n\n grid.setupElementSpans();\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n const [upperRows, lowerRows] =\n grid.grid.masterColumns[0]?.sections.filter((section) => section.type === 'round') ?? [];\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n sections: createBracketGridSections({\n columns: finalizedGrid.columns,\n sectionOf: doubleEliminationRoundSection,\n titleHeight: options.sectionTitleHeight ?? 0,\n titleGap: options.sectionTitleGap,\n tops: {\n upper: upperRows?.dimensions.top,\n lower: lowerRows?.dimensions.top,\n finals: upperRows?.dimensions.top,\n },\n }),\n };\n};\n","import {\n BRACKET_ROUND_MIRROR_TYPE,\n BracketRoundType,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n} from '../../core';\nimport { Bracket, BracketRound } from '../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport { createBracketGapMasterColumn, createRoundBracketSubColumnRelativeToFirstRound } from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { resolveBracketGridRowSpan } from './row-span';\nimport { createSingleEliminationGrid } from './single-elimination';\n\nconst CENTRE_CHAIN_ORDER: Partial<Record<string, number>> = {\n final: 1,\n 'reverse-final': 2,\n 'third-place': 3,\n};\n\ntype StackedBlock<TRoundData, TMatchData> = {\n firstRound: BracketRound<TRoundData, TMatchData>;\n /** Outermost first. */\n left: BracketRound<TRoundData, TMatchData>[];\n /** Innermost first. */\n right: BracketRound<TRoundData, TMatchData>[];\n /** Top to bottom from the round both halves converge on; empty when they never meet. */\n chain: BracketRound<TRoundData, TMatchData>[];\n options: CreateBracketGridConfig;\n body: number;\n columnContent: (round: BracketRound<TRoundData, TMatchData>) => number;\n spacerTop: number;\n spacerBottom: number;\n};\n\ntype StackedBlockConfig<TRoundData, TMatchData> = {\n rounds: BracketRound<TRoundData, TMatchData>[];\n options: CreateBracketGridConfig;\n hasReverseFinal: boolean;\n};\n\nconst isFinalMatchRound = <TRoundData, TMatchData>(\n round: BracketRound<TRoundData, TMatchData>,\n hasReverseFinal: boolean,\n) =>\n hasReverseFinal\n ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL\n : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\nconst chainRoundHeight = <TRoundData, TMatchData>(config: {\n round: BracketRound<TRoundData, TMatchData>;\n options: CreateBracketGridConfig;\n hasReverseFinal: boolean;\n}) => {\n const { round, options, hasReverseFinal } = config;\n const cardHeight = isFinalMatchRound(round, hasReverseFinal) ? options.finalMatchHeight : options.matchHeight;\n\n return round.matchCount * cardHeight + Math.max(0, round.matchCount - 1) * options.rowGap;\n};\n\nconst createStackedBlock = <TRoundData, TMatchData>(\n config: StackedBlockConfig<TRoundData, TMatchData>,\n): StackedBlock<TRoundData, TMatchData> | null => {\n const { rounds, hasReverseFinal } = config;\n const options = resolveBracketGridRowSpan({ rounds }, config.options);\n\n const halves = rounds.filter((round) => !!round.mirrorRoundType);\n const left = halves\n .filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT)\n .sort((a, b) => a.logicalIndex - b.logicalIndex);\n const right = halves\n .filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT)\n .sort((a, b) => b.logicalIndex - a.logicalIndex);\n\n const middles = rounds\n .filter((round) => !round.mirrorRoundType)\n .sort(\n (a, b) =>\n (CENTRE_CHAIN_ORDER[a.type] ?? 0) - (CENTRE_CHAIN_ORDER[b.type] ?? 0) || a.logicalIndex - b.logicalIndex,\n );\n\n // Where the two halves meet: one depth past the innermost round that had a second half to fold against.\n const foldDepth = left.length ? Math.max(...left.map((round) => round.logicalIndex)) + 1 : 0;\n\n // An odd early round could not halve, so it has no twin on the way back and keeps a slot of its own on\n // the way out rather than sitting in a middle it is far too wide for.\n const isEarly = (round: BracketRound<TRoundData, TMatchData>) =>\n !CENTRE_CHAIN_ORDER[round.type] && round.logicalIndex < foldDepth;\n\n const leftSlots = [...left, ...middles.filter(isEarly)].sort((a, b) => a.logicalIndex - b.logicalIndex);\n const chain = middles.filter((round) => !isEarly(round));\n\n const firstRound = leftSlots[0] ?? chain[0];\n\n if (!firstRound) return null;\n\n const rows = options.rowSpanMatchCount ?? firstRound.matchCount;\n const rowsHeight = (count: number) => count * options.matchHeight + Math.max(0, count - 1) * options.rowGap;\n const content = rowsHeight(rows);\n const columnContent = (round: BracketRound<TRoundData, TMatchData>) => rowsHeight(Math.max(rows, round.matchCount));\n\n let chainHeight = 0;\n\n for (const [index, round] of chain.entries()) {\n chainHeight += (index ? options.rowRoundGap : 0) + chainRoundHeight({ round, options, hasReverseFinal });\n }\n const anchorHeight = chain[0] ? chainRoundHeight({ round: chain[0], options, hasReverseFinal }) : 0;\n\n // The round both halves converge on sits on the block's vertical centre, which is where the two halves'\n // own matches sit - so the connectors into it stay straight. A chain too long to hang under it from\n // there grows the block rather than sliding up: an anchor a few px off centre turns every one of those\n // connectors into a diagonal, in a drawing where nothing else is.\n const spacerTop = Math.max(0, (content - anchorHeight) / 2);\n const body = Math.max(spacerTop + chainHeight, ...[...leftSlots, ...right].map(columnContent));\n\n return {\n firstRound,\n left: leftSlots,\n right,\n chain,\n options,\n body,\n columnContent,\n spacerTop,\n spacerBottom: Math.max(0, body - spacerTop - chainHeight),\n };\n};\n\n/**\n * Draws a double elimination as two mirrored blocks, one above the other: the winners bracket folded\n * around its own centre, the losers bracket folded around its own, and nothing but a gap between them.\n * Each block's deciding rounds hang vertically below the round its two halves converge on.\n */\nexport const createStackedDoubleEliminationGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n\n const roundsOfType = (type: BracketRoundType) => Array.from(bracketData.roundsByType.get(type)?.values() ?? []);\n\n const hasReverseFinal = !!roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL).length;\n\n const winners = createStackedBlock({\n rounds: [\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET),\n ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.FINAL),\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL),\n ],\n options,\n hasReverseFinal,\n });\n\n const losers = createStackedBlock({\n rounds: [\n ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET),\n ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE),\n ],\n options,\n hasReverseFinal,\n });\n\n if (!winners || !losers) return createSingleEliminationGrid(bracketData, options, components);\n\n const blocks = [winners, losers];\n const headerBlock = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;\n const blockHeight = (block: StackedBlock<TRoundData, TMatchData>) => headerBlock + block.body;\n\n const centreIndex = Math.max(...blocks.map((block) => block.left.length));\n const columnCount = centreIndex + 1 + Math.max(...blocks.map((block) => block.right.length));\n\n const createPlaceholderSubColumn = (block: StackedBlock<TRoundData, TMatchData>) => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n const height = blockHeight(block);\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: height,\n partHeights: [height],\n }),\n );\n\n return subColumn;\n };\n\n const createChainSubColumn = (block: StackedBlock<TRoundData, TMatchData>) => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n const anchor = block.chain[0];\n\n if (!anchor) return createPlaceholderSubColumn(block);\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n // One header for the whole chain, naming the round its two halves converge on. The rounds below it\n // are a vertical run of single matches; a header between each would sit on the line joining them.\n if (options.roundHeaderHeight > 0) {\n elementsToCreate.push(\n {\n type: 'header',\n area: `h${anchor.shortId}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: components.roundHeader,\n round: anchor,\n roundSwissGroup: null,\n },\n {\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [options.roundHeaderGap],\n elementHeight: options.roundHeaderGap,\n },\n );\n }\n\n if (block.spacerTop > 0) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [block.spacerTop],\n elementHeight: block.spacerTop,\n });\n }\n\n for (const [roundIndex, round] of block.chain.entries()) {\n if (roundIndex) {\n elementsToCreate.push({\n type: 'roundGap',\n area: '.',\n partHeights: [options.rowRoundGap],\n elementHeight: options.rowRoundGap,\n });\n }\n\n const isFinalCard = isFinalMatchRound(round, hasReverseFinal);\n const cardHeight = isFinalCard ? options.finalMatchHeight : options.matchHeight;\n\n for (const [matchIndex, match] of Array.from(round.matches.values()).entries()) {\n if (matchIndex) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [options.rowGap],\n elementHeight: options.rowGap,\n });\n }\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: [cardHeight],\n elementHeight: cardHeight,\n component: isFinalCard ? components.finalMatch : components.match,\n match,\n round,\n roundSwissGroup: null,\n });\n }\n }\n\n if (block.spacerBottom > 0) {\n elementsToCreate.push({\n type: 'colGap',\n area: '.',\n partHeights: [block.spacerBottom],\n elementHeight: block.spacerBottom,\n });\n }\n\n for (const elementData of elementsToCreate) {\n pushElement(createBracketElement<TRoundData, TMatchData>(elementData));\n }\n\n return subColumn;\n };\n\n const createBlockSubColumn = (block: StackedBlock<TRoundData, TMatchData>, columnIndex: number) => {\n const slotIndex = columnIndex - (centreIndex - block.left.length);\n\n if (slotIndex === block.left.length) return createChainSubColumn(block);\n\n const round =\n slotIndex >= 0 && slotIndex < block.left.length\n ? block.left[slotIndex]\n : block.right[slotIndex - block.left.length - 1];\n\n if (!round) return createPlaceholderSubColumn(block);\n\n return createRoundBracketSubColumnRelativeToFirstRound({\n firstRound: block.firstRound,\n round,\n options: block.options,\n hasReverseFinal,\n bottomPadding: block.body - block.columnContent(round),\n span: { isStart: true, isEnd: true },\n components,\n });\n };\n\n const createBandSubColumn = () => {\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: { isStart: true, isEnd: true },\n });\n\n pushElement(\n createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: options.rowRoundGap,\n partHeights: [options.rowRoundGap],\n }),\n );\n\n return subColumn;\n };\n\n for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: columnIndex === centreIndex ? options.finalColumnWidth : options.columnWidth,\n padding: { bottom: 0, left: 0, right: 0, top: 0 },\n });\n\n const winnersSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'round' });\n const bandSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'gap' });\n const losersSection = createBracketMasterColumnSection<TRoundData, TMatchData>({ type: 'round' });\n\n winnersSection.pushSubColumn(createBlockSubColumn(winners, columnIndex));\n bandSection.pushSubColumn(createBandSubColumn());\n losersSection.pushSubColumn(createBlockSubColumn(losers, columnIndex));\n\n pushSection(winnersSection.masterColumnSection, bandSection.masterColumnSection, losersSection.masterColumnSection);\n\n grid.pushMasterColumn(masterColumn);\n\n if (columnIndex < columnCount - 1) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n","import {\n BracketMatchId,\n BracketMatchPosition,\n BracketRoundId,\n BracketWarning,\n COMMON_BRACKET_ROUND_TYPE,\n} from '../core';\nimport { BracketMatchOutcomeSlotSource, BracketMatchSource } from '../integrations';\nimport { Bracket, BracketMatch, BracketRound } from './bracket';\nimport { BracketRoundRelation } from './round-relations';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nconst FALLBACK_MATCH_RELATION_POSITION = -1 as BracketMatchPosition;\n\n// Will usually be 0.5, 1 or 2. In Swiss this value will be gibberish\nexport type BracketMatchFactor = number;\n\n// One match has one previous match and one next match (this would be the case, if a group tournament is being displayed via a bracket)\nexport type BracketMatchRelationOneToOne<TRoundData, TMatchData> = {\n type: 'one-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousMatch: BracketMatch<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has no previous match but a single next match (eg. the start of the bracket)\nexport type BracketMatchRelationNothingToOne<TRoundData, TMatchData> = {\n type: 'nothing-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has no next match but a single previous match (eg. reverse finals)\nexport type BracketMatchRelationOneToNothing<TRoundData, TMatchData> = {\n type: 'one-to-nothing';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousMatch: BracketMatch<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has two previous matches and one next match (eg. a normal match in the bracket that is neither the start nor the end)\nexport type BracketMatchRelationTwoToOne<TRoundData, TMatchData> = {\n type: 'two-to-one';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperMatch: BracketMatch<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerMatch: BracketMatch<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextMatch: BracketMatch<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n};\n\n// The match has two previous matches and no next match (eg. the finals in a single elimination bracket)\nexport type BracketMatchRelationTwoToNothing<TRoundData, TMatchData> = {\n type: 'two-to-nothing';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperMatch: BracketMatch<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerMatch: BracketMatch<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketMatchRelationNone<TRoundData, TMatchData> = {\n type: 'none';\n currentMatch: BracketMatch<TRoundData, TMatchData>;\n currentRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketMatchRelation<TRoundData, TMatchData> =\n | BracketMatchRelationNone<TRoundData, TMatchData>\n | BracketMatchRelationOneToOne<TRoundData, TMatchData>\n | BracketMatchRelationTwoToOne<TRoundData, TMatchData>\n | BracketMatchRelationNothingToOne<TRoundData, TMatchData>\n | BracketMatchRelationOneToNothing<TRoundData, TMatchData>\n | BracketMatchRelationTwoToNothing<TRoundData, TMatchData>;\n\nexport type MatchPositionMaps<TRoundData, TMatchData> = Map<\n BracketRoundId,\n Map<BracketMatchPosition, BracketMatch<TRoundData, TMatchData>>\n>;\n\nexport const generateMatchPosition = (\n match: BracketMatch<unknown, unknown>,\n factor: BracketMatchFactor,\n): BracketMatchPosition => Math.ceil(match.position * factor) as BracketMatchPosition;\n\nconst generatePreviousRoundMatchPositions = <TRoundData, TMatchData>(\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-one' | 'one-to-nothing' }>,\n match: BracketMatch<TRoundData, TMatchData>,\n) => {\n const feederFactor = relation.currentRound.matchCount / relation.previousRound.matchCount;\n const feederPositions: BracketMatchPosition[] = [];\n\n for (const feeder of relation.previousRound.matches.values()) {\n if (generateMatchPosition(feeder, feederFactor) === match.position) feederPositions.push(feeder.position);\n }\n\n const first = feederPositions[0];\n const last = feederPositions[feederPositions.length - 1];\n\n if (first !== undefined && last !== undefined) {\n return { previousUpperRoundMatchPosition: first, previousLowerRoundMatchPosition: last };\n }\n\n const double = relation.previousRoundMatchFactor === 2 ? 1 : 0;\n\n return {\n previousUpperRoundMatchPosition: (generateMatchPosition(match, relation.previousRoundMatchFactor) -\n double) as BracketMatchPosition,\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousRoundMatchFactor),\n };\n};\n\nexport const generateMatchRelationPositions = <TRoundData, TMatchData>(\n relation: BracketRoundRelation<TRoundData, TMatchData>,\n match: BracketMatch<TRoundData, TMatchData>,\n) => {\n switch (relation.type) {\n case 'none':\n return null;\n\n case 'nothing-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n previousUpperRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n previousLowerRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n };\n\n case 'one-to-nothing':\n return {\n nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n ...generatePreviousRoundMatchPositions(relation, match),\n };\n\n case 'one-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n ...generatePreviousRoundMatchPositions(relation, match),\n };\n\n case 'two-to-one':\n return {\n nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),\n previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor),\n };\n\n case 'two-to-nothing':\n return {\n nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,\n previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),\n previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor),\n };\n }\n};\n\nconst relationMatchNotFound = (options: {\n match: { id: string; round: { id: string } };\n feeder: string;\n round: { id: string };\n position: BracketMatchPosition;\n}) =>\n new BracketRuntimeError(\n BRACKET_ERROR_CODES.MATCH_RELATION_INVALID,\n `Match \"${options.match.id}\" in round \"${options.match.round.id}\" has no ${options.feeder} match at position ${options.position} of round \"${options.round.id}\". Check the match counts of both rounds, or declare homeSource/awaySource.`,\n );\n\nconst createNothingToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'nothing-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationNothingToOne<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, nextRoundMatchPosition } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n\n return {\n type: 'nothing-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n};\n\nconst createOneToNothingOrTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-nothing' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}):\n | BracketMatchRelationOneToNothing<TRoundData, TMatchData>\n | BracketMatchRelationTwoToNothing<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } =\n params;\n\n const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);\n\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous',\n round: relation.previousRound,\n position: previousUpperRoundMatchPosition,\n });\n\n if (previousUpperRoundMatchPosition !== previousLowerRoundMatchPosition) {\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousRound,\n previousLowerMatch,\n previousLowerRound: relation.previousRound,\n };\n } else {\n return {\n type: 'one-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousMatch: previousUpperMatch,\n previousRound: relation.previousRound,\n };\n }\n};\n\nconst createOneToOneOrTwoToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'one-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationOneToOne<TRoundData, TMatchData> | BracketMatchRelationTwoToOne<TRoundData, TMatchData> => {\n const {\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousRound,\n position: previousLowerRoundMatchPosition,\n });\n\n if (previousUpperRoundMatchPosition === previousLowerRoundMatchPosition) {\n return {\n type: 'one-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousMatch: previousUpperMatch,\n previousRound: relation.previousRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n } else {\n return {\n type: 'two-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousRound,\n previousLowerMatch,\n previousLowerRound: relation.previousRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n }\n};\n\nconst createTwoToOneRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'two-to-one' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n nextRoundMatchPosition: BracketMatchPosition;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationTwoToOne<TRoundData, TMatchData> => {\n const {\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n } = params;\n\n const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);\n const previousUpperMatch = matchPositionMaps\n .get(relation.previousUpperRound.id)\n ?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps\n .get(relation.previousLowerRound.id)\n ?.get(previousLowerRoundMatchPosition);\n\n if (!nextMatch)\n throw relationMatchNotFound({ match, feeder: 'next', round: relation.nextRound, position: nextRoundMatchPosition });\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousUpperRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousLowerRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-one',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousUpperRound,\n previousLowerMatch,\n previousLowerRound: relation.previousLowerRound,\n nextMatch,\n nextRound: relation.nextRound,\n };\n};\n\nconst createTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n match: BracketMatch<TRoundData, TMatchData>;\n relation: Extract<BracketRoundRelation<TRoundData, TMatchData>, { type: 'two-to-nothing' }>;\n matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData>;\n previousUpperRoundMatchPosition: BracketMatchPosition;\n previousLowerRoundMatchPosition: BracketMatchPosition;\n}): BracketMatchRelationTwoToNothing<TRoundData, TMatchData> => {\n const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } =\n params;\n\n const previousUpperMatch = matchPositionMaps\n .get(relation.previousUpperRound.id)\n ?.get(previousUpperRoundMatchPosition);\n const previousLowerMatch = matchPositionMaps\n .get(relation.previousLowerRound.id)\n ?.get(previousLowerRoundMatchPosition);\n\n if (!previousUpperMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous upper',\n round: relation.previousUpperRound,\n position: previousUpperRoundMatchPosition,\n });\n if (!previousLowerMatch)\n throw relationMatchNotFound({\n match,\n feeder: 'previous lower',\n round: relation.previousLowerRound,\n position: previousLowerRoundMatchPosition,\n });\n\n return {\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: relation.currentRound,\n previousUpperMatch,\n previousUpperRound: relation.previousUpperRound,\n previousLowerMatch,\n previousLowerRound: relation.previousLowerRound,\n };\n};\n\nexport const generateMatchRelationsNew = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: {\n source?: { matches: BracketMatchSource<TMatchData>[] };\n previousMatchIds?: (match: BracketMatchSource<TMatchData>) => string[];\n onWarning?: (warning: BracketWarning) => void;\n } = {},\n): BracketMatchRelation<TRoundData, TMatchData>[] => {\n const sourceMatches = options.source?.matches ?? [];\n const hasDeclaredGraph =\n options.previousMatchIds !== undefined || sourceMatches.some((match) => matchOutcomeSlots(match).length > 0);\n\n if (hasDeclaredGraph) {\n return generateDeclaredMatchRelations({\n bracket: bracketData,\n sourceMatches,\n previousMatchIds: options.previousMatchIds ?? defaultPreviousMatchIds,\n onWarning: options.onWarning,\n });\n }\n\n const matchRelations: BracketMatchRelation<TRoundData, TMatchData>[] = [];\n const matchPositionMaps: MatchPositionMaps<TRoundData, TMatchData> = new Map();\n\n for (const round of bracketData.rounds.values()) {\n const matchMap = new Map([...round.matches.values()].map((m) => [m.position, m]));\n matchPositionMaps.set(round.id, matchMap);\n }\n\n for (const match of bracketData.matches.values()) {\n const relation = match.round.relation;\n\n const positions = generateMatchRelationPositions(relation, match);\n\n if (!positions) continue;\n\n const { nextRoundMatchPosition, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = positions;\n\n switch (relation.type) {\n case 'nothing-to-one':\n matchRelations.push(\n createNothingToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n }),\n );\n break;\n\n case 'one-to-nothing':\n matchRelations.push(\n createOneToNothingOrTwoToNothingRelation({\n match,\n relation,\n matchPositionMaps,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'one-to-one':\n matchRelations.push(\n createOneToOneOrTwoToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'two-to-one':\n matchRelations.push(\n createTwoToOneRelation({\n match,\n relation,\n matchPositionMaps,\n nextRoundMatchPosition,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n\n case 'two-to-nothing':\n matchRelations.push(\n createTwoToNothingRelation({\n match,\n relation,\n matchPositionMaps,\n previousUpperRoundMatchPosition,\n previousLowerRoundMatchPosition,\n }),\n );\n break;\n }\n }\n\n return matchRelations;\n};\n\nconst matchOutcomeSlots = <TMatchData>(match: BracketMatchSource<TMatchData>) =>\n [match.homeSource, match.awaySource].filter(\n (slot): slot is BracketMatchOutcomeSlotSource => slot?.kind === 'match-outcome' && !!slot.matchId,\n );\n\nconst defaultPreviousMatchIds = <TMatchData>(match: BracketMatchSource<TMatchData>): string[] =>\n matchOutcomeSlots(match)\n .filter((slot) => slot.role !== 'loser')\n .map((slot) => slot.matchId);\n\nconst reportDeclaredGraphWarnings = <TRoundData, TMatchData>(options: {\n bracket: Bracket<TRoundData, TMatchData>;\n sourceMatches: BracketMatchSource<TMatchData>[];\n previousByMatchId: Map<string, string[]>;\n onWarning: (warning: BracketWarning) => void;\n}) => {\n const { bracket, sourceMatches, previousByMatchId, onWarning } = options;\n const feederIds = new Set<string>();\n\n for (const match of sourceMatches) {\n const referenced = new Set([\n ...(previousByMatchId.get(match.id) ?? []),\n ...matchOutcomeSlots(match).map((slot) => slot.matchId),\n ]);\n\n for (const feederId of referenced) {\n feederIds.add(feederId);\n\n if (bracket.matches.has(feederId as BracketMatchId)) continue;\n\n onWarning({\n type: 'unknown-feeder',\n matchId: match.id,\n feederId,\n message: `Match \"${match.id}\" is fed by \"${feederId}\", which is not in source.matches. The connector is not drawn.`,\n });\n }\n }\n\n if (sourceMatches.length < 2) return;\n\n for (const match of sourceMatches) {\n const declaresFeeders =\n (previousByMatchId.get(match.id)?.length ?? 0) > 0 ||\n matchOutcomeSlots(match).length > 0 ||\n [match.homeSource, match.awaySource].some((slot) => slot?.kind === 'unknown');\n\n if (declaresFeeders || feederIds.has(match.id)) continue;\n if (bracket.matches.get(match.id as BracketMatchId)?.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;\n\n onWarning({\n type: 'unlinked-match',\n matchId: match.id,\n message: `Match \"${match.id}\" declares no feeders and feeds no match. A source with any match-outcome slot (or a previousMatchIds option) is linked only from what it declares, so give every match its homeSource/awaySource.`,\n });\n }\n};\n\nconst generateDeclaredMatchRelations = <TRoundData, TMatchData>(options: {\n bracket: Bracket<TRoundData, TMatchData>;\n sourceMatches: BracketMatchSource<TMatchData>[];\n previousMatchIds: (match: BracketMatchSource<TMatchData>) => string[];\n onWarning?: (warning: BracketWarning) => void;\n}): BracketMatchRelation<TRoundData, TMatchData>[] => {\n const { bracket, sourceMatches, previousMatchIds, onWarning } = options;\n const previousByMatchId = new Map(sourceMatches.map((match) => [match.id, previousMatchIds(match)]));\n\n if (onWarning) reportDeclaredGraphWarnings({ bracket, sourceMatches, previousByMatchId, onWarning });\n const nextByMatchId = new Map<string, string>();\n\n // A match can feed two: a semi final feeds the final with its winner and the third place match with\n // its loser. The winner is where the match leads, so it wins over whatever the source happens to list\n // first - without this, `nextMatch` answers \"where does this winner go\" from array order.\n const winnerConsumerByFeederId = new Map<string, string>();\n\n for (const match of sourceMatches) {\n for (const slot of [match.homeSource, match.awaySource]) {\n if (slot?.kind !== 'match-outcome' || slot.role === 'loser' || !slot.matchId) continue;\n if (!winnerConsumerByFeederId.has(slot.matchId)) winnerConsumerByFeederId.set(slot.matchId, match.id);\n }\n }\n\n for (const [matchId, feederIds] of previousByMatchId) {\n for (const feederId of feederIds) {\n if (winnerConsumerByFeederId.get(feederId) === matchId) nextByMatchId.set(feederId, matchId);\n else if (!nextByMatchId.has(feederId)) nextByMatchId.set(feederId, matchId);\n }\n }\n\n const relations: BracketMatchRelation<TRoundData, TMatchData>[] = [];\n\n for (const match of bracket.matches.values()) {\n const previousMatches = (previousByMatchId.get(match.id) ?? [])\n .map((id) => bracket.matches.get(id as BracketMatchId))\n .filter((candidate): candidate is BracketMatch<TRoundData, TMatchData> => candidate !== undefined);\n const nextMatchId = nextByMatchId.get(match.id);\n const nextMatch = nextMatchId ? bracket.matches.get(nextMatchId as BracketMatchId) : undefined;\n\n if (previousMatches.length === 0 && nextMatch) {\n relations.push({\n type: 'nothing-to-one',\n currentMatch: match,\n currentRound: match.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length === 1 && nextMatch) {\n const previousMatch = previousMatches[0];\n\n if (!previousMatch) continue;\n\n relations.push({\n type: 'one-to-one',\n currentMatch: match,\n currentRound: match.round,\n previousMatch,\n previousRound: previousMatch.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length >= 2 && nextMatch) {\n const previousUpperMatch = previousMatches[0];\n const previousLowerMatch = previousMatches[1];\n\n if (!previousUpperMatch || !previousLowerMatch) continue;\n\n relations.push({\n type: 'two-to-one',\n currentMatch: match,\n currentRound: match.round,\n previousUpperMatch,\n previousUpperRound: previousUpperMatch.round,\n previousLowerMatch,\n previousLowerRound: previousLowerMatch.round,\n nextMatch,\n nextRound: nextMatch.round,\n });\n } else if (previousMatches.length === 1) {\n const previousMatch = previousMatches[0];\n\n if (!previousMatch) continue;\n\n relations.push({\n type: 'one-to-nothing',\n currentMatch: match,\n currentRound: match.round,\n previousMatch,\n previousRound: previousMatch.round,\n });\n } else if (previousMatches.length >= 2) {\n const previousUpperMatch = previousMatches[0];\n const previousLowerMatch = previousMatches[1];\n\n if (!previousUpperMatch || !previousLowerMatch) continue;\n\n relations.push({\n type: 'two-to-nothing',\n currentMatch: match,\n currentRound: match.round,\n previousUpperMatch,\n previousUpperRound: previousUpperMatch.round,\n previousLowerMatch,\n previousLowerRound: previousLowerMatch.round,\n });\n }\n }\n\n return relations;\n};\n","import { BRACKET_ROUND_MIRROR_TYPE, COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE } from '../core';\nimport { Bracket, BracketRound } from './bracket';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\n// One round has one next round (the first round of the bracket)\nexport type BracketRoundRelationNothingToOne<TRoundData, TMatchData> = {\n type: 'nothing-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n};\n\n// One round has one previous round (eg. the finals round of the bracket in case of a single elimination bracket)\nexport type BracketRoundRelationOneToNothing<TRoundData, TMatchData> = {\n type: 'one-to-nothing';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n previousRoundMatchFactor: number;\n rootRoundMatchFactor: number;\n};\n\n// One round has one previous round and one next round (eg. a normal round in the bracket that is neither the start nor the end)\nexport type BracketRoundRelationOneToOne<TRoundData, TMatchData> = {\n type: 'one-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n previousRoundMatchFactor: number;\n rootRoundMatchFactor: number;\n};\n\n// One round has two previous rounds and one next round (eg. the finals round in a double elimination bracket when the reverse finals is also being played)\nexport type BracketRoundRelationTwoToOne<TRoundData, TMatchData> = {\n type: 'two-to-one';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n nextRoundMatchFactor: number;\n previousUpperRoundMatchFactor: number;\n previousLowerRoundMatchFactor: number;\n upperRootRoundMatchFactor: number;\n lowerRootRoundMatchFactor: number;\n};\n\n// One round has two previous rounds and no next round (eg. the finals round in a double elimination bracket when the reverse finals is not being played)\nexport type BracketRoundRelationTwoToNothing<TRoundData, TMatchData> = {\n type: 'two-to-nothing';\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRoundMatchFactor: number;\n previousLowerRoundMatchFactor: number;\n upperRootRoundMatchFactor: number;\n lowerRootRoundMatchFactor: number;\n};\n\nexport type BracketRoundRelationNone<TRoundData, TMatchData> = {\n type: 'none';\n currentRound: BracketRound<TRoundData, TMatchData>;\n};\n\nexport type BracketRoundRelation<TRoundData, TMatchData> =\n | BracketRoundRelationNone<TRoundData, TMatchData>\n | BracketRoundRelationNothingToOne<TRoundData, TMatchData>\n | BracketRoundRelationOneToNothing<TRoundData, TMatchData>\n | BracketRoundRelationOneToOne<TRoundData, TMatchData>\n | BracketRoundRelationTwoToOne<TRoundData, TMatchData>\n | BracketRoundRelationTwoToNothing<TRoundData, TMatchData>;\n\nconst calculateMatchFactor = <TRoundData, TMatchData>(\n numeratorRound: BracketRound<TRoundData, TMatchData>,\n denominatorRound: BracketRound<TRoundData, TMatchData>,\n) => numeratorRound.matchCount / denominatorRound.matchCount;\n\nconst createNothingToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationNothingToOne<TRoundData, TMatchData> => ({\n type: 'nothing-to-one',\n currentRound: params.currentRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n});\n\nconst createOneToNothingRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n rootRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationOneToNothing<TRoundData, TMatchData> => ({\n type: 'one-to-nothing',\n currentRound: params.currentRound,\n previousRound: params.previousRound,\n previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),\n rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound),\n});\n\nconst createOneToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n rootRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationOneToOne<TRoundData, TMatchData> => ({\n type: 'one-to-one',\n currentRound: params.currentRound,\n previousRound: params.previousRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),\n rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound),\n});\n\nconst createTwoToOneRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n nextRound: BracketRound<TRoundData, TMatchData>;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationTwoToOne<TRoundData, TMatchData> => ({\n type: 'two-to-one',\n currentRound: params.currentRound,\n previousUpperRound: params.previousUpperRound,\n previousLowerRound: params.previousLowerRound,\n nextRound: params.nextRound,\n nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),\n previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),\n previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),\n upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),\n lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound),\n});\n\nconst createTwoToNothingRelation = <TRoundData, TMatchData>(params: {\n currentRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n previousLowerRound: BracketRound<TRoundData, TMatchData>;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n}): BracketRoundRelationTwoToNothing<TRoundData, TMatchData> => ({\n type: 'two-to-nothing',\n currentRound: params.currentRound,\n previousUpperRound: params.previousUpperRound,\n previousLowerRound: params.previousLowerRound,\n previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),\n previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),\n upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),\n lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound),\n});\n\n/** A round drawn on the way back from the middle of a mirrored bracket. */\nconst isFoldedBackRound = <TRoundData, TMatchData>(round: BracketRound<TRoundData, TMatchData>) =>\n round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;\n\n/** One bracket's rounds keyed by depth, with the two sides of a fold kept apart. */\ntype BracketRoundsByDepth<TRoundData, TMatchData> = Map<\n number,\n {\n left: BracketRound<TRoundData, TMatchData> | null;\n right: BracketRound<TRoundData, TMatchData> | null;\n /** The round at this depth that was never folded - the middle of a mirrored bracket. */\n single: BracketRound<TRoundData, TMatchData> | null;\n }\n>;\n\nconst buildRoundsByDepth = <TRoundData, TMatchData>(\n rounds: BracketRound<TRoundData, TMatchData>[],\n): BracketRoundsByDepth<TRoundData, TMatchData> => {\n const byDepth: BracketRoundsByDepth<TRoundData, TMatchData> = new Map();\n\n for (const round of rounds) {\n const slot = byDepth.get(round.logicalIndex) ?? { left: null, right: null, single: null };\n\n if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT) slot.left = round;\n else if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT) slot.right = round;\n else slot.single = round;\n\n byDepth.set(round.logicalIndex, slot);\n }\n\n return byDepth;\n};\n\n/**\n * The round one depth along on the same side of the fold - or, where the fold has closed because that\n * depth was too small to halve, the whole round sitting in the middle.\n */\nconst roundAtDepth = <TRoundData, TMatchData>(params: {\n byDepth: BracketRoundsByDepth<TRoundData, TMatchData>;\n depth: number;\n side: BracketRound<TRoundData, TMatchData>['mirrorRoundType'];\n}) => {\n const slot = params.byDepth.get(params.depth);\n\n if (!slot) return null;\n\n const sameSide = params.side === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? slot.right : slot.left;\n\n return sameSide ?? slot.single ?? null;\n};\n\nconst getNavigationContext = <TRoundData, TMatchData>(params: {\n upperRounds: BracketRound<TRoundData, TMatchData>[];\n upperRoundsByDepth: BracketRoundsByDepth<TRoundData, TMatchData>;\n currentUpperRoundIndex: number;\n}) => {\n const { upperRounds, upperRoundsByDepth, currentUpperRoundIndex } = params;\n const currentUpperRound = upperRounds[currentUpperRoundIndex];\n\n if (!currentUpperRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, 'currentUpperRound is null');\n\n const isLeftToRight =\n !currentUpperRound.mirrorRoundType || currentUpperRound.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT;\n\n // A folded half follows the fold, not the array. Its neighbours are the rounds one depth away on its\n // own side, because the array puts a right half next to whatever happened to be emitted beside it -\n // in a double elimination that is the grand final rather than the round it actually feeds.\n const isFolded = !!currentUpperRound.mirrorRoundType;\n const side = currentUpperRound.mirrorRoundType;\n const depth = currentUpperRound.logicalIndex;\n\n const relativePrevious = isFolded\n ? roundAtDepth({ byDepth: upperRoundsByDepth, depth: depth - 1, side })\n : upperRounds[currentUpperRoundIndex - 1] || null;\n const relativeNext = isFolded\n ? roundAtDepth({ byDepth: upperRoundsByDepth, depth: depth + 1, side })\n : upperRounds[currentUpperRoundIndex + 1] || null;\n\n // A folded half already resolved its own direction, so the swap that turns array order into flow\n // order for a right-hand round must not be applied twice.\n const previousUpperRound = isFolded || isLeftToRight ? relativePrevious : relativeNext;\n const flowNext = isFolded || isLeftToRight ? relativeNext : relativePrevious;\n\n // An unfolded round sits in the middle of the fold, so a right half beside it in the array feeds it\n // rather than following it.\n const nextUpperRound = !isFolded && flowNext?.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? null : flowNext;\n\n const isLastUpperRound = !nextUpperRound;\n\n const isFinal = currentUpperRound.type === COMMON_BRACKET_ROUND_TYPE.FINAL;\n\n return {\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n isLastUpperRound,\n isFinal,\n };\n};\n\nconst handleFinalRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData> | null;\n /** The lower bracket as it is played, one round per depth - see `lowerFlow`. */\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData>;\n lastLowerRound: BracketRound<TRoundData, TMatchData>;\n}) => {\n const {\n relations,\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n lowerRounds,\n firstUpperRound,\n firstLowerRound,\n lastLowerRound,\n } = params;\n\n const finalLowerRound = lastLowerRound;\n const isAsyncBracket = nextUpperRound?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL;\n\n if (nextUpperRound) {\n relations.push(\n createTwoToOneRelation({\n currentRound: currentUpperRound,\n previousUpperRound,\n previousLowerRound: finalLowerRound,\n nextRound: nextUpperRound,\n firstUpperRound,\n firstLowerRound,\n }),\n );\n } else {\n relations.push(\n createTwoToNothingRelation({\n currentRound: currentUpperRound,\n previousUpperRound,\n previousLowerRound: finalLowerRound,\n firstUpperRound,\n firstLowerRound,\n }),\n );\n }\n\n const preFinalLowerRound = lowerRounds[lowerRounds.length - 2] || null;\n\n if (!preFinalLowerRound) {\n relations.push(createNothingToOneRelation({ currentRound: finalLowerRound, nextRound: currentUpperRound }));\n\n return;\n }\n\n relations.push(\n createOneToOneRelation({\n currentRound: finalLowerRound,\n previousRound: preFinalLowerRound,\n nextRound: currentUpperRound,\n rootRound: firstLowerRound,\n }),\n );\n\n if (!isAsyncBracket) return;\n\n const prePreFinalLowerRound = lowerRounds[lowerRounds.length - 3] || null;\n\n relations.push(\n prePreFinalLowerRound\n ? createOneToOneRelation({\n currentRound: preFinalLowerRound,\n previousRound: prePreFinalLowerRound,\n nextRound: finalLowerRound,\n rootRound: firstLowerRound,\n })\n : createNothingToOneRelation({ currentRound: preFinalLowerRound, nextRound: finalLowerRound }),\n );\n};\n\nconst handleFirstRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData>;\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n}) => {\n const { relations, currentUpperRound, nextUpperRound, lowerRounds, currentUpperRoundIndex } = params;\n\n relations.push(\n createNothingToOneRelation({\n currentRound: currentUpperRound,\n nextRound: nextUpperRound,\n }),\n );\n\n const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;\n const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;\n\n // Pairing \"upper round at index i\" with \"lower round at index i\" only means something while the upper\n // array is the outbound flow. A round on the way back from a fold sits past the finals in that array,\n // so its index would claim a lower round in the middle of the bracket and wire it as an opening round -\n // the loop at the end of `generateRoundRelations` reaches it by depth instead.\n if (currentLowerRound && nextLowerRound && !isFoldedBackRound(currentUpperRound)) {\n relations.push(\n createNothingToOneRelation({\n currentRound: currentLowerRound,\n nextRound: nextLowerRound,\n }),\n );\n }\n};\n\nconst handleRegularRound = <TRoundData, TMatchData>(params: {\n relations: BracketRoundRelation<TRoundData, TMatchData>[];\n currentUpperRound: BracketRound<TRoundData, TMatchData>;\n previousUpperRound: BracketRound<TRoundData, TMatchData>;\n nextUpperRound: BracketRound<TRoundData, TMatchData>;\n lowerRounds: BracketRound<TRoundData, TMatchData>[];\n currentUpperRoundIndex: number;\n firstUpperRound: BracketRound<TRoundData, TMatchData>;\n firstLowerRound: BracketRound<TRoundData, TMatchData> | null;\n}) => {\n const {\n relations,\n currentUpperRound,\n previousUpperRound,\n nextUpperRound,\n lowerRounds,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n } = params;\n\n relations.push(\n createOneToOneRelation({\n currentRound: currentUpperRound,\n previousRound: previousUpperRound,\n nextRound: nextUpperRound,\n rootRound: firstUpperRound,\n }),\n );\n\n const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;\n const previousLowerRound = lowerRounds[currentUpperRoundIndex - 1] || null;\n const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;\n\n if (\n currentLowerRound &&\n currentUpperRound.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET &&\n previousLowerRound &&\n nextLowerRound &&\n firstLowerRound &&\n // See `handleFirstRound`: an index into the outbound flow says nothing about a folded-back round.\n !isFoldedBackRound(currentUpperRound)\n ) {\n relations.push(\n createOneToOneRelation({\n currentRound: currentLowerRound,\n previousRound: previousLowerRound,\n nextRound: nextLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n};\n\nexport const generateRoundRelationsNew = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n): BracketRoundRelation<TRoundData, TMatchData>[] => {\n const relations: BracketRoundRelation<TRoundData, TMatchData>[] = [];\n\n // A relation may never name a round with no matches: every position in it comes from a ratio of match\n // counts, so a zero puts each neighbour's match at a position nothing occupies. A round whose matches\n // are not drawn yet is treated as absent instead, and its neighbours wired to each other.\n // A third place match is fed by losers, so it is no step in the chain that ends in the final.\n const allRounds = [...bracketData.rounds.values()].filter(\n (round) => round.matchCount > 0 && round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,\n );\n const upperRounds = allRounds.filter((r) => r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);\n const lowerRounds = allRounds.filter((r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);\n\n const upperRoundsByDepth = buildRoundsByDepth(upperRounds);\n const lowerRoundsByDepth = buildRoundsByDepth(lowerRounds);\n\n // The lower bracket as it is *played*: one round per depth, taking the left half of a folded round.\n // A fold draws each early round twice, so the raw array holds two entries per depth and its last\n // element is a first-round half rather than the round that feeds the grand final. Unfolded, this is\n // the array itself.\n const lowerFlow = Array.from(lowerRoundsByDepth.keys())\n .sort((a, b) => a - b)\n .map((depth) => roundAtDepth({ byDepth: lowerRoundsByDepth, depth, side: null }))\n .filter((round) => !!round);\n\n const firstUpperRound = upperRounds[0];\n const firstLowerRound = lowerFlow[0] || null;\n const lastLowerRound = lowerFlow[lowerFlow.length - 1] || null;\n\n // Nothing is drawn yet, so there is nothing to relate - not a malformed structure.\n if (allRounds.length === 0) return relations;\n\n const hasLowerRounds = lowerRounds.length > 0;\n\n if (firstUpperRound) {\n for (const [currentUpperRoundIndex] of upperRounds.entries()) {\n const nav = getNavigationContext({\n upperRounds,\n upperRoundsByDepth,\n currentUpperRoundIndex,\n });\n\n if (nav.isFinal && hasLowerRounds && lastLowerRound && firstLowerRound && nav.previousUpperRound) {\n handleFinalRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n previousUpperRound: nav.previousUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n lastLowerRound,\n });\n } else if (nav.isLastUpperRound && nav.previousUpperRound) {\n relations.push(\n createOneToNothingRelation({\n currentRound: nav.currentUpperRound,\n previousRound: nav.previousUpperRound,\n rootRound: firstUpperRound,\n }),\n );\n } else if (nav.currentUpperRound.isFirstRound && nav.nextUpperRound) {\n handleFirstRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n });\n } else if (nav.nextUpperRound && !nav.previousUpperRound) {\n relations.push(\n createNothingToOneRelation({\n currentRound: nav.currentUpperRound,\n nextRound: nav.nextUpperRound,\n }),\n );\n } else if (nav.previousUpperRound && nav.nextUpperRound) {\n handleRegularRound({\n relations,\n currentUpperRound: nav.currentUpperRound,\n previousUpperRound: nav.previousUpperRound,\n nextUpperRound: nav.nextUpperRound,\n lowerRounds: lowerFlow,\n currentUpperRoundIndex,\n firstUpperRound,\n firstLowerRound,\n });\n }\n }\n }\n\n if (hasLowerRounds && firstLowerRound) {\n const assignedRoundIds = new Set(relations.map((r) => r.currentRound.id));\n\n // By depth and side rather than by array position: in a folded bracket the array holds two rounds\n // per depth, so its neighbours are whatever was emitted alongside - for an unfolded one the two are\n // the same thing.\n for (const lowerRound of lowerRounds) {\n if (assignedRoundIds.has(lowerRound.id)) continue;\n\n const side = lowerRound.mirrorRoundType;\n const depth = lowerRound.logicalIndex;\n const prevLowerRound = roundAtDepth({ byDepth: lowerRoundsByDepth, depth: depth - 1, side });\n const nextLowerRound = roundAtDepth({ byDepth: lowerRoundsByDepth, depth: depth + 1, side });\n\n if (nextLowerRound) {\n if (!prevLowerRound) {\n relations.push(createNothingToOneRelation({ currentRound: lowerRound, nextRound: nextLowerRound }));\n } else {\n relations.push(\n createOneToOneRelation({\n currentRound: lowerRound,\n previousRound: prevLowerRound,\n nextRound: nextLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n } else if (prevLowerRound) {\n // Truncated bracket: the last lower round has no final round to feed into, so it terminates here.\n // In a complete bracket this round is wired up by handleFinalRound and already in assignedRoundIds.\n relations.push(\n createOneToNothingRelation({\n currentRound: lowerRound,\n previousRound: prevLowerRound,\n rootRound: firstLowerRound,\n }),\n );\n }\n }\n }\n\n return relations;\n};\n","import {\n BracketMap,\n BracketMatchId,\n BracketRoundId,\n BracketRoundType,\n createBracketBase,\n CreateBracketOptions,\n MatchParticipantId,\n BracketMatchBase,\n BracketMatchParticipantBase,\n BracketParticipantBase,\n BracketRoundBase,\n TournamentMode,\n} from '../core';\nimport { BracketDataSource } from '../integrations';\nimport { BracketMatchRelation, BracketMatchRelationNone, generateMatchRelationsNew } from './match-relations';\nimport { BracketRoundRelation, BracketRoundRelationNone, generateRoundRelationsNew } from './round-relations';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../bracket-errors';\n\nexport type Bracket<TRoundData, TMatchData> = {\n rounds: BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>;\n roundsByType: BracketMap<BracketRoundType, BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>>;\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n participants: BracketMap<MatchParticipantId, BracketParticipant<TRoundData, TMatchData>>;\n mode: TournamentMode;\n};\n\nexport type BracketRound<TRoundData, TMatchData> = BracketRoundBase<TRoundData> & {\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n relation: BracketRoundRelation<TRoundData, TMatchData>;\n};\n\nexport type BracketMatch<TRoundData, TMatchData> = BracketMatchBase<TMatchData> & {\n round: BracketRound<TRoundData, TMatchData>;\n home: BracketMatchParticipant<TRoundData, TMatchData> | null;\n away: BracketMatchParticipant<TRoundData, TMatchData> | null;\n winner: BracketMatchParticipant<TRoundData, TMatchData> | null;\n relation: BracketMatchRelation<TRoundData, TMatchData>;\n};\n\nexport type BracketParticipantMatch<TRoundData, TMatchData> = BracketMatch<TRoundData, TMatchData> & {\n me: BracketMatchParticipant<TRoundData, TMatchData>;\n opponent: BracketMatchParticipant<TRoundData, TMatchData> | null;\n};\n\nexport type BracketParticipant<TRoundData, TMatchData> = BracketParticipantBase & {\n matches: BracketMap<BracketMatchId, BracketParticipantMatch<TRoundData, TMatchData>>;\n};\n\nexport type BracketMatchParticipant<TRoundData, TMatchData> = BracketMatchParticipantBase & {\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n};\n\nexport const createBracket = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: CreateBracketOptions<TMatchData>,\n) => {\n if (!source.rounds.length)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, 'The bracket source has no rounds to render');\n\n const bracketNewBase = createBracketBase(source, options);\n\n const rounds = new BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>();\n const roundsByType = new BracketMap<\n BracketRoundType,\n BracketMap<BracketRoundId, BracketRound<TRoundData, TMatchData>>\n >();\n\n for (const roundBase of bracketNewBase.rounds.values()) {\n const relation = { type: 'none' } as BracketRoundRelationNone<TRoundData, TMatchData>;\n const newRound: BracketRound<TRoundData, TMatchData> = { ...roundBase, matches: new BracketMap(), relation };\n relation.currentRound = newRound;\n rounds.set(roundBase.id, newRound);\n if (!roundsByType.has(roundBase.type)) {\n roundsByType.set(roundBase.type, new BracketMap());\n }\n roundsByType.getOrThrow(roundBase.type).set(roundBase.id, newRound);\n }\n\n const participants = new BracketMap<MatchParticipantId, BracketParticipant<TRoundData, TMatchData>>();\n\n for (const participantBase of bracketNewBase.participants.values()) {\n participants.set(participantBase.id, {\n ...participantBase,\n matches: new BracketMap(),\n });\n }\n\n const matches = new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>();\n\n for (const matchBase of bracketNewBase.matches.values()) {\n const round = rounds.getOrThrow(matchBase.roundId as BracketRoundId);\n\n const homeParticipant = matchBase.home\n ? { ...matchBase.home, matches: new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>() }\n : null;\n const awayParticipant = matchBase.away\n ? { ...matchBase.away, matches: new BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>() }\n : null;\n\n const relation = { type: 'none', currentRound: round } as BracketMatchRelationNone<TRoundData, TMatchData>;\n const newMatch: BracketMatch<TRoundData, TMatchData> = {\n ...matchBase,\n home: homeParticipant,\n away: awayParticipant,\n winner: null,\n round,\n relation,\n };\n relation.currentMatch = newMatch;\n\n if (matchBase.winner) {\n const winnerParticipant = homeParticipant?.id === matchBase.winner.id ? homeParticipant : awayParticipant;\n if (!winnerParticipant)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.WINNER_NOT_FOUND,\n `Winner participant with id ${matchBase.winner.id} not found in match base`,\n );\n newMatch.winner = winnerParticipant;\n }\n\n matches.set(matchBase.id, newMatch);\n round.matches.set(matchBase.id, newMatch);\n }\n\n const newBracket: Bracket<TRoundData, TMatchData> = {\n matches,\n participants,\n rounds,\n roundsByType,\n mode: bracketNewBase.mode,\n };\n\n const roundRelations = generateRoundRelationsNew(newBracket);\n\n for (const roundRelation of roundRelations) {\n roundRelation.currentRound.relation = roundRelation;\n }\n\n const matchRelations = generateMatchRelationsNew(newBracket, {\n source,\n previousMatchIds: options.previousMatchIds,\n onWarning: options.onWarning,\n });\n\n for (const matchRelation of matchRelations) {\n matchRelation.currentMatch.relation = matchRelation;\n }\n\n // After the relations, never before: a participant's view of a match is a copy of it, so building it\n // any earlier would freeze the placeholder relation into every copy.\n for (const match of matches.values()) {\n if (match.home) {\n participants.getOrThrow(match.home.id).matches.set(match.id, { ...match, me: match.home, opponent: match.away });\n }\n if (match.away) {\n participants.getOrThrow(match.away.id).matches.set(match.id, { ...match, me: match.away, opponent: match.home });\n }\n }\n\n for (const participant of participants.values()) {\n for (const match of participant.matches.values()) {\n if (match.home?.id === participant.id) match.home.matches = participant.matches;\n if (match.away?.id === participant.id) match.away.matches = participant.matches;\n if (match.winner?.id === participant.id) match.winner.matches = participant.matches;\n }\n }\n\n return newBracket;\n};\n","import { BracketMatchId, MatchParticipantSide } from '../core';\nimport { BracketMatchOutcomeSlotSource, BracketSlotSource } from '../integrations';\nimport { Bracket, BracketMatch } from './bracket';\n\n/** The table position a `standing-rank` slot asks about, and the slot that asks. */\nexport type BracketStandingRankPickQuery = {\n standingId: string;\n rank: number;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n};\n\nexport type BracketPickSet = {\n /** The participant the viewer picked to win a match. */\n matchWinner: (matchId: string) => string | null;\n /** The participant the viewer put on a table position. */\n standingRank: (options: BracketStandingRankPickQuery) => string | null;\n};\n\nexport const isBracketSlotPredictable = (source: BracketSlotSource | null): boolean =>\n source?.kind === 'match-outcome' || source?.kind === 'standing-rank' || source?.kind === 'seed';\n\n/** How a resolution weighs a prediction against what is already known. Both parts default to the stricter answer. */\nexport type BracketSlotResolutionPolicy = {\n /**\n * Whether the participant really standing on a slot of the given match outranks whatever the picks\n * predict for it. Must answer from the match alone, and answer the same way throughout one\n * resolution: the walk memoizes per slot.\n *\n * `true` answers with the real participant wherever one is known - the pairing a pick was made\n * against, which is what an open round should show. `false`, the default, answers with the\n * prediction even where reality already disagrees, which is what a locked round should show: the\n * record of the guess.\n */\n realParticipantOutranksPick?: (match: BracketMatch<unknown, unknown>) => boolean;\n\n /**\n * Whether a predicted winner still counts while one side of the match it was made on is unknown.\n * `false`, the default, drops it until both sides resolve. `true` keeps it until both sides are\n * known and it is neither of them - until then nothing contradicts it.\n */\n keepPickWhileFeederSideIsOpen?: boolean;\n\n /**\n * Whether a `match-outcome` or `standing-rank` slot the picks leave empty answers with the\n * participant really standing there. `false`, the default, leaves it empty.\n */\n fallBackToRealParticipant?: boolean;\n};\n\ntype BracketSlotResolverOptions = BracketSlotResolutionPolicy & {\n bracket: Bracket<unknown, unknown>;\n picks: BracketPickSet;\n /**\n * Earlier stages a `match-outcome` slot of `bracket` may point into. A feeder is looked up in\n * `bracket` first, then in these in order, so match ids must be unique across all of them.\n */\n linkedBrackets?: readonly Bracket<unknown, unknown>[];\n};\n\ntype ResolveBracketSlotOptions = BracketSlotResolverOptions & {\n matchId: string;\n side: MatchParticipantSide;\n};\n\nconst sourceFor = (match: BracketMatch<unknown, unknown>, side: MatchParticipantSide) =>\n side === 'home' ? match.homeSource : match.awaySource;\n\nconst participantIdFor = (match: BracketMatch<unknown, unknown>, side: MatchParticipantSide) => match[side]?.id ?? null;\n\ntype ResolveWalk = {\n lookupMatch: (matchId: string) => BracketMatch<unknown, unknown> | undefined;\n picks: BracketPickSet;\n realParticipantOutranksPick: (match: BracketMatch<unknown, unknown>) => boolean;\n keepPickWhileFeederSideIsOpen: boolean;\n fallBackToRealParticipant: boolean;\n visitDepths: Map<string, number>;\n resolved: Map<string, string | null>;\n shallowestCycleHit: number;\n};\n\nconst resolveMatchOutcome = (options: { walk: ResolveWalk; source: BracketMatchOutcomeSlotSource }): string | null => {\n const { walk, source } = options;\n\n const feeder = walk.lookupMatch(source.matchId);\n\n if (!feeder) return null;\n\n const homeSource = sourceFor(feeder, 'home');\n const awaySource = sourceFor(feeder, 'away');\n const home = resolveSlot({ walk, match: feeder, side: 'home' });\n const away = resolveSlot({ walk, match: feeder, side: 'away' });\n\n if (homeSource?.kind === 'bye' && awaySource?.kind !== 'bye') {\n return source.role !== 'loser' ? away : null;\n }\n\n if (awaySource?.kind === 'bye' && homeSource?.kind !== 'bye') {\n return source.role !== 'loser' ? home : null;\n }\n\n if (!home || !away) {\n return walk.keepPickWhileFeederSideIsOpen && source.role !== 'loser' ? walk.picks.matchWinner(feeder.id) : null;\n }\n\n const pickedWinner = walk.picks.matchWinner(feeder.id);\n\n if (pickedWinner !== home && pickedWinner !== away) return null;\n\n return source.role !== 'loser' ? pickedWinner : pickedWinner === home ? away : home;\n};\n\nconst resolveSource = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n source: BracketSlotSource;\n}): string | null => {\n const { walk, match, side, source } = options;\n\n switch (source.kind) {\n case 'match-outcome':\n return resolveMatchOutcome({ walk, source });\n case 'standing-rank':\n return walk.picks.standingRank({ standingId: source.standingId, rank: source.rank, match, side });\n case 'seed':\n case 'swiss-bucket':\n case 'external':\n case 'unknown':\n return participantIdFor(match, side);\n case 'bye':\n return null;\n }\n};\n\nconst resolveSlotOccupant = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n}): string | null => {\n const { walk, match, side } = options;\n const real = participantIdFor(match, side);\n\n if (real !== null && walk.realParticipantOutranksPick(match)) return real;\n\n const source = sourceFor(match, side);\n\n if (!source) return real;\n\n const resolved = resolveSource({ walk, match, side, source });\n\n if (resolved !== null || !walk.fallBackToRealParticipant) return resolved;\n\n return source.kind === 'match-outcome' || source.kind === 'standing-rank' ? real : null;\n};\n\nconst resolveSlot = (options: {\n walk: ResolveWalk;\n match: BracketMatch<unknown, unknown>;\n side: MatchParticipantSide;\n}): string | null => {\n const { walk, match, side } = options;\n const visitKey = `${match.id}:${side}`;\n const openDepth = walk.visitDepths.get(visitKey);\n\n if (openDepth !== undefined) {\n walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, openDepth);\n\n return null;\n }\n\n const resolved = walk.resolved.get(visitKey);\n\n if (resolved !== undefined) return resolved;\n\n const depth = walk.visitDepths.size;\n const shallowestCycleHitBefore = walk.shallowestCycleHit;\n\n walk.visitDepths.set(visitKey, depth);\n walk.shallowestCycleHit = Infinity;\n\n try {\n const result = resolveSlotOccupant({ walk, match, side });\n\n // A result whose cycle guard only fired on this slot or below it is a function of the slot alone.\n // One that hit a slot above it depends on the path that reached it, so caching it would answer a\n // later path with a cycle's `null`.\n if (walk.shallowestCycleHit >= depth) walk.resolved.set(visitKey, result);\n\n return result;\n } finally {\n walk.visitDepths.delete(visitKey);\n walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, shallowestCycleHitBefore);\n }\n};\n\nconst matchLookupFor = (brackets: readonly Bracket<unknown, unknown>[]) => (matchId: string) => {\n for (const bracket of brackets) {\n const match = bracket.matches.get(matchId as BracketMatchId);\n\n if (match) return match;\n }\n\n return undefined;\n};\n\nconst createResolveWalk = (options: BracketSlotResolverOptions): ResolveWalk => ({\n lookupMatch: matchLookupFor([options.bracket, ...(options.linkedBrackets ?? [])]),\n picks: options.picks,\n realParticipantOutranksPick: options.realParticipantOutranksPick ?? (() => false),\n keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen ?? false,\n fallBackToRealParticipant: options.fallBackToRealParticipant ?? false,\n visitDepths: new Map(),\n resolved: new Map(),\n shallowestCycleHit: Infinity,\n});\n\n/**\n * @internal A {@link resolveBracketSlot} that shares one memo across its calls. Valid only while the\n * picks it was created with do not change.\n */\nexport const createBracketSlotResolver = (options: BracketSlotResolverOptions) => {\n const walk = createResolveWalk(options);\n\n return (matchId: string, side: MatchParticipantSide): string | null => {\n const match = options.bracket.matches.get(matchId as BracketMatchId);\n\n return match ? resolveSlot({ walk, match, side }) : null;\n };\n};\n\n/** Who the viewer's own picks put in a slot, or `null` while their picks do not reach it. */\nexport const resolveBracketSlot = (options: ResolveBracketSlotOptions): string | null =>\n createBracketSlotResolver(options)(options.matchId, options.side);\n","import { BracketMatchId } from '../core';\nimport { Bracket, BracketMatch } from './bracket';\nimport {\n BracketPickSet,\n BracketSlotResolutionPolicy,\n BracketStandingRankPickQuery,\n createBracketSlotResolver,\n} from './resolve-bracket-slot';\n\nexport type BracketPickMigrationOptions = BracketSlotResolutionPolicy & {\n bracket: Bracket<unknown, unknown>;\n /**\n * Earlier stages a `match-outcome` slot of `bracket` may point into. Their picks are read from\n * {@link pickAsMade} as given, so migrate an earlier stage first and answer with its result.\n */\n linkedBrackets?: readonly Bracket<unknown, unknown>[];\n /** The participant the viewer picked on a match, on the match they picked it on. */\n pickAsMade: (matchId: string) => string | null;\n /** The participant the viewer put on a table position, for the `standing-rank` slots a round resolves from. */\n standingRank?: (options: BracketStandingRankPickQuery) => string | null;\n /** Matches whose picks the backend already keeps. Their picks neither travel out nor take one in. */\n lockedMatchIds?: ReadonlySet<string>;\n};\n\nexport type BracketPickMigration = {\n /** The pick that counts on a match: the one made on it, or the one that followed its participant here. */\n pickByMatchId: Record<string, string | undefined>;\n /** For a match that took a pick in, the match that pick was made on. */\n movedFromByMatchId: Record<string, string | undefined>;\n /** For a match whose pick nothing in its round can honour, that pick. Such a match holds no selection. */\n strandedByMatchId: Record<string, string | undefined>;\n};\n\n// Grouped by type and depth rather than by round id: a mirrored layout splits one round into two\n// half-rounds to draw either side of the fold, and a pick has to be able to travel across it. Ordered\n// topologically over the declared provenance, because a round is settled against the ones feeding it.\nconst roundsOf = (bracket: Bracket<unknown, unknown>): BracketMatch<unknown, unknown>[][] => {\n const matchesByKey = new Map<string, BracketMatch<unknown, unknown>[]>();\n const keyByMatchId = new Map<string, string>();\n\n for (const round of bracket.rounds.values()) {\n const key = `${round.type}:${round.logicalIndex}`;\n const matches = matchesByKey.get(key) ?? [];\n\n for (const match of round.matches.values()) {\n matches.push(match);\n keyByMatchId.set(match.id, key);\n }\n\n matchesByKey.set(key, matches);\n }\n\n const unsettledFeedersByKey = new Map<string, Set<string>>();\n\n for (const [key, matches] of matchesByKey) {\n const feeders = new Set<string>();\n\n for (const match of matches) {\n for (const source of [match.homeSource, match.awaySource]) {\n if (source?.kind !== 'match-outcome' || !source.matchId) continue;\n\n const feederKey = keyByMatchId.get(source.matchId);\n\n if (feederKey !== undefined && feederKey !== key) feeders.add(feederKey);\n }\n }\n\n unsettledFeedersByKey.set(key, feeders);\n }\n\n const ordered: BracketMatch<unknown, unknown>[][] = [];\n\n while (unsettledFeedersByKey.size) {\n const keys = [...unsettledFeedersByKey.keys()];\n // A malformed graph can leave a cycle in which nothing is ready, so fall back to the first\n // round left rather than looping forever.\n const key = keys.find((candidate) => !unsettledFeedersByKey.get(candidate)?.size) ?? keys[0];\n\n if (key === undefined) break;\n\n ordered.push(matchesByKey.get(key) ?? []);\n unsettledFeedersByKey.delete(key);\n\n for (const feeders of unsettledFeedersByKey.values()) feeders.delete(key);\n }\n\n return ordered;\n};\n\n/**\n * Where every pick stands once each one has followed its participant into whichever match of its own\n * round that participant now plays. A pick nothing in the round can honour comes back stranded.\n */\nexport const migrateBracketPicks = (options: BracketPickMigrationOptions): BracketPickMigration => {\n const { bracket, pickAsMade } = options;\n const locked = options.lockedMatchIds ?? new Set<string>();\n const pickByMatchId: Record<string, string | undefined> = {};\n const movedFromByMatchId: Record<string, string | undefined> = {};\n const strandedByMatchId: Record<string, string | undefined> = {};\n\n const settled: BracketPickSet = {\n matchWinner: (matchId) =>\n bracket.matches.has(matchId as BracketMatchId) ? (pickByMatchId[matchId] ?? null) : pickAsMade(matchId),\n standingRank: options.standingRank ?? (() => null),\n };\n\n for (const round of roundsOf(bracket)) {\n const sidesByMatchId = new Map<string, [string | null, string | null]>();\n const travelling: { matchId: string; pick: string }[] = [];\n const strandedHere = new Set<string>();\n const sidesOf = (matchId: string) => sidesByMatchId.get(matchId) ?? [null, null];\n\n const resolve = createBracketSlotResolver({\n bracket,\n linkedBrackets: options.linkedBrackets,\n picks: settled,\n realParticipantOutranksPick: options.realParticipantOutranksPick,\n keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen,\n fallBackToRealParticipant: options.fallBackToRealParticipant,\n });\n\n for (const match of round) {\n sidesByMatchId.set(match.id, [resolve(match.id, 'home'), resolve(match.id, 'away')]);\n }\n\n for (const match of round) {\n const pick = pickAsMade(match.id);\n\n if (!pick) continue;\n\n const [home, away] = sidesOf(match.id);\n\n if (pick === home || pick === away) {\n pickByMatchId[match.id] = pick;\n\n continue;\n }\n\n if (locked.has(match.id)) {\n pickByMatchId[match.id] = pick;\n strandedByMatchId[match.id] = pick;\n\n continue;\n }\n\n travelling.push({ matchId: match.id, pick });\n }\n\n for (const { matchId, pick } of travelling) {\n const target = round.find((candidate) => {\n if (candidate.id === matchId || locked.has(candidate.id) || pickByMatchId[candidate.id]) return false;\n if (strandedHere.has(candidate.id)) return false;\n\n const [home, away] = sidesOf(candidate.id);\n\n return pick === home || pick === away;\n });\n\n if (!target) {\n strandedByMatchId[matchId] = pick;\n strandedHere.add(matchId);\n\n continue;\n }\n\n pickByMatchId[target.id] = pick;\n movedFromByMatchId[target.id] = matchId;\n }\n\n // After the travelling, not during it: a match that carries the stranded note holds no selection\n // at all, even where a pick reached it in the meantime.\n for (const matchId of strandedHere) delete pickByMatchId[matchId];\n }\n\n return { pickByMatchId, movedFromByMatchId, strandedByMatchId };\n};\n","import {\n BracketMap,\n BracketMatchId,\n BracketMatchParticipantBase,\n BracketRoundId,\n SWISS_ADVANCE_WINS,\n SWISS_ELIMINATE_LOSSES,\n TOURNAMENT_MODE,\n TournamentMode,\n isSwissMode,\n} from '../core';\nimport { Bracket, BracketMatch } from './bracket';\n\nexport type BracketRoundSwissGroupId = string & { _brand: 'BracketRoundSwissGroupId' };\n\nexport type BracketRoundSwissGroup<TRoundData, TMatchData> = {\n id: BracketRoundSwissGroupId;\n name: string;\n matches: BracketMap<BracketMatchId, BracketMatch<TRoundData, TMatchData>>;\n allowedMatchCount: number;\n /** The record tone of the group - see {@link getSwissGroupColorType}. */\n colorType: BracketSwissGroupColorType;\n};\n\nexport type BracketRoundSwissGroupMap<TRoundData, TMatchData> = Map<\n BracketRoundSwissGroupId,\n BracketRoundSwissGroup<TRoundData, TMatchData>\n>;\n\nexport type BracketRoundSwissData<TRoundData, TMatchData> = {\n groups: BracketRoundSwissGroupMap<TRoundData, TMatchData>;\n};\n\nexport type BracketRoundMapWithSwissData<TRoundData, TMatchData> = Map<\n BracketRoundId,\n BracketRoundSwissData<TRoundData, TMatchData>\n>;\n\nexport const BRACKET_SWISS_GROUP_COLOR_TYPE = {\n /** The starting group (0-0) */\n NEUTRAL: 'neutral',\n\n /** The group has more wins than losses */\n POSITIVE: 'positive',\n\n /** The group is one loss away from elimination */\n NEGATIVE: 'negative',\n\n /** Everything in between */\n WARNING: 'warning',\n} as const;\n\nexport type BracketSwissGroupColorType =\n (typeof BRACKET_SWISS_GROUP_COLOR_TYPE)[keyof typeof BRACKET_SWISS_GROUP_COLOR_TYPE];\n\n/**\n * Colors for the swiss group borders and connection lines, keyed by the group color type\n * (see {@link getSwissGroupColorType}). Connection lines are drawn in the neutral color and fade\n * into the target group color on the last portion before touching its border.\n * Any CSS color value is allowed. Missing entries fall back to the connector/border color\n * (the `--et-bracket-line-color` / `--et-bracket-swiss-group-border-color` custom properties,\n * which default to `--et-surface-border`).\n */\nexport type BracketSwissColors = Partial<Record<BracketSwissGroupColorType, string>>;\n\n/** The record tone of a swiss group. A `'swiss'` stage eliminates nobody, so it has no negative tone. */\nexport const getSwissGroupColorType = (\n wins: number,\n losses: number,\n mode: TournamentMode = TOURNAMENT_MODE.SWISS_WITH_ELIMINATION,\n // eslint-disable-next-line max-params -- public (wins, losses) signature; the mode is an optional third fact\n): BracketSwissGroupColorType => {\n if (wins === 0 && losses === 0) return BRACKET_SWISS_GROUP_COLOR_TYPE.NEUTRAL;\n if (mode !== TOURNAMENT_MODE.SWISS && losses === SWISS_ELIMINATE_LOSSES - 1)\n return BRACKET_SWISS_GROUP_COLOR_TYPE.NEGATIVE;\n if (wins > losses) return BRACKET_SWISS_GROUP_COLOR_TYPE.POSITIVE;\n\n return BRACKET_SWISS_GROUP_COLOR_TYPE.WARNING;\n};\n\nconst factorialCache = /* @__PURE__ */ new Map<number, number>();\n\nexport const getAvailableSwissGroupsForRound = (\n roundNumber: number,\n totalMatchesInRound: number,\n mode: TournamentMode = TOURNAMENT_MODE.SWISS_WITH_ELIMINATION,\n // eslint-disable-next-line max-params -- public (round, match count) signature; the mode is an optional third fact\n) => {\n const limited = mode !== TOURNAMENT_MODE.SWISS;\n const advanceWins = limited ? SWISS_ADVANCE_WINS : Infinity;\n const eliminateLosses = limited ? SWISS_ELIMINATE_LOSSES : Infinity;\n\n const getFactorial = (n: number): number => {\n if (n <= 1) return 1;\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n if (factorialCache.has(n)) return factorialCache.get(n)!;\n\n const result = n * getFactorial(n - 1);\n factorialCache.set(n, result);\n return result;\n };\n\n const roundFactorial = getFactorial(roundNumber);\n\n let totalCombinations = 0;\n const validGroups: { wins: number; losses: number; combinations: number }[] = [];\n\n for (let wins = roundNumber; wins >= 0; wins--) {\n const losses = roundNumber - wins;\n const remainingGames = advanceWins + eliminateLosses - (wins + losses) - 1;\n const notYetEliminated = losses < eliminateLosses;\n const canStillAdvance = wins < advanceWins && remainingGames >= 0;\n\n if (!canStillAdvance || !notYetEliminated) continue;\n\n const combinations = roundFactorial / (getFactorial(wins) * getFactorial(losses));\n totalCombinations += combinations;\n validGroups.push({ wins, losses, combinations });\n }\n\n return validGroups.map(({ wins, losses, combinations }) => ({\n wins,\n losses,\n id: `${wins}-${losses}` as BracketRoundSwissGroupId,\n name: `${wins}-${losses}`,\n matchesInGroup: Math.round((combinations / totalCombinations) * totalMatchesInRound),\n }));\n};\n\n/** The group an undrawn match falls into when its round has no win/loss record to group by. */\nconst UNDRAWN_SWISS_GROUP_ID = 'undrawn' as BracketRoundSwissGroupId;\n\nconst getRecordBeforeMatch = (participant: BracketMatchParticipantBase) => ({\n wins: participant.winCount - (participant.result === 'win' ? 1 : 0),\n losses: participant.lossCount - (participant.result === 'loss' ? 1 : 0),\n});\n\nexport const generateBracketRoundSwissGroupMaps = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n) => {\n if (!isSwissMode(bracketData.mode)) {\n return null;\n }\n\n const roundsWithSwissGroups: BracketRoundMapWithSwissData<TRoundData, TMatchData> = new Map();\n\n let roundNumber = 0;\n for (const bracketRound of bracketData.rounds.values()) {\n const availableGroups = getAvailableSwissGroupsForRound(roundNumber, bracketRound.matchCount, bracketData.mode);\n const colorTypeOf = (wins: number, losses: number) => getSwissGroupColorType(wins, losses, bracketData.mode);\n\n const roundSwissData: BracketRoundSwissData<TRoundData, TMatchData> = {\n groups: new Map(),\n };\n\n for (const group of availableGroups) {\n const subGroup: BracketRoundSwissGroup<TRoundData, TMatchData> = {\n id: group.id,\n name: group.name,\n matches: new BracketMap(),\n allowedMatchCount: group.matchesInGroup,\n colorType: colorTypeOf(group.wins, group.losses),\n };\n\n roundSwissData.groups.set(group.id, subGroup);\n }\n\n const emptyMatchIds: BracketMatchId[] = [];\n\n for (const match of bracketRound.matches.values()) {\n const anyParticipant = match.home || match.away;\n\n if (!anyParticipant) {\n emptyMatchIds.push(match.id);\n continue;\n }\n\n const { wins, losses } = getRecordBeforeMatch(anyParticipant);\n const groupId = `${wins}-${losses}` as BracketRoundSwissGroupId;\n\n // The table above enumerates the records of somebody who played every round. A bye, a walkover or\n // an uneven field leaves a participant with fewer games than the round index, so their group is\n // real but not in the table - create it rather than losing the whole bracket over one match.\n let group = roundSwissData.groups.get(groupId);\n\n if (!group) {\n group = {\n id: groupId,\n name: `${wins}-${losses}`,\n matches: new BracketMap(),\n allowedMatchCount: 0,\n colorType: colorTypeOf(wins, losses),\n };\n roundSwissData.groups.set(groupId, group);\n }\n\n group.matches.set(match.id, match);\n }\n\n for (const emptyMatchId of emptyMatchIds) {\n const match = bracketRound.matches.getOrThrow(emptyMatchId);\n const groups = [...roundSwissData.groups.values()];\n let group =\n groups.find((candidate) => candidate.matches.size < candidate.allowedMatchCount) ??\n groups.reduce<BracketRoundSwissGroup<TRoundData, TMatchData> | null>(\n (fewest, candidate) => (!fewest || candidate.matches.size < fewest.matches.size ? candidate : fewest),\n null,\n );\n\n // A round past the last one a 3-3 swiss can reach - the elimination rounds of a\n // swiss-with-elimination stage - has no record groups, and an undrawn match carries no record to\n // build one from. A nameless group keeps the round drawn instead of losing the whole bracket.\n if (!group) {\n group = {\n id: UNDRAWN_SWISS_GROUP_ID,\n name: '',\n matches: new BracketMap(),\n allowedMatchCount: 0,\n colorType: BRACKET_SWISS_GROUP_COLOR_TYPE.NEUTRAL,\n };\n roundSwissData.groups.set(group.id, group);\n }\n\n group.matches.set(match.id, match);\n }\n\n for (const [groupId, group] of roundSwissData.groups) {\n if (!group.matches.size) roundSwissData.groups.delete(groupId);\n }\n\n // The map is drawn top to bottom in insertion order, so a group created on demand has to be sorted\n // back into the best-record-first order the table was built in.\n const orderedGroups = [...roundSwissData.groups.entries()].sort(([a], [b]) => {\n const [aWins = 0, aLosses = 0] = a.split('-').map(Number);\n const [bWins = 0, bLosses = 0] = b.split('-').map(Number);\n\n return bWins - aWins || aLosses - bLosses;\n });\n\n roundSwissData.groups = new Map(orderedGroups);\n\n roundsWithSwissGroups.set(bracketRound.id, roundSwissData);\n\n roundNumber++;\n }\n\n return roundsWithSwissGroups;\n};\n","import { BracketMatchId, MatchParticipantSide } from '../core';\nimport { Bracket } from './bracket';\n\nexport type BracketStandingRankSide = {\n side: MatchParticipantSide;\n standingId: string;\n rank: number;\n standingName: string | null;\n /** The participant really standing on the side, or `null` while the standing is not decided. */\n participantId: string | null;\n};\n\n/** The sides of a match whose source is a `standing-rank` slot, home first. Empty for an unknown match. */\nexport const standingRankSides = (options: {\n bracket: Bracket<unknown, unknown>;\n matchId: string;\n}): BracketStandingRankSide[] => {\n const match = options.bracket.matches.get(options.matchId as BracketMatchId);\n\n if (!match) return [];\n\n return (['home', 'away'] as const).flatMap((side) => {\n const source = side === 'home' ? match.homeSource : match.awaySource;\n\n if (source?.kind !== 'standing-rank') return [];\n\n return [\n {\n side,\n standingId: source.standingId,\n rank: source.rank,\n standingName: source.standingName ?? null,\n participantId: match[side]?.id ?? null,\n },\n ];\n });\n};\n","import { CreateBracketOptions } from '../core';\nimport { BracketRuntimeError } from '../bracket-runtime-error';\nimport { BracketDataSource } from '../integrations';\nimport { createBracket } from './bracket';\n\n/**\n * Runs {@link createBracket} on `source` and returns the `BracketRuntimeError` it would throw, or `null` for a\n * usable source. Any other error is rethrown.\n */\nexport const validateBracketSource = <TRoundData, TMatchData>(\n source: BracketDataSource<TRoundData, TMatchData>,\n options: CreateBracketOptions<TMatchData>,\n): BracketRuntimeError | null => {\n try {\n createBracket(source, options);\n\n return null;\n } catch (error) {\n if (error instanceof BracketRuntimeError) return error;\n\n throw error;\n }\n};\n","import { BracketRoundSwissData, generateBracketRoundSwissGroupMaps, Bracket } from '../../linked';\nimport {\n BracketComponents,\n BracketElementToCreate,\n createBracketElement,\n createBracketGrid,\n createBracketMasterColumn,\n createBracketMasterColumnSection,\n createBracketSubColumn,\n finalizeBracketGrid,\n} from './core';\nimport { createBracketGapMasterColumn } from './prebuild';\nimport { ComputedBracketGrid, CreateBracketGridConfig } from './types';\nimport { BracketRuntimeError } from '../../bracket-runtime-error';\nimport { BRACKET_ERROR_CODES } from '../../bracket-errors';\n\ntype SwissColumnMetrics = {\n naturalHeight: number;\n stretchableGapCount: number;\n};\n\nconst getSwissGroupBoxPadding = (options: CreateBracketGridConfig) =>\n options.swissGroupPadding + options.swissGroupBorderWidth;\n\nconst calculateSwissColumnMetrics = <TRoundData, TMatchData>(\n groupMap: BracketRoundSwissData<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n): SwissColumnMetrics => {\n const includeHeaders = options.roundHeaderHeight > 0;\n const boxPadding = getSwissGroupBoxPadding(options);\n\n let naturalHeight = 0;\n let stretchableGapCount = 0;\n\n for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {\n if (groupIndex !== 0) {\n // The gap section between two groups\n naturalHeight += options.rowRoundGap;\n stretchableGapCount++;\n }\n\n // The round header gap is not stretchable: the first match should always sit directly\n // below it, no matter how much a column gets stretched.\n if (includeHeaders) {\n naturalHeight += options.roundHeaderHeight + options.roundHeaderGap;\n }\n\n const matchGapCount = Math.max(0, group.matches.size - 1);\n\n naturalHeight += boxPadding * 2 + group.matches.size * options.matchHeight + matchGapCount * options.rowGap;\n stretchableGapCount += matchGapCount;\n }\n\n return { naturalHeight, stretchableGapCount };\n};\n\n// The naturally tallest master column (the round with the most groups) keeps the original\n// gaps (rowGap, rowRoundGap, roundHeaderGap) and defines the total bracket height.\n// The master cols before it are stretched to that height by distributing the missing\n// height evenly across all of their gap elements.\n// The master cols after it keep the original gaps, resulting in a top alignment. They get\n// one more gap element at the end of the column to fill the remaining space if any.\nexport const createSwissGrid = <TRoundData, TMatchData>(\n bracketData: Bracket<TRoundData, TMatchData>,\n options: CreateBracketGridConfig,\n components: BracketComponents<TRoundData, TMatchData>,\n // eslint-disable-next-line max-params -- grid builder signature (data, options, components)\n): ComputedBracketGrid<TRoundData, TMatchData> => {\n const swissGroupMaps = generateBracketRoundSwissGroupMaps(bracketData);\n\n if (!swissGroupMaps)\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.SWISS_GROUPING_FAILED,\n 'Unable to generate Swiss groups for the provided bracket data',\n );\n\n const grid = createBracketGrid<TRoundData, TMatchData>({ spanElementWidth: options.columnWidth });\n\n const groupMaps = Array.from(swissGroupMaps.values());\n const columnMetrics = groupMaps.map((groupMap) => calculateSwissColumnMetrics(groupMap, options));\n\n const totalHeight = Math.max(...columnMetrics.map((metrics) => metrics.naturalHeight));\n const longestColumnIndex = columnMetrics.findIndex((metrics) => metrics.naturalHeight === totalHeight);\n\n for (const [groupMapIndex, groupMap] of groupMaps.entries()) {\n const isLastGroupMap = groupMapIndex === swissGroupMaps.size - 1;\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const metrics = columnMetrics[groupMapIndex]!;\n const heightToFill = totalHeight - metrics.naturalHeight;\n const isStretched = groupMapIndex < longestColumnIndex && metrics.stretchableGapCount > 0;\n const gapStretch = isStretched ? heightToFill / metrics.stretchableGapCount : 0;\n\n const rowGap = options.rowGap + gapStretch;\n const rowRoundGap = options.rowRoundGap + gapStretch;\n\n // The border and group padding are part of the column width (the match elements\n // shrink by them), so the column footprint stays at columnWidth and the group borders\n // drawn around the matches don't overflow the bracket container. The padding lives on\n // the match list sections, the header and gap sections stay unpadded and span the\n // whole column width.\n const boxPadding = getSwissGroupBoxPadding(options);\n\n const { masterColumn, pushSection } = createBracketMasterColumn<TRoundData, TMatchData>({\n columnWidth: options.columnWidth,\n padding: {\n bottom: 0,\n left: 0,\n right: 0,\n top: 0,\n },\n });\n\n for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {\n const isLastGroup = groupIndex === groupMap.groups.size - 1;\n\n if (options.roundHeaderHeight > 0) {\n const firstMatchRound = group.matches.first()?.round;\n\n if (!firstMatchRound)\n throw new BracketRuntimeError(BRACKET_ERROR_CODES.SWISS_GROUP_EMPTY, 'No rounds found in Swiss group');\n\n const headerColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n });\n\n const headerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const headerElement = createBracketElement<TRoundData, TMatchData>({\n type: 'header',\n area: `h${group.id}`,\n partHeights: [options.roundHeaderHeight],\n elementHeight: options.roundHeaderHeight,\n component: components.roundHeader,\n round: firstMatchRound,\n roundSwissGroup: group,\n });\n\n const headerGapElement = createBracketElement<TRoundData, TMatchData>({\n type: 'roundHeaderGap',\n area: '.',\n partHeights: [options.roundHeaderGap],\n elementHeight: options.roundHeaderGap,\n });\n\n headerSubColumn.pushElement(headerElement, headerGapElement);\n headerColumnSection.pushSubColumn(headerSubColumn.subColumn);\n pushSection(headerColumnSection.masterColumnSection);\n }\n\n const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'round',\n padding: {\n bottom: boxPadding,\n left: boxPadding,\n right: boxPadding,\n top: boxPadding,\n },\n });\n\n const { subColumn, pushElement } = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const elementsToCreate: Array<BracketElementToCreate<TRoundData, TMatchData>> = [];\n\n for (const [matchIndex, match] of Array.from(group.matches.values()).entries()) {\n const isLastMatch = matchIndex === group.matches.size - 1;\n\n elementsToCreate.push({\n type: 'match',\n area: `m${match.shortId}`,\n partHeights: [options.matchHeight],\n elementHeight: options.matchHeight,\n component: components.match,\n match,\n round: match.round,\n roundSwissGroup: group,\n });\n\n if (!isLastMatch) {\n elementsToCreate.push({\n type: 'matchGap',\n area: '.',\n partHeights: [rowGap],\n elementHeight: rowGap,\n });\n }\n }\n\n for (const elementData of elementsToCreate) {\n const element = createBracketElement(elementData);\n\n pushElement(element);\n }\n\n pushSubColumn(subColumn);\n pushSection(masterColumnSection);\n\n if (!isLastGroup) {\n const groupGapColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const groupGapSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const groupGapElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'roundGap',\n elementHeight: rowRoundGap,\n partHeights: [rowRoundGap],\n });\n\n groupGapSubColumn.pushElement(groupGapElement);\n\n groupGapColumnSection.pushSubColumn(groupGapSubColumn.subColumn);\n\n pushSection(groupGapColumnSection.masterColumnSection);\n }\n }\n\n // Top aligned columns end above the total height, so we fill the remaining space with\n // one last gap element.\n const fillerHeight = isStretched ? 0 : heightToFill;\n\n if (fillerHeight > 0) {\n const fillerColumnSection = createBracketMasterColumnSection<TRoundData, TMatchData>({\n type: 'gap',\n });\n\n const fillerSubColumn = createBracketSubColumn<TRoundData, TMatchData>({\n span: {\n isStart: true,\n isEnd: true,\n },\n });\n\n const fillerElement = createBracketElement<TRoundData, TMatchData>({\n area: '.',\n type: 'colGap',\n elementHeight: fillerHeight,\n partHeights: [fillerHeight],\n });\n\n fillerSubColumn.pushElement(fillerElement);\n fillerColumnSection.pushSubColumn(fillerSubColumn.subColumn);\n pushSection(fillerColumnSection.masterColumnSection);\n }\n\n grid.pushMasterColumn(masterColumn);\n\n if (!isLastGroupMap) {\n grid.pushMasterColumn(\n createBracketGapMasterColumn({\n existingMasterColumns: grid.grid.masterColumns,\n columnGap: options.columnGap,\n }),\n );\n }\n }\n\n grid.calculateDimensions();\n\n const finalizedGrid = finalizeBracketGrid(grid);\n\n return {\n raw: grid,\n columns: finalizedGrid.columns,\n matchElementMap: finalizedGrid.elementMap,\n };\n};\n","import {\n BracketByeSlotSource,\n BracketExternalSlotSource,\n BracketMatchOutcomeSlotSource,\n BracketSeedSlotSource,\n BracketStandingRankSlotSource,\n BracketSwissBucketSlotSource,\n BracketUnknownSlotSource,\n} from './base';\n\n/**\n * Constructors for every {@link BracketSlotSource} kind, each taking an optional competition `label`.\n *\n * @example\n * homeSource: bracketSlot.matchOutcome('semi-final-1', 'winner'),\n * awaySource: bracketSlot.standingRank('group-a', 2, 'Group A'),\n */\nexport const bracketSlot = {\n // eslint-disable-next-line max-params -- positional slot constructors read like the slot they build\n matchOutcome: (\n matchId: string,\n role: 'winner' | 'loser' | null,\n label: string | null = null,\n ): BracketMatchOutcomeSlotSource => ({ kind: 'match-outcome', matchId, role, label }),\n // eslint-disable-next-line max-params -- positional slot constructors read like the slot they build\n standingRank: (\n standingId: string,\n rank: number,\n standingName: string | null = null,\n label: string | null = null,\n ): BracketStandingRankSlotSource => ({ kind: 'standing-rank', standingId, rank, standingName, label }),\n seed: (seed: number, label: string | null = null): BracketSeedSlotSource => ({ kind: 'seed', seed, label }),\n swissBucket: (label: string | null = null): BracketSwissBucketSlotSource => ({ kind: 'swiss-bucket', label }),\n bye: (label: string | null = null): BracketByeSlotSource => ({ kind: 'bye', label }),\n external: (label: string): BracketExternalSlotSource => ({ kind: 'external', label }),\n unknown: (label: string | null = null): BracketUnknownSlotSource => ({ kind: 'unknown', label }),\n} as const;\n","import { BRACKET_ERROR_CODES } from './bracket-errors';\nimport { BracketRuntimeError } from './bracket-runtime-error';\nimport { TournamentMode } from './core';\n\nexport type BracketLayoutRegistration = {\n name: string;\n mode: TournamentMode;\n extraModes?: readonly TournamentMode[];\n};\n\nconst LAYOUT_FACTORY_SUGGESTION: Record<TournamentMode, string> = {\n 'single-elimination': 'singleEliminationBracketLayout()',\n 'double-elimination': 'doubleEliminationBracketLayout()',\n 'swiss-with-elimination': 'swissBracketLayout()',\n swiss: 'swissBracketLayout()',\n};\n\n/** Returns the first registered layout matching the tournament mode. */\nexport const resolveBracketLayout = <TLayout extends BracketLayoutRegistration>(\n layouts: readonly TLayout[] | undefined,\n mode: TournamentMode,\n): TLayout => {\n const layout = layouts?.find((candidate) => candidate.mode === mode || candidate.extraModes?.includes(mode));\n\n if (!layout) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.LAYOUT_NOT_REGISTERED,\n `No bracket layout registered for mode \"${mode}\". Add ${LAYOUT_FACTORY_SUGGESTION[mode]} to provideBracketConfig({ layouts: [...] }) or to the layouts input.`,\n );\n }\n\n return layout;\n};\n","import { BRACKET_ERROR_CODES } from './bracket-errors';\nimport { BracketRuntimeError } from './bracket-runtime-error';\nimport {\n BracketRoundType,\n COMMON_BRACKET_ROUND_TYPE,\n DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE,\n SINGLE_ELIMINATION_BRACKET_ROUND_TYPE,\n SWISS_BRACKET_ROUND_TYPE,\n} from './core/round';\nimport { TOURNAMENT_MODE } from './core/tournament';\nimport { BracketDataSource, BracketMatchSource, BracketRoundSource } from './integrations/base';\n\nexport type SingleEliminationPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.SINGLE_ELIMINATION;\n /** A power of two, at least 2. */\n participantCount: number;\n /** @default false */\n includeThirdPlace?: boolean;\n};\n\nexport type DoubleEliminationPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.DOUBLE_ELIMINATION;\n /** A power of two, at least 4. */\n participantCount: number;\n /** @default true */\n includeFinal?: boolean;\n /** Ignored when `includeFinal` is false. @default true */\n includeReverseFinal?: boolean;\n /** @default false */\n includeThirdPlace?: boolean;\n};\n\nexport type SwissPlaceholderShape = {\n mode: typeof TOURNAMENT_MODE.SWISS;\n /** An even number, at least 4. Every participant plays each round. */\n participantCount: number;\n /** The scheduled number of rounds, from 1 through 171. */\n roundCount: number;\n};\n\n/** The structure a placeholder bracket is drawn with - see {@link createPlaceholderBracketSource}. */\nexport type PlaceholderBracketShape =\n SingleEliminationPlaceholderShape | DoubleEliminationPlaceholderShape | SwissPlaceholderShape;\n\nconst MIN_PARTICIPANTS: Record<Exclude<PlaceholderBracketShape, SwissPlaceholderShape>['mode'], number> = {\n 'single-elimination': 2,\n 'double-elimination': 4,\n};\n\n// The Swiss grouping uses factorials of the zero-based round index. 171! overflows a number.\nconst MAX_SWISS_ROUNDS = 171;\n\nconst assertPlaceholderShape = (shape: PlaceholderBracketShape) => {\n const { participantCount, mode } = shape;\n\n if (mode === TOURNAMENT_MODE.SWISS) {\n if (!Number.isSafeInteger(participantCount) || participantCount < 4 || participantCount % 2 !== 0) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A Swiss placeholder bracket needs an even participantCount of at least 4, got ${participantCount}.`,\n );\n }\n\n const { roundCount } = shape;\n if (!Number.isInteger(roundCount) || roundCount < 1 || roundCount > MAX_SWISS_ROUNDS) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A Swiss placeholder bracket needs an integer roundCount from 1 through ${MAX_SWISS_ROUNDS}, got ${roundCount}.`,\n );\n }\n\n return;\n }\n\n const min = MIN_PARTICIPANTS[mode];\n const isPowerOfTwo = Number.isInteger(participantCount) && (participantCount & (participantCount - 1)) === 0;\n\n if (participantCount < min || !isPowerOfTwo) {\n throw new BracketRuntimeError(\n BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID,\n `A ${mode} placeholder bracket needs a power-of-two participantCount of at least ${min}, got ${participantCount}.`,\n );\n }\n};\n\nconst halvingCounts = (from: number) => {\n const counts: number[] = [];\n\n for (let n = from; n >= 1; n = n / 2) {\n counts.push(n);\n }\n\n return counts;\n};\n\n/**\n * An empty bracket of the given shape - every match `pending`, both sides `null` - for drawing a loading\n * state with the real layout before the data arrives. Throws `ET3415` for invalid shape counts.\n *\n * @example\n * const source = createPlaceholderBracketSource({ mode: 'single-elimination', participantCount: 16 });\n */\nexport const createPlaceholderBracketSource = (shape: PlaceholderBracketShape): BracketDataSource<null, null> => {\n assertPlaceholderShape(shape);\n\n const rounds: BracketRoundSource<null>[] = [];\n const matches: BracketMatchSource<null>[] = [];\n\n const addRound = (round: { id: string; type: BracketRoundType; matchCount: number }) => {\n const { id, type, matchCount } = round;\n\n rounds.push({ id, type, name: '', data: null });\n\n for (let index = 0; index < matchCount; index++) {\n matches.push({\n id: `${id}-m${index}`,\n roundId: id,\n home: null,\n away: null,\n winner: null,\n status: 'pending',\n data: null,\n });\n }\n };\n\n const { participantCount } = shape;\n\n if (shape.mode === TOURNAMENT_MODE.SWISS) {\n for (let index = 0; index < shape.roundCount; index++) {\n addRound({ id: `r${index}`, type: SWISS_BRACKET_ROUND_TYPE.SWISS, matchCount: participantCount / 2 });\n }\n\n return { mode: shape.mode, rounds, matches };\n }\n\n if (shape.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION) {\n const counts = halvingCounts(participantCount / 2);\n\n counts.forEach((matchCount, index) => {\n const isFinal = index === counts.length - 1;\n\n addRound({\n id: isFinal ? 'final' : `r${index}`,\n type: isFinal\n ? COMMON_BRACKET_ROUND_TYPE.FINAL\n : SINGLE_ELIMINATION_BRACKET_ROUND_TYPE.SINGLE_ELIMINATION_BRACKET,\n matchCount,\n });\n });\n\n if (shape.includeThirdPlace) {\n addRound({ id: 'third-place', type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE, matchCount: 1 });\n }\n\n return { mode: TOURNAMENT_MODE.SINGLE_ELIMINATION, rounds, matches };\n }\n\n const { includeFinal = true, includeReverseFinal = true, includeThirdPlace = false } = shape;\n\n halvingCounts(participantCount / 2).forEach((matchCount, index) =>\n addRound({ id: `ub-r${index}`, type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET, matchCount }),\n );\n\n halvingCounts(participantCount / 4)\n .flatMap((matchCount) => [matchCount, matchCount])\n .forEach((matchCount, index) =>\n addRound({ id: `lb-r${index}`, type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET, matchCount }),\n );\n\n if (includeFinal) {\n addRound({ id: 'final', type: COMMON_BRACKET_ROUND_TYPE.FINAL, matchCount: 1 });\n\n if (includeReverseFinal) {\n addRound({ id: 'reverse-final', type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL, matchCount: 1 });\n }\n }\n\n if (includeThirdPlace) {\n addRound({ id: 'third-place', type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE, matchCount: 1 });\n }\n\n return { mode: TOURNAMENT_MODE.DOUBLE_ELIMINATION, rounds, matches };\n};\n","/** How a group-table prediction scored on one position, once the real order is in. */\nexport const STANDING_PICK_OUTCOME = {\n /** The participant finished on exactly the predicted position. */\n EXACT: 'exact',\n /** They finished on the predicted side of the advancing line, on another position. */\n PARTIAL: 'partial',\n /** They finished on the other side of the advancing line. */\n WRONG: 'wrong',\n} as const;\n\nexport type StandingPickOutcome = (typeof STANDING_PICK_OUTCOME)[keyof typeof STANDING_PICK_OUTCOME];\n\n/**\n * How the participant predicted on `predictedPosition` scored, given where they really finished.\n *\n * `advancingCount` is how many positions advance, so a position is on the advancing side while it is\n * `<= advancingCount`. Ending up on the other side of that line is `WRONG` whatever the distance; the\n * predicted side of it is `EXACT` on the predicted position and `PARTIAL` on any other.\n *\n * `EXACT` is awarded below the line as well. An app whose API stores only the advancing positions holds no\n * prediction for the rest - the order there is whatever its UI happened to draw - and should narrow the\n * result to `PARTIAL`/`WRONG` itself for those positions.\n *\n * Returns the outcome and no points: what an outcome is worth is a rule of the competition, and\n * `POINTS[outcome]` is a lookup the app already owns.\n */\nexport const standingPickOutcome = (options: {\n /** The position the participant was predicted to finish on, 1-based. */\n predictedPosition: number;\n /** The position they really finished on, 1-based. */\n actualPosition: number;\n /** How many positions advance. */\n advancingCount: number;\n}): StandingPickOutcome => {\n const { predictedPosition, actualPosition, advancingCount } = options;\n const predictedToAdvance = predictedPosition <= advancingCount;\n\n if (predictedToAdvance !== actualPosition <= advancingCount) return STANDING_PICK_OUTCOME.WRONG;\n if (predictedPosition === actualPosition) return STANDING_PICK_OUTCOME.EXACT;\n\n return STANDING_PICK_OUTCOME.PARTIAL;\n};\n","/** A prediction already stored for one position of a group table. */\nexport type StandingPick = {\n /** The position it was stored on, 1-based. */\n position: number;\n /** The participant predicted to finish there. */\n participantId: string;\n};\n\n/**\n * The order to show a group table in before anyone moves a row: every stored pick takes the position it was\n * stored on, and the participants without one follow in the order the backend listed them, filling the gaps.\n *\n * A pick the field cannot hold is dropped rather than drawn - a position that is not an integer in\n * `1..participantIds.length`, an id that is not in the field, a second pick for a position or for a\n * participant already placed (the lowest position keeps it). The result is therefore always a permutation\n * of `participantIds`.\n */\nexport const standingPickStartOrder = (options: {\n /** The participants, in the order the backend listed them. */\n participantIds: readonly string[];\n /** What is already stored, in any order. */\n picks: readonly StandingPick[];\n}): string[] => {\n const { participantIds, picks } = options;\n const field = new Set(participantIds);\n const byPosition = new Map<number, string>();\n const placed = new Set<string>();\n\n for (const pick of [...picks].sort((left, right) => left.position - right.position)) {\n const holds =\n Number.isInteger(pick.position) &&\n pick.position >= 1 &&\n pick.position <= participantIds.length &&\n field.has(pick.participantId) &&\n !placed.has(pick.participantId) &&\n !byPosition.has(pick.position);\n\n if (!holds) continue;\n\n byPosition.set(pick.position, pick.participantId);\n placed.add(pick.participantId);\n }\n\n const rest = participantIds.filter((id) => !placed.has(id));\n const order: string[] = [];\n\n for (let position = 1; position <= participantIds.length; position++) {\n const id = byPosition.get(position) ?? rest.shift();\n\n if (id !== undefined) order.push(id);\n }\n\n return order;\n};\n","/**\n * Puts `participantId` on `rank` (1-based) of a standing order by swapping it with whoever stood there. Always\n * returns a new array; it equals `order` when the participant is not in it or `rank` is outside the order.\n */\nexport const swapStandingRank = (options: {\n order: readonly string[];\n rank: number;\n participantId: string;\n}): string[] => {\n const { order, rank, participantId } = options;\n const next = [...order];\n const to = rank - 1;\n const from = next.indexOf(participantId);\n\n if (from < 0 || !Number.isInteger(rank) || to < 0 || to >= next.length) return next;\n\n [next[from], next[to]] = [next[to] as string, participantId];\n\n return next;\n};\n"],"mappings":"AAAA,MAAa,sBAAsB;CAEjC,cAAc;CAEd,kBAAkB;CAElB,iBAAiB;CAEjB,iBAAiB;CAEjB,wBAAwB;CAExB,wBAAwB;CAExB,cAAc;CAEd,uBAAuB;CAEvB,mBAAmB;CAEnB,kBAAkB;CAElB,oBAAoB;CAEpB,0BAA0B;CAE1B,uBAAuB;CAEvB,qBAAqB;CAErB,2BAA2B;AACnB;AC3BV,IAAa,sBAAb,cAAyC,MAAK;CAG5C,YAAY,MAAc,SAAe;EACvC,MAAM,KAAK,KAAI,IAAK,SAAS;EAC7B,KAAK,OAAO;EACZ,KAAK,OAAO;CACd;AACD;ACVD,IAAa,aAAb,cAA8C,IAAiB;CAC7D,cAAA;EACE,MAAK;CACP;CAEA,WAAW,KAAS;EAClB,MAAM,QAAQ,MAAM,IAAI,GAAG;EAE3B,IAAI,UAAU,QACZ,MAAM,IAAI,oBACR,oBAAoB,oBACpB,iBAAiB,IAAG,0BAA2B;EAInD,OAAO;CACT;CAEA,QAAK;EACH,OAAO,KAAK,OAAM,CAAE,CAAC,KAAI,CAAE,CAAC;CAC9B;CAE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