@ethlete/components 1.0.0-next.104 → 1.0.0-next.106

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.
Files changed (28) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/design/bracket.ts +2 -2
  3. package/design/dialog.ts +5 -0
  4. package/design/sdk/components/anchored-dialog/anchored-dialog.ts +4 -2
  5. package/design/sdk/components/bracket/bracket.ts +2 -2
  6. package/design/sdk/components/dialog/dialog.ts +12 -38
  7. package/design/sdk/ready.json +48 -14
  8. package/design/table.ts +7 -3
  9. package/fesm2022/ethlete-components-bracket.mjs +3498 -0
  10. package/fesm2022/ethlete-components-bracket.mjs.map +1 -0
  11. package/fesm2022/ethlete-components.mjs +40 -16
  12. package/fesm2022/ethlete-components.mjs.map +1 -1
  13. package/generators/generators.json +5 -0
  14. package/generators/migrate-bracket-entry-point/bracket-entry-point.js +27 -0
  15. package/generators/migrate-bracket-entry-point/migration.js +60 -0
  16. package/generators/migrate-bracket-entry-point/schema.json +26 -0
  17. package/generators/migrate-overlay-and-column-api/migration.js +6 -8
  18. package/generators/migrate-overlay-and-column-api/overlay-result.js +47 -0
  19. package/migrations.json +9 -0
  20. package/package.json +9 -6
  21. package/src/lib/bracket/bracket.component.css +3 -1
  22. package/src/lib/button/button.component.css +1 -0
  23. package/src/lib/button/window-control-button.component.css +2 -2
  24. package/src/lib/overlay/overlay-main-styles.component.css +6 -0
  25. package/src/lib/scrollable/headless/scrollable-buttons.component.css +3 -1
  26. package/src/lib/scrollable/headless/scrollable-masks.component.css +2 -0
  27. package/types/ethlete-components-bracket.d.ts +1177 -0
  28. package/types/ethlete-components.d.ts +21 -12
@@ -0,0 +1,3498 @@
1
+ const BRACKET_ERROR_CODES = {
2
+ SOURCE_EMPTY: 3401,
3
+ MODE_UNSUPPORTED: 3402,
4
+ DUPLICATE_ROUND: 3403,
5
+ DUPLICATE_MATCH: 3404,
6
+ ROUND_RELATION_INVALID: 3405,
7
+ MATCH_RELATION_INVALID: 3406,
8
+ GRID_INVALID: 3407,
9
+ SWISS_GROUPING_FAILED: 3408,
10
+ SWISS_GROUP_EMPTY: 3409,
11
+ WINNER_NOT_FOUND: 3410,
12
+ DATA_LOOKUP_FAILED: 3411,
13
+ MISSING_MATCH_NORMALIZER: 3412,
14
+ LAYOUT_NOT_REGISTERED: 3413,
15
+ CARD_NOT_REGISTERED: 3414,
16
+ PLACEHOLDER_SHAPE_INVALID: 3415
17
+ };
18
+ var BracketRuntimeError = class extends Error {
19
+ constructor(code, message) {
20
+ super(`ET${code}: ${message}`);
21
+ this.name = "BracketRuntimeError";
22
+ this.code = code;
23
+ }
24
+ };
25
+ var BracketMap = class extends Map {
26
+ constructor() {
27
+ super();
28
+ }
29
+ getOrThrow(key) {
30
+ const value = super.get(key);
31
+ if (value === void 0) throw new BracketRuntimeError(BRACKET_ERROR_CODES.DATA_LOOKUP_FAILED, `Value for key ${key} not found in bracket map`);
32
+ return value;
33
+ }
34
+ first() {
35
+ return this.values().next().value;
36
+ }
37
+ last() {
38
+ const values = Array.from(this.values());
39
+ return values.length > 0 ? values[values.length - 1] : void 0;
40
+ }
41
+ };
42
+ const BRACKET_DATA_LAYOUT = {
43
+ LEFT_TO_RIGHT: "left-to-right",
44
+ MIRRORED: "mirrored"
45
+ };
46
+ const TOURNAMENT_MODE = {
47
+ SINGLE_ELIMINATION: "single-elimination",
48
+ DOUBLE_ELIMINATION: "double-elimination",
49
+ SWISS_WITH_ELIMINATION: "swiss-with-elimination"
50
+ };
51
+ const SWISS_ADVANCE_WINS = 3;
52
+ const SWISS_ELIMINATE_LOSSES = 3;
53
+ const BRACKET_ROUND_MIRROR_TYPE = {
54
+ LEFT: "left",
55
+ RIGHT: "right"
56
+ };
57
+ const COMMON_BRACKET_ROUND_TYPE = {
58
+ THIRD_PLACE: "third-place",
59
+ FINAL: "final"
60
+ };
61
+ const SINGLE_ELIMINATION_BRACKET_ROUND_TYPE = { SINGLE_ELIMINATION_BRACKET: "single-elimination-bracket" };
62
+ const DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE = {
63
+ UPPER_BRACKET: "upper-bracket",
64
+ LOWER_BRACKET: "lower-bracket",
65
+ REVERSE_FINAL: "reverse-final"
66
+ };
67
+ const SWISS_BRACKET_ROUND_TYPE = { SWISS: "swiss" };
68
+ const GROUP_BRACKET_ROUND_TYPE = { GROUP: "group" };
69
+ const TERMINAL_ROUND_SORT_PRIORITY = {
70
+ final: 1,
71
+ "reverse-final": 2,
72
+ "third-place": 3
73
+ };
74
+ const createRoundsMapBase = (source, options) => {
75
+ const map = new BracketMap();
76
+ const shouldSplitRoundsInTwo = options.layout === BRACKET_DATA_LAYOUT.MIRRORED;
77
+ const isDoubleElimination = source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION;
78
+ let currentUpperBracketIndex = 0;
79
+ let currentLowerBracketIndex = 0;
80
+ const foldClosed = {
81
+ upper: false,
82
+ lower: false
83
+ };
84
+ const splitRoundsRest = [];
85
+ const orderedRounds = [...source.rounds].sort((a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0));
86
+ for (const [roundIndex, round] of orderedRounds.entries()) {
87
+ const isUpperBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET;
88
+ const isLowerBracket = round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET;
89
+ const isCommonDoubleEliminationRound = !isUpperBracket && !isLowerBracket && isDoubleElimination;
90
+ const matches = source.matches.filter((m) => m.roundId === round.id);
91
+ const roundId = round.id;
92
+ const foldSide = isLowerBracket || isCommonDoubleEliminationRound ? "lower" : "upper";
93
+ const canHalveRound = matches.length >= 2 && matches.length % 2 === 0;
94
+ const shouldSplitRound = shouldSplitRoundsInTwo && canHalveRound && !foldClosed[foldSide];
95
+ if (!canHalveRound) foldClosed[foldSide] = true;
96
+ const isFirstRound = roundIndex === 0;
97
+ const isLastRound = roundIndex === orderedRounds.length - 1;
98
+ const isFirstOfType = orderedRounds.findIndex((r) => r.type === round.type) === roundIndex;
99
+ const isLastOfType = orderedRounds.slice().reverse().findIndex((r) => r.type === round.type) === orderedRounds.length - roundIndex - 1;
100
+ const depth = isLowerBracket || isCommonDoubleEliminationRound ? currentLowerBracketIndex : currentUpperBracketIndex;
101
+ if (shouldSplitRound) {
102
+ const firstHalfRoundId = `${roundId}--half-1`;
103
+ const secondHalfRoundId = `${roundId}--half-2`;
104
+ const firstHalfMatchesMaxIndex = matches.length / 2 - 1;
105
+ const halfBase = {
106
+ type: round.type,
107
+ logicalIndex: depth,
108
+ data: round.data,
109
+ position: depth + 1,
110
+ name: round.name,
111
+ matchCount: matches.length / 2,
112
+ isFirstRound,
113
+ isLastRound,
114
+ isFirstOfType,
115
+ isLastOfType
116
+ };
117
+ const bracketRoundFirstHalf = {
118
+ ...halfBase,
119
+ id: firstHalfRoundId,
120
+ shortId: `${roundIndex}-left`,
121
+ matchIds: matches.slice(0, firstHalfMatchesMaxIndex + 1).map((m) => m.id),
122
+ mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.LEFT
123
+ };
124
+ const bracketRoundSecondHalf = {
125
+ ...halfBase,
126
+ id: secondHalfRoundId,
127
+ shortId: `${roundIndex}-right`,
128
+ matchIds: matches.slice(firstHalfMatchesMaxIndex + 1).map((m) => m.id),
129
+ mirrorRoundType: BRACKET_ROUND_MIRROR_TYPE.RIGHT
130
+ };
131
+ map.set(firstHalfRoundId, bracketRoundFirstHalf);
132
+ splitRoundsRest.unshift(bracketRoundSecondHalf);
133
+ } else {
134
+ const bracketRound = {
135
+ type: round.type,
136
+ id: roundId,
137
+ shortId: `${roundIndex}`,
138
+ logicalIndex: depth,
139
+ data: round.data,
140
+ position: depth + 1,
141
+ name: round.name,
142
+ matchCount: matches.length,
143
+ matchIds: matches.map((m) => m.id),
144
+ mirrorRoundType: null,
145
+ isFirstRound,
146
+ isLastRound,
147
+ isFirstOfType,
148
+ isLastOfType
149
+ };
150
+ map.set(roundId, bracketRound);
151
+ }
152
+ if (isLowerBracket || isCommonDoubleEliminationRound) currentLowerBracketIndex++;
153
+ else currentUpperBracketIndex++;
154
+ }
155
+ if (splitRoundsRest.length) {
156
+ if (!map.last()) throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, "Last round not found");
157
+ for (const splitRound of splitRoundsRest) map.set(splitRound.id, splitRound);
158
+ }
159
+ return map;
160
+ };
161
+ const thirdPlaceFeederRoundId = (source) => {
162
+ if (!source.rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)) return null;
163
+ const chain = source.rounds.filter((round) => round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE);
164
+ const finalIndex = chain.findIndex((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL);
165
+ return finalIndex > 0 ? chain[finalIndex - 1]?.id ?? null : null;
166
+ };
167
+ const createNewMatchParticipantBase = (source, participantId, match, rounds, matchRoundId, participants, sourceMatchesById) => {
168
+ if (!participantId) return null;
169
+ const findSourceMatch = (matchId) => matchId === void 0 ? void 0 : sourceMatchesById ? sourceMatchesById.get(matchId) : source.matches.find((m) => m.id === matchId);
170
+ const participantBase = participants.getOrThrow(participantId);
171
+ const roundBase = rounds.getOrThrow(matchRoundId);
172
+ const matchIndex = participantBase.matchIds.indexOf(match.id);
173
+ if (matchIndex === -1) throw new BracketRuntimeError(BRACKET_ERROR_CODES.MATCH_RELATION_INVALID, `Match with id ${match.id} not found in participant with id ${participantId}`);
174
+ const participantSide = match.home === participantId ? "home" : "away";
175
+ const isWinner = match.winner === participantSide;
176
+ const isLooser = match.winner && match.winner !== participantSide;
177
+ const isTie = match.status === "completed" && !match.winner;
178
+ let winsTilNow = isWinner ? 1 : 0;
179
+ let lossesTilNow = isLooser ? 1 : 0;
180
+ let tiesTilNow = isTie ? 1 : 0;
181
+ for (let i = 0; i < matchIndex; i++) {
182
+ const previousMatchId = participantBase.matchIds[i];
183
+ const previousMatch = findSourceMatch(previousMatchId);
184
+ const myPreviousMatchSide = previousMatch?.home === participantId ? "home" : previousMatch?.away === participantId ? "away" : null;
185
+ if (!previousMatch || !myPreviousMatchSide) continue;
186
+ const previousIsWinner = previousMatch.winner === myPreviousMatchSide;
187
+ const previousIsLooser = previousMatch.winner && previousMatch.winner !== myPreviousMatchSide;
188
+ const previousIsTie = previousMatch.status === "completed" && !previousMatch.winner;
189
+ if (previousIsWinner) winsTilNow++;
190
+ else if (previousIsLooser) lossesTilNow++;
191
+ else if (previousIsTie) tiesTilNow++;
192
+ }
193
+ const hasElimination = source.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION || source.mode === TOURNAMENT_MODE.DOUBLE_ELIMINATION || source.mode === TOURNAMENT_MODE.SWISS_WITH_ELIMINATION;
194
+ let isEliminated = false;
195
+ let isEliminationMatch = false;
196
+ if (hasElimination) switch (source.mode) {
197
+ case TOURNAMENT_MODE.SINGLE_ELIMINATION:
198
+ isEliminationMatch = match.roundId !== thirdPlaceFeederRoundId(source);
199
+ isEliminated = (isEliminationMatch && isLooser) ?? false;
200
+ break;
201
+ case TOURNAMENT_MODE.DOUBLE_ELIMINATION:
202
+ isEliminationMatch = roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET || roundBase.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL || roundBase.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE;
203
+ if (roundBase.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {
204
+ if (!source.rounds.some((r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)) {
205
+ isEliminationMatch = true;
206
+ isEliminated = isLooser ?? false;
207
+ break;
208
+ }
209
+ isEliminationMatch = participantBase.matchIds.some((matchId) => {
210
+ const playedMatch = findSourceMatch(matchId);
211
+ return !!playedMatch && source.rounds.find((round) => round.id === playedMatch.roundId)?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET;
212
+ });
213
+ }
214
+ isEliminated = (isEliminationMatch && isLooser) ?? false;
215
+ break;
216
+ case TOURNAMENT_MODE.SWISS_WITH_ELIMINATION:
217
+ isEliminationMatch = lossesTilNow - (isLooser ? 1 : 0) >= 2;
218
+ isEliminated = (isEliminationMatch && isLooser) ?? false;
219
+ }
220
+ return {
221
+ ...participantBase,
222
+ isEliminated,
223
+ isEliminationMatch,
224
+ lossCount: lossesTilNow,
225
+ tieCount: tiesTilNow,
226
+ winCount: winsTilNow,
227
+ result: isWinner ? "win" : isLooser ? "loss" : isTie ? "tie" : null,
228
+ side: participantSide
229
+ };
230
+ };
231
+ const createMatchesMapBase = (source, rounds, participants) => {
232
+ const map = new BracketMap();
233
+ const sourceMatchesById = new Map(source.matches.map((match) => [match.id, match]));
234
+ for (const match of source.matches) {
235
+ const genericRound = rounds.get(match.roundId);
236
+ const splitRound = rounds.get(`${match.roundId}--half-1`);
237
+ const splitRound2 = rounds.get(`${match.roundId}--half-2`);
238
+ const genericRoundMatchIndex = genericRound?.matchIds.indexOf(match.id) ?? -1;
239
+ const splitRoundMatchIndex = splitRound?.matchIds.indexOf(match.id) ?? -1;
240
+ const splitRound2MatchIndex = splitRound2?.matchIds.indexOf(match.id) ?? -1;
241
+ const roundToUse = genericRoundMatchIndex !== -1 ? genericRound : splitRoundMatchIndex !== -1 ? splitRound : splitRound2MatchIndex !== -1 ? splitRound2 : null;
242
+ if (!roundToUse) throw new BracketRuntimeError(BRACKET_ERROR_CODES.MATCH_RELATION_INVALID, `Match "${match.id}" names round "${match.roundId}", which is not in source.rounds (known: ${source.rounds.map((round) => round.id).join(", ")})`);
243
+ const indexInRound = genericRoundMatchIndex !== -1 ? genericRoundMatchIndex : splitRoundMatchIndex !== -1 ? splitRoundMatchIndex : splitRound2MatchIndex !== -1 ? splitRound2MatchIndex : -1;
244
+ if (indexInRound === -1) throw new BracketRuntimeError(BRACKET_ERROR_CODES.MATCH_RELATION_INVALID, `Match with id ${match.id} not found in round with id ${roundToUse.id}`);
245
+ const home = createNewMatchParticipantBase(source, match.home, match, rounds, roundToUse.id, participants, sourceMatchesById);
246
+ const away = createNewMatchParticipantBase(source, match.away, match, rounds, roundToUse.id, participants, sourceMatchesById);
247
+ const winner = match.winner === "home" ? home : match.winner === "away" ? away : null;
248
+ const matchBase = {
249
+ home,
250
+ away,
251
+ data: match.data,
252
+ shortId: `${roundToUse.shortId}-${indexInRound}`,
253
+ id: match.id,
254
+ indexInRound,
255
+ position: indexInRound + 1,
256
+ roundId: roundToUse?.id,
257
+ status: match.status,
258
+ homeSource: match.homeSource ?? null,
259
+ awaySource: match.awaySource ?? null,
260
+ winner,
261
+ winnerSide: match.winner
262
+ };
263
+ map.set(matchBase.id, matchBase);
264
+ }
265
+ return map;
266
+ };
267
+ const createParticipantsMapBase = (source) => {
268
+ const map = new BracketMap();
269
+ const participantIds = source.matches.map((m) => [m.home, m.away]).flat().filter((p) => !!p);
270
+ const matchIdsByParticipant = /* @__PURE__ */ new Map();
271
+ for (const match of source.matches) for (const participantId of /* @__PURE__ */ new Set([match.home, match.away])) {
272
+ if (!participantId) continue;
273
+ const matchIds = matchIdsByParticipant.get(participantId) ?? [];
274
+ matchIds.push(match.id);
275
+ matchIdsByParticipant.set(participantId, matchIds);
276
+ }
277
+ for (const [index, participantId] of participantIds.entries()) {
278
+ const participantBase = {
279
+ id: participantId,
280
+ shortId: `p${index}`,
281
+ matchIds: matchIdsByParticipant.get(participantId) ?? []
282
+ };
283
+ map.set(participantId, participantBase);
284
+ }
285
+ return map;
286
+ };
287
+ const sortSourceMatchesByRoundOrder = (source) => {
288
+ const orderedRoundIds = [...source.rounds].sort((a, b) => (TERMINAL_ROUND_SORT_PRIORITY[a.type] ?? 0) - (TERMINAL_ROUND_SORT_PRIORITY[b.type] ?? 0)).map((r) => r.id);
289
+ const roundIndexMap = new Map(orderedRoundIds.map((id, i) => [id, i]));
290
+ const sortedMatches = [...source.matches].sort((a, b) => (roundIndexMap.get(a.roundId) ?? 0) - (roundIndexMap.get(b.roundId) ?? 0));
291
+ return {
292
+ ...source,
293
+ matches: sortedMatches
294
+ };
295
+ };
296
+ const assertUniqueIds = (options) => {
297
+ const seen = /* @__PURE__ */ new Set();
298
+ for (const id of options.ids) {
299
+ if (seen.has(id)) throw new BracketRuntimeError(options.code, `${options.kind} with id ${id} exists more than once in the source.`);
300
+ seen.add(id);
301
+ }
302
+ };
303
+ const createBracketBase = (source, options) => {
304
+ assertUniqueIds({
305
+ ids: source.rounds.map((round) => round.id),
306
+ code: BRACKET_ERROR_CODES.DUPLICATE_ROUND,
307
+ kind: "Round"
308
+ });
309
+ assertUniqueIds({
310
+ ids: source.matches.map((match) => match.id),
311
+ code: BRACKET_ERROR_CODES.DUPLICATE_MATCH,
312
+ kind: "Match"
313
+ });
314
+ const normalizedSource = sortSourceMatchesByRoundOrder(source);
315
+ const participants = createParticipantsMapBase(normalizedSource);
316
+ const rounds = createRoundsMapBase(normalizedSource, options);
317
+ return {
318
+ matches: createMatchesMapBase(normalizedSource, rounds, participants),
319
+ rounds,
320
+ participants,
321
+ mode: source.mode
322
+ };
323
+ };
324
+ const path = (d, options) => {
325
+ const commands = d.replace(/\s+/g, " ").trim();
326
+ return {
327
+ id: options.id,
328
+ d: commands,
329
+ cssPath: `path("${commands}")`,
330
+ cssClass: options.className,
331
+ strokeWidth: options.width,
332
+ dashArray: options.dashArray,
333
+ dashOffset: options.dashOffset,
334
+ stroke: options.stroke ?? "currentColor"
335
+ };
336
+ };
337
+ const curvePath = (from, to, direction, options) => {
338
+ const inverted = options.inverted ?? false;
339
+ const fromInline = inverted ? from.inline.start : from.inline.end;
340
+ const toInline = inverted ? to.inline.end : to.inline.start;
341
+ const fromBlock = from.block.center;
342
+ const toBlock = to.block.center;
343
+ const requestedCurve = options.lineStartingCurveAmount + options.lineEndingCurveAmount;
344
+ const totalInline = Math.abs(toInline - fromInline);
345
+ const room = Math.min(Math.abs(toBlock - fromBlock), totalInline);
346
+ const curveScale = requestedCurve > room ? room / requestedCurve : 1;
347
+ const startCurve = options.lineStartingCurveAmount * curveScale;
348
+ const endCurve = options.lineEndingCurveAmount * curveScale;
349
+ const straightTotal = totalInline - startCurve - endCurve;
350
+ const turnOffset = options.turnOffset ?? null;
351
+ const leadingStraight = turnOffset === null ? straightTotal / 2 : Math.max(0, Math.min(turnOffset - startCurve, straightTotal));
352
+ const trailingStraight = straightTotal - leadingStraight;
353
+ const straightEnd = inverted ? fromInline - leadingStraight : fromInline + leadingStraight;
354
+ const straightStart = inverted ? toInline + trailingStraight : toInline - trailingStraight;
355
+ const firstCurveEndX = inverted ? straightEnd - startCurve : straightEnd + startCurve;
356
+ const firstCurveEndY = direction === "down" ? fromBlock + startCurve : fromBlock - startCurve;
357
+ const secondCurveStartY = direction === "down" ? toBlock - endCurve : toBlock + endCurve;
358
+ const secondCurveEndX = straightStart;
359
+ const secondCurveEndY = toBlock;
360
+ const secondCurveBezierX = inverted ? straightStart + endCurve : straightStart - endCurve;
361
+ const d = [
362
+ `M ${fromInline} ${fromBlock}`,
363
+ `H ${straightEnd}`,
364
+ `Q ${firstCurveEndX} ${fromBlock}, ${firstCurveEndX} ${firstCurveEndY}`,
365
+ `V ${secondCurveStartY}`,
366
+ `Q ${secondCurveBezierX} ${toBlock}, ${secondCurveEndX} ${secondCurveEndY}`,
367
+ `H ${toInline}`
368
+ ].join(" ");
369
+ return path(d, options.path);
370
+ };
371
+ const bracketGridNaturalWidth = (grid) => grid.raw.grid.dimensions.width;
372
+ const BRACKET_FINAL_ALIGNMENT = {
373
+ UPPER: "upper",
374
+ CENTER: "center"
375
+ };
376
+ const createBracketElementPart = (config) => ({ dimensions: {
377
+ width: 0,
378
+ height: config.elementPartHeight,
379
+ top: 0,
380
+ left: 0
381
+ } });
382
+ const createBracketElement = (config) => {
383
+ const { type, area, elementHeight, partHeights } = config;
384
+ const parts = [];
385
+ const newElementBase = {
386
+ dimensions: {
387
+ width: 0,
388
+ height: elementHeight,
389
+ top: 0,
390
+ left: 0
391
+ },
392
+ containerDimensions: {
393
+ width: 0,
394
+ height: 0,
395
+ top: 0,
396
+ left: 0
397
+ },
398
+ parts,
399
+ area
400
+ };
401
+ const newElement = (() => {
402
+ switch (type) {
403
+ case "header": return {
404
+ ...newElementBase,
405
+ type,
406
+ component: config.component,
407
+ round: config.round,
408
+ roundSwissGroup: config.roundSwissGroup
409
+ };
410
+ case "match": return {
411
+ ...newElementBase,
412
+ type,
413
+ component: config.component,
414
+ match: config.match,
415
+ round: config.round,
416
+ roundSwissGroup: config.roundSwissGroup
417
+ };
418
+ case "matchGap":
419
+ case "roundHeaderGap":
420
+ case "roundGap":
421
+ case "colGap": return {
422
+ ...newElementBase,
423
+ type
424
+ };
425
+ case "continue": return {
426
+ ...newElementBase,
427
+ type,
428
+ component: config.component,
429
+ matches: config.matches
430
+ };
431
+ default: throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, `Unknown element type: ${type}`);
432
+ }
433
+ })();
434
+ for (const partHeight of partHeights) parts.push(createBracketElementPart({ elementPartHeight: partHeight }));
435
+ return newElement;
436
+ };
437
+ const finalizeBracketGrid = (grid) => {
438
+ const finalizedColumns = [];
439
+ const finalizedElementMap = new BracketMap();
440
+ const ignoredSections = [];
441
+ for (const [masterColumnIndex, masterColumn] of grid.grid.masterColumns.entries()) for (const [sectionIndex, section] of masterColumn.sections.entries()) {
442
+ if (ignoredSections.some((s) => s.masterColumnIndex === masterColumnIndex && s.sectionIndex === sectionIndex)) continue;
443
+ const elements = [];
444
+ const firstSubColumn = section.subColumns[0];
445
+ const lastSubColumn = section.subColumns[section.subColumns.length - 1];
446
+ if (!firstSubColumn || !lastSubColumn) continue;
447
+ let sectionWidth = section.dimensions.width;
448
+ for (const element of firstSubColumn.elements) if (element.type === "header") elements.push({
449
+ type: "header",
450
+ dimensions: element.dimensions,
451
+ component: element.component,
452
+ round: element.round,
453
+ roundSwissGroup: element.roundSwissGroup
454
+ });
455
+ else if (element.type === "match") {
456
+ const matchEl = {
457
+ type: "match",
458
+ dimensions: element.dimensions,
459
+ component: element.component,
460
+ match: element.match,
461
+ round: element.round,
462
+ classes: [element.match.home?.shortId, element.match.away?.shortId].filter((v) => !!v).join(" "),
463
+ roundSwissGroup: element.roundSwissGroup
464
+ };
465
+ elements.push(matchEl);
466
+ finalizedElementMap.set(element.match.id, matchEl);
467
+ } else if (element.type === "continue") elements.push({
468
+ type: "continue",
469
+ dimensions: element.dimensions,
470
+ component: element.component,
471
+ matches: element.matches
472
+ });
473
+ if (!lastSubColumn.span.isEnd) for (let index = masterColumnIndex + 1; index < grid.grid.masterColumns.length; index++) {
474
+ const nextSection = grid.grid.masterColumns[index]?.sections[sectionIndex];
475
+ if (!nextSection) break;
476
+ sectionWidth += nextSection.dimensions.width;
477
+ ignoredSections.push({
478
+ masterColumnIndex: index,
479
+ sectionIndex
480
+ });
481
+ if (nextSection.subColumns.some((sc) => sc.span.isEnd)) break;
482
+ }
483
+ if (!elements.length) continue;
484
+ finalizedColumns.push({
485
+ dimensions: {
486
+ ...section.dimensions,
487
+ width: sectionWidth
488
+ },
489
+ elements
490
+ });
491
+ }
492
+ return {
493
+ columns: finalizedColumns,
494
+ elementMap: finalizedElementMap
495
+ };
496
+ };
497
+ const createBracketGrid = (config) => {
498
+ const masterColumns = [];
499
+ const contentWidths = /* @__PURE__ */ new WeakMap();
500
+ const newGrid = {
501
+ dimensions: {
502
+ width: 0,
503
+ height: 0,
504
+ top: 0,
505
+ left: 0
506
+ },
507
+ masterColumns
508
+ };
509
+ const pushMasterColumn = (...newMasterColumns) => {
510
+ masterColumns.push(...newMasterColumns);
511
+ };
512
+ const calculateDimensions = () => {
513
+ let currentMasterColumnLeft = 0;
514
+ let maxGridHeight = 0;
515
+ const masterCols = newGrid.masterColumns;
516
+ for (const masterColumn of masterCols) {
517
+ const { padding } = masterColumn;
518
+ masterColumn.dimensions.left = currentMasterColumnLeft;
519
+ masterColumn.dimensions.top = 0;
520
+ const contentWidth = contentWidths.get(masterColumn) ?? masterColumn.dimensions.width;
521
+ contentWidths.set(masterColumn, contentWidth);
522
+ masterColumn.dimensions.width = contentWidth + padding.left + padding.right;
523
+ const sections = masterColumn.sections;
524
+ let runningTop = 0;
525
+ const firstSectionIsHeader = (sections[0]?.subColumns[0]?.elements[0])?.type === "header";
526
+ for (const [secIdx, section] of sections.entries()) {
527
+ const sectionPadding = section.padding ?? padding;
528
+ let sectionPaddingTop;
529
+ if (secIdx === 0) sectionPaddingTop = firstSectionIsHeader ? 0 : sectionPadding.top;
530
+ else sectionPaddingTop = sectionPadding.top;
531
+ section.dimensions.width = masterColumn.dimensions.width;
532
+ section.dimensions.left = masterColumn.dimensions.left;
533
+ section.dimensions.top = runningTop;
534
+ runningTop += sectionPaddingTop;
535
+ const sectionContentWidth = masterColumn.dimensions.width - sectionPadding.left - sectionPadding.right;
536
+ const subColumns = section.subColumns;
537
+ const subColumnWidth = sectionContentWidth / subColumns.length;
538
+ let currentSubColumnLeft = masterColumn.dimensions.left + sectionPadding.left;
539
+ let maxSectionHeight = 0;
540
+ for (const subColumn of subColumns) {
541
+ subColumn.dimensions.width = subColumnWidth;
542
+ subColumn.dimensions.left = currentSubColumnLeft;
543
+ subColumn.dimensions.top = section.dimensions.top + sectionPaddingTop;
544
+ let totalSubColumnHeight = 0;
545
+ const elements = subColumn.elements;
546
+ for (const element of elements) {
547
+ let totalElementHeight = 0;
548
+ const parts = element.parts;
549
+ for (const part of parts) {
550
+ part.dimensions.width = subColumnWidth;
551
+ part.dimensions.left = currentSubColumnLeft;
552
+ part.dimensions.top = subColumn.dimensions.top + totalSubColumnHeight + totalElementHeight;
553
+ totalElementHeight += part.dimensions.height;
554
+ }
555
+ element.containerDimensions.height = totalElementHeight;
556
+ element.containerDimensions.width = subColumnWidth;
557
+ element.containerDimensions.left = currentSubColumnLeft;
558
+ element.containerDimensions.top = subColumn.dimensions.top + totalSubColumnHeight;
559
+ element.dimensions.width = subColumnWidth;
560
+ element.dimensions.left = currentSubColumnLeft;
561
+ element.dimensions.top = element.containerDimensions.top + (totalElementHeight - element.dimensions.height) * .5;
562
+ totalSubColumnHeight += totalElementHeight;
563
+ }
564
+ subColumn.dimensions.height = totalSubColumnHeight;
565
+ if (totalSubColumnHeight > maxSectionHeight) maxSectionHeight = totalSubColumnHeight;
566
+ currentSubColumnLeft += subColumnWidth;
567
+ }
568
+ section.dimensions.height = Math.max(0, sectionPaddingTop + maxSectionHeight + sectionPadding.bottom);
569
+ runningTop += maxSectionHeight + sectionPadding.bottom;
570
+ }
571
+ masterColumn.dimensions.height = runningTop;
572
+ if (masterColumn.dimensions.height > maxGridHeight) maxGridHeight = masterColumn.dimensions.height;
573
+ currentMasterColumnLeft += masterColumn.dimensions.width;
574
+ }
575
+ newGrid.dimensions.width = currentMasterColumnLeft;
576
+ newGrid.dimensions.height = maxGridHeight;
577
+ calculateSpanningElementDimensions();
578
+ };
579
+ const calculateSpanningElementDimensions = () => {
580
+ const spanDimensions = /* @__PURE__ */ new Map();
581
+ const masterCols = newGrid.masterColumns;
582
+ for (const [mcIdx, masterColumn] of masterCols.entries()) {
583
+ const sections = masterColumn.sections;
584
+ for (const [secIdx, section] of sections.entries()) {
585
+ const subColumns = section.subColumns;
586
+ for (const [scIdx, subColumn] of subColumns.entries()) {
587
+ const elements = subColumn.elements;
588
+ for (const element of elements) {
589
+ if (!element.span) continue;
590
+ const span = element.span;
591
+ const isStartPosition = mcIdx === span.masterColumnStart && secIdx === span.sectionStart && scIdx === span.subColumnStart;
592
+ const spanKey = `${span.masterColumnStart}-${span.masterColumnEnd}-${span.sectionStart}-${span.sectionEnd}-${span.subColumnStart}-${span.subColumnEnd}`;
593
+ if (isStartPosition && !spanDimensions.has(spanKey)) {
594
+ const { left: spanStartLeft, width: totalSpannedWidth } = calculateSpanExtent(span, masterCols);
595
+ const width = config.spanElementWidth;
596
+ const alignFactor = (element.type === "header" || element.type === "match" ? element.round : null)?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET ? 0 : .5;
597
+ spanDimensions.set(spanKey, {
598
+ width,
599
+ left: spanStartLeft + (totalSpannedWidth - width) * alignFactor
600
+ });
601
+ }
602
+ const storedDimensions = spanDimensions.get(spanKey);
603
+ if (storedDimensions) {
604
+ element.dimensions.width = storedDimensions.width;
605
+ element.dimensions.left = storedDimensions.left;
606
+ }
607
+ }
608
+ }
609
+ }
610
+ }
611
+ };
612
+ const calculateSpanExtent = (span, masterColumns) => {
613
+ const start = masterColumns[span.masterColumnStart]?.sections[span.sectionStart]?.subColumns[span.subColumnStart];
614
+ const end = masterColumns[span.masterColumnEnd]?.sections[span.sectionEnd]?.subColumns[span.subColumnEnd];
615
+ if (!start || !end) return {
616
+ left: start?.dimensions.left ?? 0,
617
+ width: 0
618
+ };
619
+ return {
620
+ left: start.dimensions.left,
621
+ width: end.dimensions.left + end.dimensions.width - start.dimensions.left
622
+ };
623
+ };
624
+ const setupElementSpans = () => {
625
+ const masterCols = newGrid.masterColumns;
626
+ for (const [mcIdx, masterColumn] of masterCols.entries()) {
627
+ const sections = masterColumn.sections;
628
+ for (const [secIdx, section] of sections.entries()) {
629
+ const subColumns = section.subColumns;
630
+ for (const [scIdx, subColumn] of subColumns.entries()) {
631
+ if (subColumn.span.isStart && subColumn.span.isEnd) continue;
632
+ let spanStart = {
633
+ masterColumnIndex: mcIdx,
634
+ sectionIndex: secIdx,
635
+ subColumnIndex: scIdx
636
+ };
637
+ if (!subColumn.span.isStart) outer: for (let m = mcIdx; m >= 0; m--) {
638
+ const mc = masterCols[m];
639
+ if (!mc) continue;
640
+ const sec = mc.sections[secIdx];
641
+ if (!sec) continue;
642
+ const end = m === mcIdx ? scIdx : sec.subColumns.length - 1;
643
+ for (let s = end; s >= 0; s--) if (sec.subColumns[s]?.span.isStart) {
644
+ spanStart = {
645
+ masterColumnIndex: m,
646
+ sectionIndex: secIdx,
647
+ subColumnIndex: s
648
+ };
649
+ break outer;
650
+ }
651
+ }
652
+ let spanEnd = {
653
+ masterColumnIndex: mcIdx,
654
+ sectionIndex: secIdx,
655
+ subColumnIndex: scIdx
656
+ };
657
+ if (!subColumn.span.isEnd) outer: for (let m = mcIdx; m < masterCols.length; m++) {
658
+ const mc = masterCols[m];
659
+ if (!mc) continue;
660
+ const sec = mc.sections[secIdx];
661
+ if (!sec) continue;
662
+ const start = m === mcIdx ? scIdx : 0;
663
+ for (let s = start; s < sec.subColumns.length; s++) if (sec.subColumns[s]?.span.isEnd) {
664
+ spanEnd = {
665
+ masterColumnIndex: m,
666
+ sectionIndex: secIdx,
667
+ subColumnIndex: s
668
+ };
669
+ break outer;
670
+ }
671
+ }
672
+ const elements = subColumn.elements;
673
+ for (const element of elements) element.span = {
674
+ masterColumnStart: spanStart.masterColumnIndex,
675
+ masterColumnEnd: spanEnd.masterColumnIndex,
676
+ sectionStart: spanStart.sectionIndex,
677
+ sectionEnd: spanEnd.sectionIndex,
678
+ subColumnStart: spanStart.subColumnIndex,
679
+ subColumnEnd: spanEnd.subColumnIndex
680
+ };
681
+ }
682
+ }
683
+ }
684
+ };
685
+ return {
686
+ grid: newGrid,
687
+ pushMasterColumn,
688
+ calculateDimensions,
689
+ setupElementSpans
690
+ };
691
+ };
692
+ const createBracketMasterColumn = (config) => {
693
+ const { columnWidth, padding } = config;
694
+ const sections = [];
695
+ const newMasterColumn = {
696
+ dimensions: {
697
+ width: columnWidth,
698
+ height: 0,
699
+ top: 0,
700
+ left: 0
701
+ },
702
+ padding,
703
+ sections
704
+ };
705
+ const pushSection = (...newSections) => {
706
+ sections.push(...newSections);
707
+ };
708
+ return {
709
+ masterColumn: newMasterColumn,
710
+ pushSection
711
+ };
712
+ };
713
+ const createBracketMasterColumnSection = (config) => {
714
+ const { type, padding } = config;
715
+ const subColumns = [];
716
+ const newMasterColumnSection = {
717
+ dimensions: {
718
+ width: 0,
719
+ height: 0,
720
+ top: 0,
721
+ left: 0
722
+ },
723
+ subColumns,
724
+ type,
725
+ padding
726
+ };
727
+ const pushSubColumn = (...newSubColumns) => {
728
+ subColumns.push(...newSubColumns);
729
+ };
730
+ return {
731
+ masterColumnSection: newMasterColumnSection,
732
+ pushSubColumn
733
+ };
734
+ };
735
+ const createBracketSubColumn = (config) => {
736
+ const { span } = config;
737
+ const elements = [];
738
+ const newSubColumn = {
739
+ dimensions: {
740
+ width: 0,
741
+ height: 0,
742
+ top: 0,
743
+ left: 0
744
+ },
745
+ elements,
746
+ span
747
+ };
748
+ const pushElement = (...newElements) => {
749
+ elements.push(...newElements);
750
+ };
751
+ return {
752
+ subColumn: newSubColumn,
753
+ pushElement
754
+ };
755
+ };
756
+ const isBracketContinueMatch = (match) => match.round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE && (match.relation.type === "one-to-nothing" || match.relation.type === "two-to-nothing");
757
+ const getBracketContinueMatches = (bracketData) => Array.from(bracketData.matches.values()).filter((match) => isBracketContinueMatch(match));
758
+ const createBracketContinueMasterColumn = (config) => {
759
+ const { existingMasterColumns, columnWidth, elementHeight, headerOffset, component, matches } = config;
760
+ const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];
761
+ if (!lastMasterColumn) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No last master column found in existing master columns");
762
+ const firstSectionIsHeader = lastMasterColumn.sections[0]?.subColumns[0]?.elements[0]?.type === "header";
763
+ let totalHeight = 0;
764
+ for (const [sectionIndex, section] of lastMasterColumn.sections.entries()) {
765
+ const padding = section.padding ?? lastMasterColumn.padding;
766
+ const paddingTop = sectionIndex === 0 && firstSectionIsHeader ? 0 : padding.top;
767
+ const sectionHeight = Math.max(0, ...section.subColumns.map((subColumn) => subColumn.elements.reduce((subColumnHeight, element) => subColumnHeight + element.parts.reduce((sum, part) => sum + part.dimensions.height, 0), 0)));
768
+ totalHeight += paddingTop + sectionHeight + padding.bottom;
769
+ }
770
+ const { masterColumn, pushSection } = createBracketMasterColumn({
771
+ columnWidth,
772
+ padding: {
773
+ bottom: 0,
774
+ left: 0,
775
+ right: 0,
776
+ top: 0
777
+ }
778
+ });
779
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({ type: "round" });
780
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
781
+ isStart: true,
782
+ isEnd: true
783
+ } });
784
+ if (headerOffset > 0) pushElement(createBracketElement({
785
+ area: ".",
786
+ type: "colGap",
787
+ elementHeight: headerOffset,
788
+ partHeights: [headerOffset]
789
+ }));
790
+ const containerHeight = Math.max(elementHeight, totalHeight - headerOffset);
791
+ pushElement(createBracketElement({
792
+ area: "continue",
793
+ type: "continue",
794
+ elementHeight,
795
+ partHeights: [containerHeight],
796
+ component,
797
+ matches
798
+ }));
799
+ pushSubColumn(subColumn);
800
+ pushSection(masterColumnSection);
801
+ return masterColumn;
802
+ };
803
+ const linePath = (from, to, options) => {
804
+ const inverted = options.inverted ?? false;
805
+ const fromInline = inverted ? from.inline.start : from.inline.end;
806
+ const toInline = inverted ? to.inline.end : to.inline.start;
807
+ return path(`M ${fromInline} ${from.block.center} L ${toInline} ${to.block.center}`, options.path);
808
+ };
809
+ const verticalPath = (from, to, options) => {
810
+ const inline = (from.inline.center + to.inline.center) / 2;
811
+ const isDownwards = to.block.center >= from.block.center;
812
+ const fromBlock = isDownwards ? from.block.end : from.block.start;
813
+ const toBlock = isDownwards ? to.block.start : to.block.end;
814
+ return path(`M ${inline} ${fromBlock} V ${toBlock}`, options.path);
815
+ };
816
+ const gutterPath = (from, to, options) => {
817
+ const inverted = options.inverted ?? false;
818
+ const fromInline = inverted ? from.inline.start : from.inline.end;
819
+ const toInline = inverted ? to.inline.start : to.inline.end;
820
+ const runInline = inverted ? Math.min(fromInline, toInline) - options.gutter : Math.max(fromInline, toInline) + options.gutter;
821
+ return path(`M ${fromInline} ${from.block.center} H ${runInline} V ${to.block.center} H ${toInline}`, options.path);
822
+ };
823
+ const makePos = (dimensions) => ({
824
+ block: {
825
+ start: dimensions.top,
826
+ end: dimensions.top + dimensions.height,
827
+ center: dimensions.top + dimensions.height / 2
828
+ },
829
+ inline: {
830
+ start: dimensions.left,
831
+ end: dimensions.left + dimensions.width,
832
+ center: dimensions.left + dimensions.width / 2
833
+ }
834
+ });
835
+ const isSameColumn = (from, to) => Math.abs(from.inline.center - to.inline.center) < 1;
836
+ const straightPath = (from, to, options) => isSameColumn(from, to) ? verticalPath(from, to, options) : linePath(from, to, options);
837
+ const mergePath = (from, to, options) => isSameColumn(from, to) ? verticalPath(from, to, { path: options.path }) : curvePath(from, to, to.block.center >= from.block.center ? "down" : "up", options);
838
+ const edgeId = (fromMatchId, toMatchId) => `${fromMatchId}|${toMatchId}`;
839
+ const drawMan = (dimensions) => {
840
+ const edges = [];
841
+ const takenIds = /* @__PURE__ */ new Set();
842
+ const pushEdge = (edge) => {
843
+ let id = edge.id;
844
+ for (let attempt = 2; takenIds.has(id); attempt++) id = `${edge.id}#${attempt}`;
845
+ takenIds.add(id);
846
+ edges.push(id === edge.id ? edge : {
847
+ ...edge,
848
+ id
849
+ });
850
+ };
851
+ const continueElement = dimensions.bracketGrid.columns.flatMap((col) => col.elements).find((el) => el.type === "continue");
852
+ const continuePos = continueElement ? makePos(continueElement.dimensions) : null;
853
+ const continueSources = [];
854
+ for (const col of dimensions.bracketGrid.columns) for (const el of col.elements) {
855
+ if (el.type !== "match") continue;
856
+ const currentMatchParticipantsShortIds = [el.match.home?.shortId, el.match.away?.shortId].filter((id) => !!id).join(" ");
857
+ const currentPos = makePos(el.dimensions);
858
+ if (el.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;
859
+ if (continuePos && isBracketContinueMatch(el.match)) continueSources.push({
860
+ pos: currentPos,
861
+ className: el.match.winner?.shortId || "",
862
+ matchId: el.match.id
863
+ });
864
+ if (el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT && "nextMatch" in el.match.relation) {
865
+ const { nextMatch, nextRound } = el.match.relation;
866
+ if (nextRound.mirrorRoundType === null) {
867
+ const next = dimensions.bracketGrid.matchElementMap.getOrThrow(nextMatch.id);
868
+ pushEdge(straightPath(makePos(next.dimensions), currentPos, { path: {
869
+ ...dimensions.path,
870
+ id: edgeId(nextMatch.id, el.match.id),
871
+ className: el.match.winner?.shortId || ""
872
+ } }));
873
+ }
874
+ }
875
+ switch (el.match.relation.type) {
876
+ case "none":
877
+ case "nothing-to-one": continue;
878
+ case "one-to-nothing":
879
+ case "one-to-one": {
880
+ const prev = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousMatch.id);
881
+ const prevPos = makePos(prev.dimensions);
882
+ pushEdge(straightPath(prevPos, currentPos, {
883
+ path: {
884
+ ...dimensions.path,
885
+ id: edgeId(el.match.relation.previousMatch.id, el.match.id),
886
+ className: el.match.relation.previousMatch.winner?.shortId || ""
887
+ },
888
+ inverted: el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT
889
+ }));
890
+ break;
891
+ }
892
+ case "two-to-nothing":
893
+ case "two-to-one": {
894
+ const prevUpper = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousUpperMatch.id);
895
+ const prevLower = dimensions.bracketGrid.matchElementMap.getOrThrow(el.match.relation.previousLowerMatch.id);
896
+ const prevUpperPos = makePos(prevUpper.dimensions);
897
+ const prevLowerPos = makePos(prevLower.dimensions);
898
+ const upperId = edgeId(el.match.relation.previousUpperMatch.id, el.match.id);
899
+ const lowerId = edgeId(el.match.relation.previousLowerMatch.id, el.match.id);
900
+ const isLowerUpperMerger = el.match.relation.previousLowerRound.id !== el.match.relation.previousUpperRound.id;
901
+ const invertCurve = el.round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;
902
+ const curveOptions = {
903
+ ...dimensions.curve,
904
+ inverted: invertCurve,
905
+ path: {
906
+ ...dimensions.path,
907
+ id: upperId,
908
+ className: ""
909
+ }
910
+ };
911
+ if (isLowerUpperMerger && dimensions.bracketGrid.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER) pushEdge(straightPath(prevUpperPos, currentPos, {
912
+ path: {
913
+ ...dimensions.path,
914
+ id: upperId,
915
+ className: currentMatchParticipantsShortIds
916
+ },
917
+ inverted: invertCurve
918
+ }));
919
+ else pushEdge(mergePath(prevUpperPos, currentPos, {
920
+ ...curveOptions,
921
+ path: {
922
+ ...curveOptions.path,
923
+ className: el.match.relation.previousUpperMatch.winner?.shortId || ""
924
+ }
925
+ }));
926
+ const lowerPathOptions = {
927
+ ...curveOptions.path,
928
+ id: lowerId,
929
+ className: el.match.relation.previousLowerMatch.winner?.shortId || ""
930
+ };
931
+ pushEdge(isSameColumn(prevLowerPos, currentPos) && prevLowerPos.block.start > currentPos.block.end ? gutterPath(prevLowerPos, currentPos, {
932
+ path: {
933
+ ...dimensions.continuePath ?? dimensions.path,
934
+ id: lowerId,
935
+ className: lowerPathOptions.className
936
+ },
937
+ inverted: invertCurve,
938
+ gutter: dimensions.columnGap / 2
939
+ }) : mergePath(prevLowerPos, currentPos, {
940
+ ...curveOptions,
941
+ path: lowerPathOptions
942
+ }));
943
+ break;
944
+ }
945
+ }
946
+ }
947
+ if (continuePos && continueSources.length) {
948
+ const continuePathOptions = dimensions.continuePath ?? dimensions.path;
949
+ const curveAmount = dimensions.curve.lineStartingCurveAmount;
950
+ const trunkInline = continuePos.inline.start - dimensions.columnGap / 2;
951
+ const continueBlockCenter = continuePos.block.center;
952
+ const sourceBlocks = continueSources.map((source) => source.pos.block.center);
953
+ const firstSourceBlock = Math.min(...sourceBlocks);
954
+ const lastSourceBlock = Math.max(...sourceBlocks);
955
+ const trunkBlocks = [continueBlockCenter];
956
+ for (const source of continueSources) {
957
+ const sourceBlockCenter = source.pos.block.center;
958
+ const blockDistance = continueBlockCenter - sourceBlockCenter;
959
+ const sourcePathOptions = {
960
+ ...continuePathOptions,
961
+ id: edgeId(source.matchId, "continue"),
962
+ className: source.className
963
+ };
964
+ const curve = sourceBlockCenter === firstSourceBlock && blockDistance > .5 || sourceBlockCenter === lastSourceBlock && blockDistance < -.5 ? Math.min(curveAmount, Math.abs(blockDistance)) : 0;
965
+ const curveEndBlock = sourceBlockCenter + curve * Math.sign(blockDistance);
966
+ pushEdge(path(`M ${source.pos.inline.end} ${sourceBlockCenter}
967
+ H ${trunkInline - curve}
968
+ Q ${trunkInline} ${sourceBlockCenter}, ${trunkInline} ${curveEndBlock}`, sourcePathOptions));
969
+ trunkBlocks.push(curveEndBlock);
970
+ }
971
+ const trunkBlockStart = Math.min(...trunkBlocks);
972
+ const trunkBlockEnd = Math.max(...trunkBlocks);
973
+ if (trunkBlockEnd - trunkBlockStart > .5) pushEdge(path(`M ${trunkInline} ${trunkBlockStart} V ${trunkBlockEnd}`, {
974
+ ...continuePathOptions,
975
+ id: "continue|trunk",
976
+ className: ""
977
+ }));
978
+ pushEdge(path(`M ${trunkInline} ${continueBlockCenter} H ${continuePos.inline.start}`, {
979
+ ...continuePathOptions,
980
+ id: "continue|element",
981
+ className: ""
982
+ }));
983
+ }
984
+ return {
985
+ edges,
986
+ rects: [],
987
+ gradients: []
988
+ };
989
+ };
990
+ const BRACKET_SWISS_GROUP_COLOR_TYPE = {
991
+ NEUTRAL: "neutral",
992
+ POSITIVE: "positive",
993
+ NEGATIVE: "negative",
994
+ WARNING: "warning"
995
+ };
996
+ const getSwissGroupColorType = (wins, losses) => {
997
+ if (wins === 0 && losses === 0) return BRACKET_SWISS_GROUP_COLOR_TYPE.NEUTRAL;
998
+ if (losses === 2) return BRACKET_SWISS_GROUP_COLOR_TYPE.NEGATIVE;
999
+ if (wins > losses) return BRACKET_SWISS_GROUP_COLOR_TYPE.POSITIVE;
1000
+ return BRACKET_SWISS_GROUP_COLOR_TYPE.WARNING;
1001
+ };
1002
+ const factorialCache = /* @__PURE__ */ new Map();
1003
+ const getAvailableSwissGroupsForRound = (roundNumber, totalMatchesInRound) => {
1004
+ const advanceWins = 3;
1005
+ const eliminateLosses = 3;
1006
+ const getFactorial = (n) => {
1007
+ if (n <= 1) return 1;
1008
+ if (factorialCache.has(n)) return factorialCache.get(n);
1009
+ const result = n * getFactorial(n - 1);
1010
+ factorialCache.set(n, result);
1011
+ return result;
1012
+ };
1013
+ const roundFactorial = getFactorial(roundNumber);
1014
+ let totalCombinations = 0;
1015
+ const validGroups = [];
1016
+ for (let wins = roundNumber; wins >= 0; wins--) {
1017
+ const losses = roundNumber - wins;
1018
+ const remainingGames = 6 - (wins + losses) - 1;
1019
+ if (!(wins < advanceWins && remainingGames >= 0) || !(losses < eliminateLosses)) continue;
1020
+ const combinations = roundFactorial / (getFactorial(wins) * getFactorial(losses));
1021
+ totalCombinations += combinations;
1022
+ validGroups.push({
1023
+ wins,
1024
+ losses,
1025
+ combinations
1026
+ });
1027
+ }
1028
+ return validGroups.map(({ wins, losses, combinations }) => ({
1029
+ id: `${wins}-${losses}`,
1030
+ name: `${wins}-${losses}`,
1031
+ matchesInGroup: Math.round(combinations / totalCombinations * totalMatchesInRound)
1032
+ }));
1033
+ };
1034
+ const UNDRAWN_SWISS_GROUP_ID = "undrawn";
1035
+ const getRecordBeforeMatch = (participant) => ({
1036
+ wins: participant.winCount - (participant.result === "win" ? 1 : 0),
1037
+ losses: participant.lossCount - (participant.result === "loss" ? 1 : 0)
1038
+ });
1039
+ const generateBracketRoundSwissGroupMaps = (bracketData) => {
1040
+ if (bracketData.mode !== TOURNAMENT_MODE.SWISS_WITH_ELIMINATION) return null;
1041
+ const roundsWithSwissGroups = /* @__PURE__ */ new Map();
1042
+ let roundNumber = 0;
1043
+ for (const bracketRound of bracketData.rounds.values()) {
1044
+ const availableGroups = getAvailableSwissGroupsForRound(roundNumber, bracketRound.matchCount);
1045
+ const roundSwissData = { groups: /* @__PURE__ */ new Map() };
1046
+ for (const group of availableGroups) {
1047
+ const subGroup = {
1048
+ id: group.id,
1049
+ name: group.name,
1050
+ matches: new BracketMap(),
1051
+ allowedMatchCount: group.matchesInGroup
1052
+ };
1053
+ roundSwissData.groups.set(group.id, subGroup);
1054
+ }
1055
+ const emptyMatchIds = [];
1056
+ for (const match of bracketRound.matches.values()) {
1057
+ const anyParticipant = match.home || match.away;
1058
+ if (!anyParticipant) {
1059
+ emptyMatchIds.push(match.id);
1060
+ continue;
1061
+ }
1062
+ const { wins, losses } = getRecordBeforeMatch(anyParticipant);
1063
+ const groupId = `${wins}-${losses}`;
1064
+ let group = roundSwissData.groups.get(groupId);
1065
+ if (!group) {
1066
+ group = {
1067
+ id: groupId,
1068
+ name: `${wins}-${losses}`,
1069
+ matches: new BracketMap(),
1070
+ allowedMatchCount: 0
1071
+ };
1072
+ roundSwissData.groups.set(groupId, group);
1073
+ }
1074
+ group.matches.set(match.id, match);
1075
+ }
1076
+ for (const emptyMatchId of emptyMatchIds) {
1077
+ const match = bracketRound.matches.getOrThrow(emptyMatchId);
1078
+ const groups = [...roundSwissData.groups.values()];
1079
+ let group = groups.find((candidate) => candidate.matches.size < candidate.allowedMatchCount) ?? groups.reduce((fewest, candidate) => !fewest || candidate.matches.size < fewest.matches.size ? candidate : fewest, null);
1080
+ if (!group) {
1081
+ group = {
1082
+ id: UNDRAWN_SWISS_GROUP_ID,
1083
+ name: "",
1084
+ matches: new BracketMap(),
1085
+ allowedMatchCount: 0
1086
+ };
1087
+ roundSwissData.groups.set(group.id, group);
1088
+ }
1089
+ group.matches.set(match.id, match);
1090
+ }
1091
+ for (const [groupId, group] of roundSwissData.groups) if (!group.matches.size) roundSwissData.groups.delete(groupId);
1092
+ const orderedGroups = [...roundSwissData.groups.entries()].sort(([a], [b]) => {
1093
+ const [aWins = 0, aLosses = 0] = a.split("-").map(Number);
1094
+ const [bWins = 0, bLosses = 0] = b.split("-").map(Number);
1095
+ return bWins - aWins || aLosses - bLosses;
1096
+ });
1097
+ roundSwissData.groups = new Map(orderedGroups);
1098
+ roundsWithSwissGroups.set(bracketRound.id, roundSwissData);
1099
+ roundNumber++;
1100
+ }
1101
+ return roundsWithSwissGroups;
1102
+ };
1103
+ const collectSwissRoundGeometries = (bracketGrid) => {
1104
+ const rounds = /* @__PURE__ */ new Map();
1105
+ for (const column of bracketGrid.columns) {
1106
+ const matchElements = column.elements.filter((element) => element.type === "match");
1107
+ const group = matchElements[0]?.roundSwissGroup;
1108
+ const round = matchElements[0]?.round;
1109
+ if (!group || !round) continue;
1110
+ const [wins, losses] = group.id.split("-").map(Number);
1111
+ if (wins === void 0 || losses === void 0 || isNaN(wins) || isNaN(losses)) continue;
1112
+ const matchesTop = Math.min(...matchElements.map((element) => element.dimensions.top));
1113
+ const matchesBottom = Math.max(...matchElements.map((element) => element.dimensions.top + element.dimensions.height));
1114
+ const winnerShortIds = [];
1115
+ const loserShortIds = [];
1116
+ for (const element of matchElements) {
1117
+ if (!element.match.winner) continue;
1118
+ const winner = element.match.winner;
1119
+ const loser = element.match.home?.id === winner.id ? element.match.away : element.match.home;
1120
+ winnerShortIds.push(winner.shortId);
1121
+ if (loser) loserShortIds.push(loser.shortId);
1122
+ }
1123
+ const position = {
1124
+ block: {
1125
+ start: matchesTop,
1126
+ end: matchesBottom,
1127
+ center: (matchesTop + matchesBottom) / 2
1128
+ },
1129
+ inline: {
1130
+ start: column.dimensions.left,
1131
+ end: column.dimensions.left + column.dimensions.width,
1132
+ center: column.dimensions.left + column.dimensions.width / 2
1133
+ }
1134
+ };
1135
+ let roundGeometry = rounds.get(round.id);
1136
+ if (!roundGeometry) {
1137
+ roundGeometry = { groups: /* @__PURE__ */ new Map() };
1138
+ rounds.set(round.id, roundGeometry);
1139
+ }
1140
+ roundGeometry.groups.set(group.id, {
1141
+ id: group.id,
1142
+ wins,
1143
+ losses,
1144
+ colorType: getSwissGroupColorType(wins, losses),
1145
+ position,
1146
+ winnerShortIds,
1147
+ loserShortIds
1148
+ });
1149
+ }
1150
+ return Array.from(rounds.values());
1151
+ };
1152
+ const groupBorderRect = (group, border, color, id) => {
1153
+ const boxPadding = border.padding + border.width;
1154
+ const strokeInset = border.width / 2;
1155
+ return {
1156
+ id,
1157
+ x: group.position.inline.start + strokeInset,
1158
+ y: group.position.block.start - boxPadding + strokeInset,
1159
+ width: group.position.inline.end - group.position.inline.start - border.width,
1160
+ height: group.position.block.end - group.position.block.start + boxPadding * 2 - border.width,
1161
+ radius: border.radius,
1162
+ stroke: color ?? "currentColor",
1163
+ strokeWidth: border.width,
1164
+ tone: group.colorType,
1165
+ cssClass: `et-bracket-swiss-group-border et-bracket-swiss-group-border--${group.id} et-bracket-swiss-group-border--${group.colorType}`
1166
+ };
1167
+ };
1168
+ const lineGradient = (config) => ({
1169
+ id: config.id,
1170
+ fromX: config.fromX,
1171
+ toX: config.toX,
1172
+ stops: [
1173
+ {
1174
+ offset: "0%",
1175
+ color: config.from
1176
+ },
1177
+ {
1178
+ offset: "50%",
1179
+ color: config.neutral
1180
+ },
1181
+ {
1182
+ offset: "100%",
1183
+ color: config.to
1184
+ }
1185
+ ]
1186
+ });
1187
+ const drawSwissMan = (dimensions) => {
1188
+ const edges = [];
1189
+ const rects = [];
1190
+ const gradients = [];
1191
+ const roundGeometries = collectSwissRoundGeometries(dimensions.bracketGrid);
1192
+ const colors = dimensions.colors;
1193
+ for (const [roundIndex, roundGeometry] of roundGeometries.entries()) for (const group of roundGeometry.groups.values()) rects.push(groupBorderRect(group, dimensions.groupBorder, colors?.[group.colorType], `r${roundIndex}|${group.id}`));
1194
+ const curveOptions = {
1195
+ lineStartingCurveAmount: dimensions.curve.lineStartingCurveAmount,
1196
+ lineEndingCurveAmount: dimensions.curve.lineStartingCurveAmount
1197
+ };
1198
+ for (const [roundIndex, roundGeometry] of roundGeometries.entries()) {
1199
+ const nextRoundGeometry = roundGeometries[roundIndex + 1];
1200
+ if (!nextRoundGeometry) break;
1201
+ for (const group of roundGeometry.groups.values()) {
1202
+ const targets = [{
1203
+ geometry: nextRoundGeometry.groups.get(`${group.wins + 1}-${group.losses}`),
1204
+ shortIds: group.winnerShortIds
1205
+ }, {
1206
+ geometry: nextRoundGeometry.groups.get(`${group.wins}-${group.losses + 1}`),
1207
+ shortIds: group.loserShortIds
1208
+ }];
1209
+ for (const { geometry: target, shortIds } of targets) {
1210
+ if (!target) continue;
1211
+ const edgeId = `r${roundIndex}|${group.id}|${target.id}`;
1212
+ const gradientId = `${dimensions.idPrefix}-swiss-line-r${roundIndex}-${group.id}-to-${target.id}`;
1213
+ const neutralColor = colors?.neutral;
1214
+ let stroke = neutralColor;
1215
+ if (neutralColor) {
1216
+ const from = colors?.[group.colorType] ?? neutralColor;
1217
+ const to = colors?.[target.colorType] ?? neutralColor;
1218
+ if (from !== neutralColor || to !== neutralColor) {
1219
+ gradients.push(lineGradient({
1220
+ id: gradientId,
1221
+ fromX: group.position.inline.end,
1222
+ toX: target.position.inline.start,
1223
+ from,
1224
+ neutral: neutralColor,
1225
+ to
1226
+ }));
1227
+ stroke = `url(#${gradientId})`;
1228
+ }
1229
+ }
1230
+ const pathOptions = {
1231
+ ...dimensions.path,
1232
+ id: edgeId,
1233
+ className: shortIds.join(" "),
1234
+ stroke
1235
+ };
1236
+ const blockDelta = target.position.block.center - group.position.block.center;
1237
+ edges.push(curvePath(group.position, target.position, blockDelta < 0 ? "up" : "down", {
1238
+ ...curveOptions,
1239
+ path: pathOptions
1240
+ }));
1241
+ }
1242
+ }
1243
+ }
1244
+ return {
1245
+ edges,
1246
+ rects,
1247
+ gradients
1248
+ };
1249
+ };
1250
+ const calculateUpperLowerRatio = (upperRoundsCount, lowerRoundsCount) => {
1251
+ const remainingUpperRounds = upperRoundsCount - 1;
1252
+ const remainingLowerRounds = lowerRoundsCount - 1;
1253
+ if (remainingUpperRounds === 0) return 1;
1254
+ return remainingLowerRounds / remainingUpperRounds;
1255
+ };
1256
+ const calculateColumnSplitFactor = (upperToLowerRatio) => upperToLowerRatio === 1.5 ? 2 : 1;
1257
+ const calculateLowerRoundIndex = (subColumnIndex, splitFactor) => Math.floor(subColumnIndex / splitFactor);
1258
+ const calculateUpperRoundIndex = (subColumnIndex, upperToLowerRatio, splitFactor) => {
1259
+ const completeColumnIndex = Math.floor(subColumnIndex / splitFactor);
1260
+ if (completeColumnIndex === 0) return 0;
1261
+ return Math.floor((completeColumnIndex - 1) / upperToLowerRatio) + 1;
1262
+ };
1263
+ const createRoundBracketSubColumnRelativeToFirstRound = (config) => {
1264
+ const { firstRound, round, options, span, hasReverseFinal } = config;
1265
+ const { subColumn, pushElement } = createBracketSubColumn({ span });
1266
+ const matchFactor = config.matchFactor ?? Math.max(1, (options.rowSpanMatchCount ?? firstRound.matchCount) / round.matchCount);
1267
+ const matches = Array.from(round.matches.values());
1268
+ const isFinalRound = hasReverseFinal ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;
1269
+ const roundHeaderGap = isFinalRound ? Math.max(options.roundHeaderGap, options.finalRoundHeaderGap ?? 0) : options.roundHeaderGap;
1270
+ const elementsToCreate = [];
1271
+ if (options.roundHeaderHeight > 0) elementsToCreate.push({
1272
+ type: "header",
1273
+ area: `h${round.shortId}`,
1274
+ partHeights: [options.roundHeaderHeight],
1275
+ elementHeight: options.roundHeaderHeight,
1276
+ component: config.components.roundHeader,
1277
+ round,
1278
+ roundSwissGroup: null
1279
+ }, {
1280
+ type: "roundHeaderGap",
1281
+ area: ".",
1282
+ partHeights: [roundHeaderGap],
1283
+ elementHeight: roundHeaderGap
1284
+ });
1285
+ if (config.topPadding) elementsToCreate.push({
1286
+ type: "colGap",
1287
+ area: ".",
1288
+ partHeights: [config.topPadding],
1289
+ elementHeight: config.topPadding
1290
+ });
1291
+ for (const [matchIndex, match] of matches.entries()) {
1292
+ const isLastMatch = matchIndex === matches.length - 1;
1293
+ const fedMatchCount = Math.floor(matchFactor);
1294
+ const matchRows = [];
1295
+ for (let factorIndex = 0; factorIndex < fedMatchCount; factorIndex++) {
1296
+ matchRows.push(options.matchHeight);
1297
+ if (factorIndex < fedMatchCount - 1) matchRows.push(options.rowGap);
1298
+ }
1299
+ const elementHeight = isFinalRound ? options.finalMatchHeight : options.matchHeight;
1300
+ const blockHeight = Math.max(elementHeight, matchFactor * options.matchHeight + (matchFactor - 1) * options.rowGap);
1301
+ const currentBlockHeight = matchRows.reduce((total, height) => total + height, 0);
1302
+ matchRows[matchRows.length - 1] = (matchRows[matchRows.length - 1] ?? 0) + blockHeight - currentBlockHeight;
1303
+ elementsToCreate.push({
1304
+ type: "match",
1305
+ area: `m${match.shortId}`,
1306
+ partHeights: matchRows,
1307
+ elementHeight,
1308
+ component: isFinalRound ? config.components.finalMatch : config.components.match,
1309
+ match,
1310
+ round,
1311
+ roundSwissGroup: null
1312
+ });
1313
+ if (!isLastMatch) elementsToCreate.push({
1314
+ type: "matchGap",
1315
+ area: ".",
1316
+ partHeights: [options.rowGap],
1317
+ elementHeight: options.rowGap
1318
+ });
1319
+ }
1320
+ if (config.bottomPadding) elementsToCreate.push({
1321
+ type: "colGap",
1322
+ area: ".",
1323
+ partHeights: [config.bottomPadding],
1324
+ elementHeight: config.bottomPadding
1325
+ });
1326
+ for (const elementData of elementsToCreate) pushElement(createBracketElement(elementData));
1327
+ return subColumn;
1328
+ };
1329
+ const heightOfElement = (element) => element.parts.reduce((total, part) => total + part.dimensions.height, 0);
1330
+ const cardGeometry = (subColumn) => {
1331
+ let height = 0;
1332
+ let cardTop = null;
1333
+ for (const element of subColumn.elements) {
1334
+ const elementHeight = heightOfElement(element);
1335
+ if (element.type === "match" && cardTop === null) cardTop = height + (elementHeight - element.dimensions.height) / 2;
1336
+ height += elementHeight;
1337
+ }
1338
+ return {
1339
+ cardTop: cardTop ?? 0,
1340
+ height
1341
+ };
1342
+ };
1343
+ const createFoldedThirdPlaceSection = (config) => {
1344
+ const { options, round } = config;
1345
+ const final = cardGeometry(config.finalSubColumn);
1346
+ const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;
1347
+ const paddingTop = final.cardTop + config.topOffset - final.height - headerOffset;
1348
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({
1349
+ type: "round",
1350
+ padding: {
1351
+ top: paddingTop,
1352
+ bottom: 0,
1353
+ left: 0,
1354
+ right: 0
1355
+ }
1356
+ });
1357
+ pushSubColumn(createRoundBracketSubColumnRelativeToFirstRound({
1358
+ firstRound: round,
1359
+ round,
1360
+ options,
1361
+ hasReverseFinal: false,
1362
+ matchFactor: 1,
1363
+ span: {
1364
+ isStart: true,
1365
+ isEnd: true
1366
+ },
1367
+ components: config.components
1368
+ }));
1369
+ return masterColumnSection;
1370
+ };
1371
+ const createBracketGapMasterColumn = (config) => {
1372
+ const { existingMasterColumns, columnGap } = config;
1373
+ const lastMasterColumn = existingMasterColumns[existingMasterColumns.length - 1];
1374
+ if (!lastMasterColumn) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No last master column found in existing master columns");
1375
+ const { masterColumn, pushSection } = createBracketMasterColumn({
1376
+ columnWidth: columnGap,
1377
+ padding: {
1378
+ bottom: 0,
1379
+ left: 0,
1380
+ right: 0,
1381
+ top: 0
1382
+ }
1383
+ });
1384
+ for (const section of lastMasterColumn.sections) {
1385
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({
1386
+ type: "gap",
1387
+ padding: section.padding && {
1388
+ ...section.padding,
1389
+ left: 0,
1390
+ right: 0
1391
+ }
1392
+ });
1393
+ const lastSubColumn = section.subColumns[section.subColumns.length - 1];
1394
+ if (!lastSubColumn) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No last sub column found in section");
1395
+ const { pushElement, subColumn } = createBracketSubColumn({ span: {
1396
+ isStart: lastSubColumn.span.isEnd ? true : false,
1397
+ isEnd: lastSubColumn.span.isEnd ? true : false
1398
+ } });
1399
+ for (const lastSubColumnElement of lastSubColumn.elements) {
1400
+ const partHeights = lastSubColumnElement.parts.map((part) => part.dimensions.height);
1401
+ const elementToCreate = (() => {
1402
+ switch (lastSubColumnElement.type) {
1403
+ case "matchGap":
1404
+ case "roundHeaderGap":
1405
+ case "roundGap":
1406
+ case "colGap": return {
1407
+ area: !lastSubColumn.span.isEnd ? lastSubColumnElement.area : `.`,
1408
+ type: !lastSubColumn.span.isEnd ? lastSubColumnElement.type : "colGap",
1409
+ elementHeight: lastSubColumnElement.dimensions.height,
1410
+ partHeights
1411
+ };
1412
+ case "header":
1413
+ if (lastSubColumn.span.isEnd) break;
1414
+ return {
1415
+ area: lastSubColumnElement.area,
1416
+ type: lastSubColumnElement.type,
1417
+ elementHeight: lastSubColumnElement.dimensions.height,
1418
+ partHeights,
1419
+ component: lastSubColumnElement.component,
1420
+ round: lastSubColumnElement.round,
1421
+ roundSwissGroup: lastSubColumnElement.roundSwissGroup
1422
+ };
1423
+ case "match":
1424
+ if (lastSubColumn.span.isEnd) break;
1425
+ return {
1426
+ area: lastSubColumnElement.area,
1427
+ type: lastSubColumnElement.type,
1428
+ elementHeight: lastSubColumnElement.dimensions.height,
1429
+ partHeights,
1430
+ component: lastSubColumnElement.component,
1431
+ round: lastSubColumnElement.round,
1432
+ match: lastSubColumnElement.match,
1433
+ roundSwissGroup: lastSubColumnElement.roundSwissGroup
1434
+ };
1435
+ }
1436
+ return {
1437
+ area: `.`,
1438
+ type: "colGap",
1439
+ elementHeight: lastSubColumnElement.dimensions.height,
1440
+ partHeights
1441
+ };
1442
+ })();
1443
+ pushElement(createBracketElement(elementToCreate));
1444
+ }
1445
+ pushSubColumn(subColumn);
1446
+ pushSection(masterColumnSection);
1447
+ }
1448
+ return masterColumn;
1449
+ };
1450
+ const resolveBracketGridRowSpan = (bracket, options) => {
1451
+ if (!options.rowSpanRoundId) return options;
1452
+ const round = Array.from(bracket.rounds.values()).find((candidate) => candidate.id === options.rowSpanRoundId || candidate.id.startsWith(`${options.rowSpanRoundId}--half-`));
1453
+ return round ? {
1454
+ ...options,
1455
+ rowSpanMatchCount: round.matchCount
1456
+ } : options;
1457
+ };
1458
+ const resolveThirdPlaceTopOffset = (options) => {
1459
+ if (options.thirdPlaceTopOffset !== null && options.thirdPlaceTopOffset !== void 0) return options.thirdPlaceTopOffset;
1460
+ if (options.layout !== BRACKET_DATA_LAYOUT.MIRRORED) return null;
1461
+ const headerOffset = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;
1462
+ return options.finalMatchHeight + options.rowGap + headerOffset;
1463
+ };
1464
+ const resolveFoldedThirdPlaceRound = (rounds, topOffset) => {
1465
+ if (topOffset === null) return null;
1466
+ if (!rounds.some((round) => round.type === COMMON_BRACKET_ROUND_TYPE.FINAL)) return null;
1467
+ return rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null;
1468
+ };
1469
+ const createSectionTitleBand = (height) => {
1470
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({ type: "gap" });
1471
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
1472
+ isStart: true,
1473
+ isEnd: true
1474
+ } });
1475
+ pushElement(createBracketElement({
1476
+ area: ".",
1477
+ type: "colGap",
1478
+ elementHeight: height,
1479
+ partHeights: [height]
1480
+ }));
1481
+ pushSubColumn(subColumn);
1482
+ return masterColumnSection;
1483
+ };
1484
+ const buildSingleEliminationGrid = (bracketData, options, components, titleSpace) => {
1485
+ const grid = createBracketGrid({ spanElementWidth: options.columnWidth });
1486
+ const rounds = Array.from(bracketData.rounds.values());
1487
+ const firstRound = bracketData.rounds.first();
1488
+ if (!firstRound) throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, "No rounds found in bracket data");
1489
+ const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);
1490
+ const thirdPlaceTopOffset = resolveThirdPlaceTopOffset(options);
1491
+ const foldedThirdPlaceRound = resolveFoldedThirdPlaceRound(rounds, thirdPlaceTopOffset);
1492
+ const ownColumnThirdPlaceRound = foldedThirdPlaceRound ? null : rounds.find((round) => round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) ?? null;
1493
+ const chainRounds = rounds.filter((round) => round !== foldedThirdPlaceRound && round !== ownColumnThirdPlaceRound);
1494
+ let pushSectionToFinal = null;
1495
+ let finalSubColumn = null;
1496
+ const pushGapColumn = () => grid.pushMasterColumn(createBracketGapMasterColumn({
1497
+ existingMasterColumns: grid.grid.masterColumns,
1498
+ columnGap: options.columnGap
1499
+ }));
1500
+ const pushRoundColumn = (round) => {
1501
+ const { masterColumn, ...mutableMasterColumn } = createBracketMasterColumn({
1502
+ columnWidth: round.type === COMMON_BRACKET_ROUND_TYPE.FINAL ? options.finalColumnWidth : options.columnWidth,
1503
+ padding: {
1504
+ bottom: 0,
1505
+ left: 0,
1506
+ right: 0,
1507
+ top: 0
1508
+ }
1509
+ });
1510
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({ type: "round" });
1511
+ const sub = createRoundBracketSubColumnRelativeToFirstRound({
1512
+ firstRound,
1513
+ round,
1514
+ options: resolvedOptions,
1515
+ hasReverseFinal: false,
1516
+ span: {
1517
+ isStart: true,
1518
+ isEnd: true
1519
+ },
1520
+ components
1521
+ });
1522
+ pushSubColumn(sub);
1523
+ if (titleSpace) mutableMasterColumn.pushSection(createSectionTitleBand(titleSpace));
1524
+ mutableMasterColumn.pushSection(masterColumnSection);
1525
+ grid.pushMasterColumn(masterColumn);
1526
+ return {
1527
+ pushSection: mutableMasterColumn.pushSection,
1528
+ sub
1529
+ };
1530
+ };
1531
+ for (const [roundIndex, round] of chainRounds.entries()) {
1532
+ if (roundIndex > 0) pushGapColumn();
1533
+ const { pushSection, sub } = pushRoundColumn(round);
1534
+ if (round.type === COMMON_BRACKET_ROUND_TYPE.FINAL) {
1535
+ pushSectionToFinal = pushSection;
1536
+ finalSubColumn = sub;
1537
+ }
1538
+ }
1539
+ if (foldedThirdPlaceRound && pushSectionToFinal && finalSubColumn) pushSectionToFinal(createFoldedThirdPlaceSection({
1540
+ finalSubColumn,
1541
+ round: foldedThirdPlaceRound,
1542
+ topOffset: thirdPlaceTopOffset ?? 0,
1543
+ options: resolvedOptions,
1544
+ components
1545
+ }));
1546
+ if (options.continueElement && components.continue) {
1547
+ const continueMatches = getBracketContinueMatches(bracketData);
1548
+ if (continueMatches.length) {
1549
+ grid.pushMasterColumn(createBracketGapMasterColumn({
1550
+ existingMasterColumns: grid.grid.masterColumns,
1551
+ columnGap: options.columnGap
1552
+ }));
1553
+ grid.pushMasterColumn(createBracketContinueMasterColumn({
1554
+ existingMasterColumns: grid.grid.masterColumns,
1555
+ columnWidth: options.continueElement.columnWidth,
1556
+ elementHeight: options.continueElement.elementHeight,
1557
+ headerOffset: titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),
1558
+ component: components.continue,
1559
+ matches: continueMatches
1560
+ }));
1561
+ }
1562
+ }
1563
+ if (ownColumnThirdPlaceRound) {
1564
+ if (chainRounds.length) pushGapColumn();
1565
+ pushRoundColumn(ownColumnThirdPlaceRound);
1566
+ }
1567
+ grid.calculateDimensions();
1568
+ const finalizedGrid = finalizeBracketGrid(grid);
1569
+ return {
1570
+ raw: grid,
1571
+ columns: finalizedGrid.columns,
1572
+ matchElementMap: finalizedGrid.elementMap
1573
+ };
1574
+ };
1575
+ const createSingleEliminationGrid = (bracketData, options, components) => buildSingleEliminationGrid(bracketData, options, components, 0);
1576
+ const BRACKET_SECTION_KEY = {
1577
+ UPPER: "upper",
1578
+ LOWER: "lower",
1579
+ FINALS: "finals"
1580
+ };
1581
+ const BRACKET_SECTION_DEFAULT_NAMES = {
1582
+ upper: "Upper bracket",
1583
+ lower: "Lower bracket",
1584
+ finals: "Finals"
1585
+ };
1586
+ const doubleEliminationRoundSection = (round) => {
1587
+ switch (round.type) {
1588
+ case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET: return BRACKET_SECTION_KEY.UPPER;
1589
+ case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET: return BRACKET_SECTION_KEY.LOWER;
1590
+ case COMMON_BRACKET_ROUND_TYPE.FINAL:
1591
+ case DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL:
1592
+ case COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE:
1593
+ default: return BRACKET_SECTION_KEY.FINALS;
1594
+ }
1595
+ };
1596
+ const createBracketGridSections = (config) => {
1597
+ const found = /* @__PURE__ */ new Map();
1598
+ for (const column of config.columns) for (const element of column.elements) {
1599
+ if (element.type === "continue") continue;
1600
+ const key = config.sectionOf(element.round);
1601
+ const { top, left, width, height } = element.dimensions;
1602
+ const box = found.get(key);
1603
+ if (!box) {
1604
+ found.set(key, {
1605
+ rounds: /* @__PURE__ */ new Set([element.round]),
1606
+ top,
1607
+ left,
1608
+ right: left + width,
1609
+ bottom: top + height
1610
+ });
1611
+ continue;
1612
+ }
1613
+ box.rounds.add(element.round);
1614
+ box.top = Math.min(box.top, top);
1615
+ box.left = Math.min(box.left, left);
1616
+ box.right = Math.max(box.right, left + width);
1617
+ box.bottom = Math.max(box.bottom, top + height);
1618
+ }
1619
+ return Object.values(BRACKET_SECTION_KEY).flatMap((key) => {
1620
+ const box = found.get(key);
1621
+ if (!box) return [];
1622
+ const width = box.right - box.left;
1623
+ const top = config.tops?.[key] ?? box.top;
1624
+ return [{
1625
+ key,
1626
+ name: BRACKET_SECTION_DEFAULT_NAMES[key],
1627
+ rounds: Array.from(box.rounds),
1628
+ dimensions: {
1629
+ top,
1630
+ left: box.left,
1631
+ width,
1632
+ height: box.bottom - top
1633
+ },
1634
+ titleDimensions: {
1635
+ top: top - (config.titleGap ?? 0) - config.titleHeight,
1636
+ left: box.left,
1637
+ width,
1638
+ height: config.titleHeight
1639
+ }
1640
+ }];
1641
+ });
1642
+ };
1643
+ const sectionTitleSpace = (options) => options.sectionTitleHeight ? options.sectionTitleHeight + (options.sectionTitleGap ?? 0) : 0;
1644
+ const hasBothSides = (bracketData) => !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.first() && !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.first();
1645
+ const createOneSidedGrid = (bracketData, options, components) => {
1646
+ const titleSpace = sectionTitleSpace(options);
1647
+ const grid = buildSingleEliminationGrid(bracketData, options, components, titleSpace);
1648
+ return {
1649
+ ...grid,
1650
+ sections: createBracketGridSections({
1651
+ columns: grid.columns,
1652
+ sectionOf: doubleEliminationRoundSection,
1653
+ titleHeight: options.sectionTitleHeight ?? 0,
1654
+ titleGap: options.sectionTitleGap,
1655
+ tops: {
1656
+ upper: titleSpace,
1657
+ lower: titleSpace,
1658
+ finals: titleSpace
1659
+ }
1660
+ })
1661
+ };
1662
+ };
1663
+ const createDoubleEliminationGrid = (bracketData, options, components) => {
1664
+ if (!hasBothSides(bracketData)) return createOneSidedGrid(bracketData, options, components);
1665
+ const grid = buildDoubleEliminationGrid(bracketData, options, components, /* @__PURE__ */ new Map());
1666
+ if (options.finalAlignment !== BRACKET_FINAL_ALIGNMENT.CENTER) return grid;
1667
+ return {
1668
+ ...buildDoubleEliminationGrid(bracketData, options, components, centeredFinalOffsets(bracketData, grid, options)),
1669
+ finalAlignment: BRACKET_FINAL_ALIGNMENT.CENTER
1670
+ };
1671
+ };
1672
+ const matchBlock = (grid, round) => {
1673
+ if (!round) return null;
1674
+ let top = Infinity;
1675
+ let bottom = -Infinity;
1676
+ for (const match of round.matches.values()) {
1677
+ const element = grid.matchElementMap.get(match.id);
1678
+ if (!element) continue;
1679
+ top = Math.min(top, element.dimensions.top);
1680
+ bottom = Math.max(bottom, element.dimensions.top + element.dimensions.height);
1681
+ }
1682
+ return top <= bottom ? {
1683
+ top,
1684
+ bottom,
1685
+ center: (top + bottom) / 2
1686
+ } : null;
1687
+ };
1688
+ const centeredFinalOffsets = (bracketData, grid, options) => {
1689
+ const offsets = /* @__PURE__ */ new Map();
1690
+ const upperFinal = matchBlock(grid, bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.last());
1691
+ const lowerFinal = matchBlock(grid, bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.last());
1692
+ if (!upperFinal || !lowerFinal) return offsets;
1693
+ const target = (upperFinal.center + lowerFinal.center) / 2;
1694
+ const thirdPlace = matchBlock(grid, bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first());
1695
+ const finalRounds = [...bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.FINAL)?.values() ?? [], ...bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.values() ?? []];
1696
+ for (const round of finalRounds) {
1697
+ const final = matchBlock(grid, round);
1698
+ if (!final) continue;
1699
+ const offset = Math.max(0, target - final.center);
1700
+ const room = thirdPlace ? Math.max(0, thirdPlace.top - options.rowGap - final.bottom) : Infinity;
1701
+ offsets.set(round.id, Math.min(offset, room));
1702
+ }
1703
+ return offsets;
1704
+ };
1705
+ const buildDoubleEliminationGrid = (bracketData, options, components, finalOffsets) => {
1706
+ const resolvedOptions = resolveBracketGridRowSpan(bracketData, options);
1707
+ const grid = createBracketGrid({ spanElementWidth: resolvedOptions.columnWidth });
1708
+ const titleSpace = sectionTitleSpace(options);
1709
+ const presentUpperBracketRounds = Array.from(bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET)?.values() ?? []);
1710
+ const lowerBracketRounds = Array.from(bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET)?.values() ?? []);
1711
+ const fullUpperRoundCount = Math.floor(lowerBracketRounds.length / 2) + 1;
1712
+ const frontMissingUpperRounds = Math.max(0, fullUpperRoundCount - presentUpperBracketRounds.length);
1713
+ const upperBracketRounds = [...Array.from({ length: frontMissingUpperRounds }, () => null), ...presentUpperBracketRounds];
1714
+ const remainingRounds = Array.from(bracketData.rounds.values()).filter((r) => r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET && r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET && r.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE);
1715
+ const thirdPlaceRound = bracketData.roundsByType.get(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)?.first() ?? null;
1716
+ const hasReverseFinal = !!bracketData.roundsByType.get(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)?.first();
1717
+ const firstUpperRound = presentUpperBracketRounds[0];
1718
+ const firstLowerRound = lowerBracketRounds[0];
1719
+ if (!firstUpperRound || !firstLowerRound) throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, "No upper or lower rounds found in bracket data");
1720
+ const upperToLowerRatio = calculateUpperLowerRatio(upperBracketRounds.length, lowerBracketRounds.length);
1721
+ const columnSplitFactor = calculateColumnSplitFactor(upperToLowerRatio);
1722
+ const createUpperBracketSubColumn = (config) => {
1723
+ if (config.round) return createRoundBracketSubColumnRelativeToFirstRound({
1724
+ firstRound: firstUpperRound,
1725
+ round: config.round,
1726
+ options: resolvedOptions,
1727
+ hasReverseFinal,
1728
+ span: config.span,
1729
+ components
1730
+ });
1731
+ const emptyUpperHeight = (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0) + firstUpperRound.matchCount * options.matchHeight + Math.max(0, firstUpperRound.matchCount - 1) * options.rowGap;
1732
+ const { subColumn, pushElement } = createBracketSubColumn({ span: config.span });
1733
+ pushElement(createBracketElement({
1734
+ area: ".",
1735
+ type: "colGap",
1736
+ elementHeight: emptyUpperHeight,
1737
+ partHeights: [emptyUpperHeight]
1738
+ }));
1739
+ return subColumn;
1740
+ };
1741
+ const createUpperLowerGapSubColumn = () => {
1742
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
1743
+ isStart: true,
1744
+ isEnd: true
1745
+ } });
1746
+ pushElement(createBracketElement({
1747
+ area: ".",
1748
+ type: "roundGap",
1749
+ elementHeight: options.rowRoundGap + titleSpace,
1750
+ partHeights: [options.rowRoundGap + titleSpace]
1751
+ }));
1752
+ return subColumn;
1753
+ };
1754
+ const pushSectionTitleBand = (pushSection) => {
1755
+ if (!titleSpace) return;
1756
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({ type: "gap" });
1757
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
1758
+ isStart: true,
1759
+ isEnd: true
1760
+ } });
1761
+ pushElement(createBracketElement({
1762
+ area: ".",
1763
+ type: "colGap",
1764
+ elementHeight: titleSpace,
1765
+ partHeights: [titleSpace]
1766
+ }));
1767
+ pushSubColumn(subColumn);
1768
+ pushSection(masterColumnSection);
1769
+ };
1770
+ let lastRoundLastSubColumnUpperIndex = -1;
1771
+ let lastRoundLastSubColumnLowerIndex = -1;
1772
+ for (const [lowerRoundIndex, lowerRound] of lowerBracketRounds.entries()) {
1773
+ const isLastLowerRound = lowerRoundIndex === lowerBracketRounds.length - 1;
1774
+ const { masterColumn, pushSection } = createBracketMasterColumn({
1775
+ columnWidth: options.columnWidth,
1776
+ padding: {
1777
+ bottom: 0,
1778
+ left: 0,
1779
+ right: 0,
1780
+ top: 0
1781
+ }
1782
+ });
1783
+ const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection({ type: "round" });
1784
+ const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } = createBracketMasterColumnSection({ type: "gap" });
1785
+ const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection({ type: "round" });
1786
+ for (let currentColumnSplitFactor = 1; currentColumnSplitFactor <= columnSplitFactor; currentColumnSplitFactor++) {
1787
+ const subColumnIndex = lowerRoundIndex * columnSplitFactor + (currentColumnSplitFactor - 1);
1788
+ const currentUpperRoundIndex = calculateUpperRoundIndex(subColumnIndex, upperToLowerRatio, columnSplitFactor);
1789
+ const currentLowerRoundIndex = lowerRoundIndex;
1790
+ const isFirstSubColumnInMasterColumn = currentColumnSplitFactor === 1;
1791
+ const isLastSubColumnInMasterColumn = currentColumnSplitFactor === columnSplitFactor;
1792
+ const previousSubColumnIndex = subColumnIndex - 1;
1793
+ const nextSubColumnIndex = subColumnIndex + 1;
1794
+ const previousUpperRoundIndex = previousSubColumnIndex >= 0 ? calculateUpperRoundIndex(previousSubColumnIndex, upperToLowerRatio, columnSplitFactor) : -1;
1795
+ const nextUpperRoundIndex = calculateUpperRoundIndex(nextSubColumnIndex, upperToLowerRatio, columnSplitFactor);
1796
+ const previousLowerRoundIndex = previousSubColumnIndex >= 0 ? calculateLowerRoundIndex(previousSubColumnIndex, columnSplitFactor) : -1;
1797
+ const nextLowerRoundIndex = calculateLowerRoundIndex(nextSubColumnIndex, columnSplitFactor);
1798
+ if (currentUpperRoundIndex < 0 || currentUpperRoundIndex >= upperBracketRounds.length) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "Upper round not found for subColumnIndex: " + subColumnIndex);
1799
+ const upperRound = upperBracketRounds[currentUpperRoundIndex];
1800
+ const isUpperSpanStart = isFirstSubColumnInMasterColumn ? lowerRoundIndex === 0 || lastRoundLastSubColumnUpperIndex !== currentUpperRoundIndex : previousUpperRoundIndex !== currentUpperRoundIndex;
1801
+ const isUpperSpanEnd = isLastSubColumnInMasterColumn ? isLastLowerRound || calculateUpperRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, upperToLowerRatio, columnSplitFactor) !== currentUpperRoundIndex : nextUpperRoundIndex !== currentUpperRoundIndex;
1802
+ const isLowerSpanStart = isFirstSubColumnInMasterColumn ? lowerRoundIndex === 0 || lastRoundLastSubColumnLowerIndex !== currentLowerRoundIndex : previousLowerRoundIndex !== currentLowerRoundIndex;
1803
+ const isLowerSpanEnd = isLastSubColumnInMasterColumn ? isLastLowerRound || calculateLowerRoundIndex((lowerRoundIndex + 1) * columnSplitFactor, columnSplitFactor) !== currentLowerRoundIndex : nextLowerRoundIndex !== currentLowerRoundIndex;
1804
+ pushUpperSubColumn(createUpperBracketSubColumn({
1805
+ round: upperRound ?? null,
1806
+ span: {
1807
+ isStart: isUpperSpanStart,
1808
+ isEnd: isUpperSpanEnd
1809
+ }
1810
+ }));
1811
+ pushUpperLowerSubColumn(createUpperLowerGapSubColumn());
1812
+ pushLowerSubColumn(createRoundBracketSubColumnRelativeToFirstRound({
1813
+ firstRound: firstLowerRound,
1814
+ round: lowerRound,
1815
+ options: resolvedOptions,
1816
+ hasReverseFinal,
1817
+ span: {
1818
+ isStart: isLowerSpanStart,
1819
+ isEnd: isLowerSpanEnd
1820
+ },
1821
+ components
1822
+ }));
1823
+ if (isLastSubColumnInMasterColumn) {
1824
+ lastRoundLastSubColumnUpperIndex = currentUpperRoundIndex;
1825
+ lastRoundLastSubColumnLowerIndex = currentLowerRoundIndex;
1826
+ }
1827
+ }
1828
+ pushSectionTitleBand(pushSection);
1829
+ pushSection(upperSection, upperLowerGapSection, lowerSection);
1830
+ grid.pushMasterColumn(masterColumn);
1831
+ if (!isLastLowerRound || remainingRounds.length) grid.pushMasterColumn(createBracketGapMasterColumn({
1832
+ existingMasterColumns: grid.grid.masterColumns,
1833
+ columnGap: options.columnGap
1834
+ }));
1835
+ }
1836
+ for (const [roundIndex, round] of remainingRounds.entries()) {
1837
+ const isLastRound = roundIndex === remainingRounds.length - 1;
1838
+ const isFirstRound = roundIndex === 0;
1839
+ const isAnyFinal = hasReverseFinal ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;
1840
+ const { masterColumn, pushSection } = createBracketMasterColumn({
1841
+ columnWidth: isAnyFinal ? options.finalColumnWidth : options.columnWidth,
1842
+ padding: {
1843
+ bottom: 0,
1844
+ left: 0,
1845
+ right: 0,
1846
+ top: 0
1847
+ }
1848
+ });
1849
+ const { masterColumnSection: upperSection, pushSubColumn: pushUpperSubColumn } = createBracketMasterColumnSection({ type: "round" });
1850
+ const finalOffset = finalOffsets.get(round.id) ?? 0;
1851
+ const { masterColumnSection: upperLowerGapSection, pushSubColumn: pushUpperLowerSubColumn } = createBracketMasterColumnSection({
1852
+ type: "gap",
1853
+ padding: finalOffset ? {
1854
+ top: -finalOffset,
1855
+ bottom: 0,
1856
+ left: 0,
1857
+ right: 0
1858
+ } : void 0
1859
+ });
1860
+ const { masterColumnSection: lowerSection, pushSubColumn: pushLowerSubColumn } = createBracketMasterColumnSection({ type: "round" });
1861
+ pushUpperSubColumn(createRoundBracketSubColumnRelativeToFirstRound({
1862
+ firstRound: firstUpperRound,
1863
+ round,
1864
+ options: resolvedOptions,
1865
+ hasReverseFinal,
1866
+ span: {
1867
+ isStart: true,
1868
+ isEnd: true
1869
+ },
1870
+ components,
1871
+ topPadding: finalOffset
1872
+ }));
1873
+ const upperLowerGapSubColumn = createBracketSubColumn({ span: {
1874
+ isStart: true,
1875
+ isEnd: true
1876
+ } });
1877
+ const upperLowerGapElement = createBracketElement({
1878
+ area: ".",
1879
+ type: "roundGap",
1880
+ elementHeight: options.rowRoundGap + titleSpace,
1881
+ partHeights: [options.rowRoundGap + titleSpace]
1882
+ });
1883
+ upperLowerGapSubColumn.pushElement(upperLowerGapElement);
1884
+ pushUpperLowerSubColumn(upperLowerGapSubColumn.subColumn);
1885
+ if (thirdPlaceRound) pushLowerSubColumn(createRoundBracketSubColumnRelativeToFirstRound({
1886
+ firstRound: firstLowerRound,
1887
+ round: thirdPlaceRound,
1888
+ options: resolvedOptions,
1889
+ hasReverseFinal,
1890
+ span: {
1891
+ isStart: isFirstRound,
1892
+ isEnd: isLastRound
1893
+ },
1894
+ components
1895
+ }));
1896
+ else {
1897
+ const lowerSubColumn = createBracketSubColumn({ span: {
1898
+ isStart: true,
1899
+ isEnd: true
1900
+ } });
1901
+ const firstMasterRound = grid.grid.masterColumns[0];
1902
+ if (!firstMasterRound) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No first master round found in grid");
1903
+ const lastMasterColumnSection = firstMasterRound.sections[firstMasterRound.sections.length - 1];
1904
+ if (!lastMasterColumnSection) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No last master column section found in grid");
1905
+ const firstSubColumn = lastMasterColumnSection.subColumns[0];
1906
+ if (!firstSubColumn) throw new BracketRuntimeError(BRACKET_ERROR_CODES.GRID_INVALID, "No first sub column found in grid");
1907
+ for (const element of firstSubColumn.elements) {
1908
+ const el = createBracketElement({
1909
+ area: ".",
1910
+ type: "colGap",
1911
+ elementHeight: element.dimensions.height,
1912
+ partHeights: element.parts.map((p) => p.dimensions.height)
1913
+ });
1914
+ lowerSubColumn.pushElement(el);
1915
+ }
1916
+ pushLowerSubColumn(lowerSubColumn.subColumn);
1917
+ }
1918
+ pushSectionTitleBand(pushSection);
1919
+ pushSection(upperSection, upperLowerGapSection, lowerSection);
1920
+ grid.pushMasterColumn(masterColumn);
1921
+ if (!isLastRound) grid.pushMasterColumn(createBracketGapMasterColumn({
1922
+ existingMasterColumns: grid.grid.masterColumns,
1923
+ columnGap: options.columnGap
1924
+ }));
1925
+ }
1926
+ if (options.continueElement && components.continue) {
1927
+ const continueMatches = getBracketContinueMatches(bracketData);
1928
+ if (continueMatches.length) {
1929
+ grid.pushMasterColumn(createBracketGapMasterColumn({
1930
+ existingMasterColumns: grid.grid.masterColumns,
1931
+ columnGap: options.columnGap
1932
+ }));
1933
+ grid.pushMasterColumn(createBracketContinueMasterColumn({
1934
+ existingMasterColumns: grid.grid.masterColumns,
1935
+ columnWidth: options.continueElement.columnWidth,
1936
+ elementHeight: options.continueElement.elementHeight,
1937
+ headerOffset: titleSpace + (options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0),
1938
+ component: components.continue,
1939
+ matches: continueMatches
1940
+ }));
1941
+ }
1942
+ }
1943
+ grid.setupElementSpans();
1944
+ grid.calculateDimensions();
1945
+ const finalizedGrid = finalizeBracketGrid(grid);
1946
+ const [upperRows, lowerRows] = grid.grid.masterColumns[0]?.sections.filter((section) => section.type === "round") ?? [];
1947
+ return {
1948
+ raw: grid,
1949
+ columns: finalizedGrid.columns,
1950
+ matchElementMap: finalizedGrid.elementMap,
1951
+ sections: createBracketGridSections({
1952
+ columns: finalizedGrid.columns,
1953
+ sectionOf: doubleEliminationRoundSection,
1954
+ titleHeight: options.sectionTitleHeight ?? 0,
1955
+ titleGap: options.sectionTitleGap,
1956
+ tops: {
1957
+ upper: upperRows?.dimensions.top,
1958
+ lower: lowerRows?.dimensions.top,
1959
+ finals: upperRows?.dimensions.top
1960
+ }
1961
+ })
1962
+ };
1963
+ };
1964
+ const CENTRE_CHAIN_ORDER = {
1965
+ final: 1,
1966
+ "reverse-final": 2,
1967
+ "third-place": 3
1968
+ };
1969
+ const isFinalMatchRound = (round, hasReverseFinal) => hasReverseFinal ? round.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL : round.type === COMMON_BRACKET_ROUND_TYPE.FINAL;
1970
+ const chainRoundHeight = (config) => {
1971
+ const { round, options, hasReverseFinal } = config;
1972
+ const cardHeight = isFinalMatchRound(round, hasReverseFinal) ? options.finalMatchHeight : options.matchHeight;
1973
+ return round.matchCount * cardHeight + Math.max(0, round.matchCount - 1) * options.rowGap;
1974
+ };
1975
+ const createStackedBlock = (config) => {
1976
+ const { rounds, hasReverseFinal } = config;
1977
+ const options = resolveBracketGridRowSpan({ rounds }, config.options);
1978
+ const halves = rounds.filter((round) => !!round.mirrorRoundType);
1979
+ const left = halves.filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT).sort((a, b) => a.logicalIndex - b.logicalIndex);
1980
+ const right = halves.filter((round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT).sort((a, b) => b.logicalIndex - a.logicalIndex);
1981
+ const middles = rounds.filter((round) => !round.mirrorRoundType).sort((a, b) => (CENTRE_CHAIN_ORDER[a.type] ?? 0) - (CENTRE_CHAIN_ORDER[b.type] ?? 0) || a.logicalIndex - b.logicalIndex);
1982
+ const foldDepth = left.length ? Math.max(...left.map((round) => round.logicalIndex)) + 1 : 0;
1983
+ const isEarly = (round) => !CENTRE_CHAIN_ORDER[round.type] && round.logicalIndex < foldDepth;
1984
+ const leftSlots = [...left, ...middles.filter(isEarly)].sort((a, b) => a.logicalIndex - b.logicalIndex);
1985
+ const chain = middles.filter((round) => !isEarly(round));
1986
+ const firstRound = leftSlots[0] ?? chain[0];
1987
+ if (!firstRound) return null;
1988
+ const rows = options.rowSpanMatchCount ?? firstRound.matchCount;
1989
+ const rowsHeight = (count) => count * options.matchHeight + Math.max(0, count - 1) * options.rowGap;
1990
+ const content = rowsHeight(rows);
1991
+ const columnContent = (round) => rowsHeight(Math.max(rows, round.matchCount));
1992
+ let chainHeight = 0;
1993
+ for (const [index, round] of chain.entries()) chainHeight += (index ? options.rowRoundGap : 0) + chainRoundHeight({
1994
+ round,
1995
+ options,
1996
+ hasReverseFinal
1997
+ });
1998
+ const anchorHeight = chain[0] ? chainRoundHeight({
1999
+ round: chain[0],
2000
+ options,
2001
+ hasReverseFinal
2002
+ }) : 0;
2003
+ const spacerTop = Math.max(0, (content - anchorHeight) / 2);
2004
+ const body = Math.max(spacerTop + chainHeight, ...[...leftSlots, ...right].map(columnContent));
2005
+ return {
2006
+ firstRound,
2007
+ left: leftSlots,
2008
+ right,
2009
+ chain,
2010
+ options,
2011
+ body,
2012
+ columnContent,
2013
+ spacerTop,
2014
+ spacerBottom: Math.max(0, body - spacerTop - chainHeight)
2015
+ };
2016
+ };
2017
+ const createStackedDoubleEliminationGrid = (bracketData, options, components) => {
2018
+ const grid = createBracketGrid({ spanElementWidth: options.columnWidth });
2019
+ const roundsOfType = (type) => Array.from(bracketData.roundsByType.get(type)?.values() ?? []);
2020
+ const hasReverseFinal = !!roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL).length;
2021
+ const winners = createStackedBlock({
2022
+ rounds: [
2023
+ ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET),
2024
+ ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.FINAL),
2025
+ ...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL)
2026
+ ],
2027
+ options,
2028
+ hasReverseFinal
2029
+ });
2030
+ const losers = createStackedBlock({
2031
+ rounds: [...roundsOfType(DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET), ...roundsOfType(COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE)],
2032
+ options,
2033
+ hasReverseFinal
2034
+ });
2035
+ if (!winners || !losers) return createSingleEliminationGrid(bracketData, options, components);
2036
+ const blocks = [winners, losers];
2037
+ const headerBlock = options.roundHeaderHeight > 0 ? options.roundHeaderHeight + options.roundHeaderGap : 0;
2038
+ const blockHeight = (block) => headerBlock + block.body;
2039
+ const centreIndex = Math.max(...blocks.map((block) => block.left.length));
2040
+ const columnCount = centreIndex + 1 + Math.max(...blocks.map((block) => block.right.length));
2041
+ const createPlaceholderSubColumn = (block) => {
2042
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
2043
+ isStart: true,
2044
+ isEnd: true
2045
+ } });
2046
+ const height = blockHeight(block);
2047
+ pushElement(createBracketElement({
2048
+ area: ".",
2049
+ type: "colGap",
2050
+ elementHeight: height,
2051
+ partHeights: [height]
2052
+ }));
2053
+ return subColumn;
2054
+ };
2055
+ const createChainSubColumn = (block) => {
2056
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
2057
+ isStart: true,
2058
+ isEnd: true
2059
+ } });
2060
+ const anchor = block.chain[0];
2061
+ if (!anchor) return createPlaceholderSubColumn(block);
2062
+ const elementsToCreate = [];
2063
+ if (options.roundHeaderHeight > 0) elementsToCreate.push({
2064
+ type: "header",
2065
+ area: `h${anchor.shortId}`,
2066
+ partHeights: [options.roundHeaderHeight],
2067
+ elementHeight: options.roundHeaderHeight,
2068
+ component: components.roundHeader,
2069
+ round: anchor,
2070
+ roundSwissGroup: null
2071
+ }, {
2072
+ type: "roundHeaderGap",
2073
+ area: ".",
2074
+ partHeights: [options.roundHeaderGap],
2075
+ elementHeight: options.roundHeaderGap
2076
+ });
2077
+ if (block.spacerTop > 0) elementsToCreate.push({
2078
+ type: "colGap",
2079
+ area: ".",
2080
+ partHeights: [block.spacerTop],
2081
+ elementHeight: block.spacerTop
2082
+ });
2083
+ for (const [roundIndex, round] of block.chain.entries()) {
2084
+ if (roundIndex) elementsToCreate.push({
2085
+ type: "roundGap",
2086
+ area: ".",
2087
+ partHeights: [options.rowRoundGap],
2088
+ elementHeight: options.rowRoundGap
2089
+ });
2090
+ const isFinalCard = isFinalMatchRound(round, hasReverseFinal);
2091
+ const cardHeight = isFinalCard ? options.finalMatchHeight : options.matchHeight;
2092
+ for (const [matchIndex, match] of Array.from(round.matches.values()).entries()) {
2093
+ if (matchIndex) elementsToCreate.push({
2094
+ type: "matchGap",
2095
+ area: ".",
2096
+ partHeights: [options.rowGap],
2097
+ elementHeight: options.rowGap
2098
+ });
2099
+ elementsToCreate.push({
2100
+ type: "match",
2101
+ area: `m${match.shortId}`,
2102
+ partHeights: [cardHeight],
2103
+ elementHeight: cardHeight,
2104
+ component: isFinalCard ? components.finalMatch : components.match,
2105
+ match,
2106
+ round,
2107
+ roundSwissGroup: null
2108
+ });
2109
+ }
2110
+ }
2111
+ if (block.spacerBottom > 0) elementsToCreate.push({
2112
+ type: "colGap",
2113
+ area: ".",
2114
+ partHeights: [block.spacerBottom],
2115
+ elementHeight: block.spacerBottom
2116
+ });
2117
+ for (const elementData of elementsToCreate) pushElement(createBracketElement(elementData));
2118
+ return subColumn;
2119
+ };
2120
+ const createBlockSubColumn = (block, columnIndex) => {
2121
+ const slotIndex = columnIndex - (centreIndex - block.left.length);
2122
+ if (slotIndex === block.left.length) return createChainSubColumn(block);
2123
+ const round = slotIndex >= 0 && slotIndex < block.left.length ? block.left[slotIndex] : block.right[slotIndex - block.left.length - 1];
2124
+ if (!round) return createPlaceholderSubColumn(block);
2125
+ return createRoundBracketSubColumnRelativeToFirstRound({
2126
+ firstRound: block.firstRound,
2127
+ round,
2128
+ options: block.options,
2129
+ hasReverseFinal,
2130
+ bottomPadding: block.body - block.columnContent(round),
2131
+ span: {
2132
+ isStart: true,
2133
+ isEnd: true
2134
+ },
2135
+ components
2136
+ });
2137
+ };
2138
+ const createBandSubColumn = () => {
2139
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
2140
+ isStart: true,
2141
+ isEnd: true
2142
+ } });
2143
+ pushElement(createBracketElement({
2144
+ area: ".",
2145
+ type: "roundGap",
2146
+ elementHeight: options.rowRoundGap,
2147
+ partHeights: [options.rowRoundGap]
2148
+ }));
2149
+ return subColumn;
2150
+ };
2151
+ for (let columnIndex = 0; columnIndex < columnCount; columnIndex++) {
2152
+ const { masterColumn, pushSection } = createBracketMasterColumn({
2153
+ columnWidth: columnIndex === centreIndex ? options.finalColumnWidth : options.columnWidth,
2154
+ padding: {
2155
+ bottom: 0,
2156
+ left: 0,
2157
+ right: 0,
2158
+ top: 0
2159
+ }
2160
+ });
2161
+ const winnersSection = createBracketMasterColumnSection({ type: "round" });
2162
+ const bandSection = createBracketMasterColumnSection({ type: "gap" });
2163
+ const losersSection = createBracketMasterColumnSection({ type: "round" });
2164
+ winnersSection.pushSubColumn(createBlockSubColumn(winners, columnIndex));
2165
+ bandSection.pushSubColumn(createBandSubColumn());
2166
+ losersSection.pushSubColumn(createBlockSubColumn(losers, columnIndex));
2167
+ pushSection(winnersSection.masterColumnSection, bandSection.masterColumnSection, losersSection.masterColumnSection);
2168
+ grid.pushMasterColumn(masterColumn);
2169
+ if (columnIndex < columnCount - 1) grid.pushMasterColumn(createBracketGapMasterColumn({
2170
+ existingMasterColumns: grid.grid.masterColumns,
2171
+ columnGap: options.columnGap
2172
+ }));
2173
+ }
2174
+ grid.calculateDimensions();
2175
+ const finalizedGrid = finalizeBracketGrid(grid);
2176
+ return {
2177
+ raw: grid,
2178
+ columns: finalizedGrid.columns,
2179
+ matchElementMap: finalizedGrid.elementMap
2180
+ };
2181
+ };
2182
+ const FALLBACK_MATCH_RELATION_POSITION = -1;
2183
+ const generateMatchPosition = (match, factor) => Math.ceil(match.position * factor);
2184
+ const generatePreviousRoundMatchPositions = (relation, match) => {
2185
+ const feederFactor = relation.currentRound.matchCount / relation.previousRound.matchCount;
2186
+ const feederPositions = [];
2187
+ for (const feeder of relation.previousRound.matches.values()) if (generateMatchPosition(feeder, feederFactor) === match.position) feederPositions.push(feeder.position);
2188
+ const first = feederPositions[0];
2189
+ const last = feederPositions[feederPositions.length - 1];
2190
+ if (first !== void 0 && last !== void 0) return {
2191
+ previousUpperRoundMatchPosition: first,
2192
+ previousLowerRoundMatchPosition: last
2193
+ };
2194
+ const double = relation.previousRoundMatchFactor === 2 ? 1 : 0;
2195
+ return {
2196
+ previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousRoundMatchFactor) - double,
2197
+ previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousRoundMatchFactor)
2198
+ };
2199
+ };
2200
+ const generateMatchRelationPositions = (relation, match) => {
2201
+ switch (relation.type) {
2202
+ case "none": return null;
2203
+ case "nothing-to-one": return {
2204
+ nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),
2205
+ previousUpperRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,
2206
+ previousLowerRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION
2207
+ };
2208
+ case "one-to-nothing": return {
2209
+ nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,
2210
+ ...generatePreviousRoundMatchPositions(relation, match)
2211
+ };
2212
+ case "one-to-one": return {
2213
+ nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),
2214
+ ...generatePreviousRoundMatchPositions(relation, match)
2215
+ };
2216
+ case "two-to-one": return {
2217
+ nextRoundMatchPosition: generateMatchPosition(match, relation.nextRoundMatchFactor),
2218
+ previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),
2219
+ previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor)
2220
+ };
2221
+ case "two-to-nothing": return {
2222
+ nextRoundMatchPosition: FALLBACK_MATCH_RELATION_POSITION,
2223
+ previousUpperRoundMatchPosition: generateMatchPosition(match, relation.previousUpperRoundMatchFactor),
2224
+ previousLowerRoundMatchPosition: generateMatchPosition(match, relation.previousLowerRoundMatchFactor)
2225
+ };
2226
+ }
2227
+ };
2228
+ const relationMatchNotFound = (options) => new BracketRuntimeError(BRACKET_ERROR_CODES.MATCH_RELATION_INVALID, `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.`);
2229
+ const createNothingToOneRelation$1 = (params) => {
2230
+ const { match, relation, matchPositionMaps, nextRoundMatchPosition } = params;
2231
+ const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);
2232
+ if (!nextMatch) throw relationMatchNotFound({
2233
+ match,
2234
+ feeder: "next",
2235
+ round: relation.nextRound,
2236
+ position: nextRoundMatchPosition
2237
+ });
2238
+ return {
2239
+ type: "nothing-to-one",
2240
+ currentMatch: match,
2241
+ currentRound: relation.currentRound,
2242
+ nextMatch,
2243
+ nextRound: relation.nextRound
2244
+ };
2245
+ };
2246
+ const createOneToNothingOrTwoToNothingRelation = (params) => {
2247
+ const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = params;
2248
+ const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);
2249
+ const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);
2250
+ if (!previousUpperMatch) throw relationMatchNotFound({
2251
+ match,
2252
+ feeder: "previous",
2253
+ round: relation.previousRound,
2254
+ position: previousUpperRoundMatchPosition
2255
+ });
2256
+ if (previousUpperRoundMatchPosition !== previousLowerRoundMatchPosition) {
2257
+ if (!previousLowerMatch) throw relationMatchNotFound({
2258
+ match,
2259
+ feeder: "previous lower",
2260
+ round: relation.previousRound,
2261
+ position: previousLowerRoundMatchPosition
2262
+ });
2263
+ return {
2264
+ type: "two-to-nothing",
2265
+ currentMatch: match,
2266
+ currentRound: relation.currentRound,
2267
+ previousUpperMatch,
2268
+ previousUpperRound: relation.previousRound,
2269
+ previousLowerMatch,
2270
+ previousLowerRound: relation.previousRound
2271
+ };
2272
+ } else return {
2273
+ type: "one-to-nothing",
2274
+ currentMatch: match,
2275
+ currentRound: relation.currentRound,
2276
+ previousMatch: previousUpperMatch,
2277
+ previousRound: relation.previousRound
2278
+ };
2279
+ };
2280
+ const createOneToOneOrTwoToOneRelation = (params) => {
2281
+ const { match, relation, matchPositionMaps, nextRoundMatchPosition, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = params;
2282
+ const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);
2283
+ const previousUpperMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousUpperRoundMatchPosition);
2284
+ const previousLowerMatch = matchPositionMaps.get(relation.previousRound.id)?.get(previousLowerRoundMatchPosition);
2285
+ if (!nextMatch) throw relationMatchNotFound({
2286
+ match,
2287
+ feeder: "next",
2288
+ round: relation.nextRound,
2289
+ position: nextRoundMatchPosition
2290
+ });
2291
+ if (!previousUpperMatch) throw relationMatchNotFound({
2292
+ match,
2293
+ feeder: "previous upper",
2294
+ round: relation.previousRound,
2295
+ position: previousUpperRoundMatchPosition
2296
+ });
2297
+ if (!previousLowerMatch) throw relationMatchNotFound({
2298
+ match,
2299
+ feeder: "previous lower",
2300
+ round: relation.previousRound,
2301
+ position: previousLowerRoundMatchPosition
2302
+ });
2303
+ if (previousUpperRoundMatchPosition === previousLowerRoundMatchPosition) return {
2304
+ type: "one-to-one",
2305
+ currentMatch: match,
2306
+ currentRound: relation.currentRound,
2307
+ previousMatch: previousUpperMatch,
2308
+ previousRound: relation.previousRound,
2309
+ nextMatch,
2310
+ nextRound: relation.nextRound
2311
+ };
2312
+ else return {
2313
+ type: "two-to-one",
2314
+ currentMatch: match,
2315
+ currentRound: relation.currentRound,
2316
+ previousUpperMatch,
2317
+ previousUpperRound: relation.previousRound,
2318
+ previousLowerMatch,
2319
+ previousLowerRound: relation.previousRound,
2320
+ nextMatch,
2321
+ nextRound: relation.nextRound
2322
+ };
2323
+ };
2324
+ const createTwoToOneRelation$1 = (params) => {
2325
+ const { match, relation, matchPositionMaps, nextRoundMatchPosition, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = params;
2326
+ const nextMatch = matchPositionMaps.get(relation.nextRound.id)?.get(nextRoundMatchPosition);
2327
+ const previousUpperMatch = matchPositionMaps.get(relation.previousUpperRound.id)?.get(previousUpperRoundMatchPosition);
2328
+ const previousLowerMatch = matchPositionMaps.get(relation.previousLowerRound.id)?.get(previousLowerRoundMatchPosition);
2329
+ if (!nextMatch) throw relationMatchNotFound({
2330
+ match,
2331
+ feeder: "next",
2332
+ round: relation.nextRound,
2333
+ position: nextRoundMatchPosition
2334
+ });
2335
+ if (!previousUpperMatch) throw relationMatchNotFound({
2336
+ match,
2337
+ feeder: "previous upper",
2338
+ round: relation.previousUpperRound,
2339
+ position: previousUpperRoundMatchPosition
2340
+ });
2341
+ if (!previousLowerMatch) throw relationMatchNotFound({
2342
+ match,
2343
+ feeder: "previous lower",
2344
+ round: relation.previousLowerRound,
2345
+ position: previousLowerRoundMatchPosition
2346
+ });
2347
+ return {
2348
+ type: "two-to-one",
2349
+ currentMatch: match,
2350
+ currentRound: relation.currentRound,
2351
+ previousUpperMatch,
2352
+ previousUpperRound: relation.previousUpperRound,
2353
+ previousLowerMatch,
2354
+ previousLowerRound: relation.previousLowerRound,
2355
+ nextMatch,
2356
+ nextRound: relation.nextRound
2357
+ };
2358
+ };
2359
+ const createTwoToNothingRelation$1 = (params) => {
2360
+ const { match, relation, matchPositionMaps, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = params;
2361
+ const previousUpperMatch = matchPositionMaps.get(relation.previousUpperRound.id)?.get(previousUpperRoundMatchPosition);
2362
+ const previousLowerMatch = matchPositionMaps.get(relation.previousLowerRound.id)?.get(previousLowerRoundMatchPosition);
2363
+ if (!previousUpperMatch) throw relationMatchNotFound({
2364
+ match,
2365
+ feeder: "previous upper",
2366
+ round: relation.previousUpperRound,
2367
+ position: previousUpperRoundMatchPosition
2368
+ });
2369
+ if (!previousLowerMatch) throw relationMatchNotFound({
2370
+ match,
2371
+ feeder: "previous lower",
2372
+ round: relation.previousLowerRound,
2373
+ position: previousLowerRoundMatchPosition
2374
+ });
2375
+ return {
2376
+ type: "two-to-nothing",
2377
+ currentMatch: match,
2378
+ currentRound: relation.currentRound,
2379
+ previousUpperMatch,
2380
+ previousUpperRound: relation.previousUpperRound,
2381
+ previousLowerMatch,
2382
+ previousLowerRound: relation.previousLowerRound
2383
+ };
2384
+ };
2385
+ const generateMatchRelationsNew = (bracketData, options = {}) => {
2386
+ const sourceMatches = options.source?.matches ?? [];
2387
+ if (options.previousMatchIds !== void 0 || sourceMatches.some((match) => matchOutcomeSlots(match).length > 0)) return generateDeclaredMatchRelations({
2388
+ bracket: bracketData,
2389
+ sourceMatches,
2390
+ previousMatchIds: options.previousMatchIds ?? defaultPreviousMatchIds,
2391
+ onWarning: options.onWarning
2392
+ });
2393
+ const matchRelations = [];
2394
+ const matchPositionMaps = /* @__PURE__ */ new Map();
2395
+ for (const round of bracketData.rounds.values()) {
2396
+ const matchMap = new Map([...round.matches.values()].map((m) => [m.position, m]));
2397
+ matchPositionMaps.set(round.id, matchMap);
2398
+ }
2399
+ for (const match of bracketData.matches.values()) {
2400
+ const relation = match.round.relation;
2401
+ const positions = generateMatchRelationPositions(relation, match);
2402
+ if (!positions) continue;
2403
+ const { nextRoundMatchPosition, previousUpperRoundMatchPosition, previousLowerRoundMatchPosition } = positions;
2404
+ switch (relation.type) {
2405
+ case "nothing-to-one":
2406
+ matchRelations.push(createNothingToOneRelation$1({
2407
+ match,
2408
+ relation,
2409
+ matchPositionMaps,
2410
+ nextRoundMatchPosition
2411
+ }));
2412
+ break;
2413
+ case "one-to-nothing":
2414
+ matchRelations.push(createOneToNothingOrTwoToNothingRelation({
2415
+ match,
2416
+ relation,
2417
+ matchPositionMaps,
2418
+ previousUpperRoundMatchPosition,
2419
+ previousLowerRoundMatchPosition
2420
+ }));
2421
+ break;
2422
+ case "one-to-one":
2423
+ matchRelations.push(createOneToOneOrTwoToOneRelation({
2424
+ match,
2425
+ relation,
2426
+ matchPositionMaps,
2427
+ nextRoundMatchPosition,
2428
+ previousUpperRoundMatchPosition,
2429
+ previousLowerRoundMatchPosition
2430
+ }));
2431
+ break;
2432
+ case "two-to-one":
2433
+ matchRelations.push(createTwoToOneRelation$1({
2434
+ match,
2435
+ relation,
2436
+ matchPositionMaps,
2437
+ nextRoundMatchPosition,
2438
+ previousUpperRoundMatchPosition,
2439
+ previousLowerRoundMatchPosition
2440
+ }));
2441
+ break;
2442
+ case "two-to-nothing": matchRelations.push(createTwoToNothingRelation$1({
2443
+ match,
2444
+ relation,
2445
+ matchPositionMaps,
2446
+ previousUpperRoundMatchPosition,
2447
+ previousLowerRoundMatchPosition
2448
+ }));
2449
+ }
2450
+ }
2451
+ return matchRelations;
2452
+ };
2453
+ const matchOutcomeSlots = (match) => [match.homeSource, match.awaySource].filter((slot) => slot?.kind === "match-outcome" && !!slot.matchId);
2454
+ const defaultPreviousMatchIds = (match) => matchOutcomeSlots(match).filter((slot) => slot.role !== "loser").map((slot) => slot.matchId);
2455
+ const reportDeclaredGraphWarnings = (options) => {
2456
+ const { bracket, sourceMatches, previousByMatchId, onWarning } = options;
2457
+ const feederIds = /* @__PURE__ */ new Set();
2458
+ for (const match of sourceMatches) {
2459
+ const referenced = /* @__PURE__ */ new Set([...previousByMatchId.get(match.id) ?? [], ...matchOutcomeSlots(match).map((slot) => slot.matchId)]);
2460
+ for (const feederId of referenced) {
2461
+ feederIds.add(feederId);
2462
+ if (bracket.matches.has(feederId)) continue;
2463
+ onWarning({
2464
+ type: "unknown-feeder",
2465
+ matchId: match.id,
2466
+ feederId,
2467
+ message: `Match "${match.id}" is fed by "${feederId}", which is not in source.matches. The connector is not drawn.`
2468
+ });
2469
+ }
2470
+ }
2471
+ if (sourceMatches.length < 2) return;
2472
+ for (const match of sourceMatches) {
2473
+ if ((previousByMatchId.get(match.id)?.length ?? 0) > 0 || matchOutcomeSlots(match).length > 0 || [match.homeSource, match.awaySource].some((slot) => slot?.kind === "unknown") || feederIds.has(match.id)) continue;
2474
+ if (bracket.matches.get(match.id)?.round.type === COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE) continue;
2475
+ onWarning({
2476
+ type: "unlinked-match",
2477
+ matchId: match.id,
2478
+ 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.`
2479
+ });
2480
+ }
2481
+ };
2482
+ const generateDeclaredMatchRelations = (options) => {
2483
+ const { bracket, sourceMatches, previousMatchIds, onWarning } = options;
2484
+ const previousByMatchId = new Map(sourceMatches.map((match) => [match.id, previousMatchIds(match)]));
2485
+ if (onWarning) reportDeclaredGraphWarnings({
2486
+ bracket,
2487
+ sourceMatches,
2488
+ previousByMatchId,
2489
+ onWarning
2490
+ });
2491
+ const nextByMatchId = /* @__PURE__ */ new Map();
2492
+ const winnerConsumerByFeederId = /* @__PURE__ */ new Map();
2493
+ for (const match of sourceMatches) for (const slot of [match.homeSource, match.awaySource]) {
2494
+ if (slot?.kind !== "match-outcome" || slot.role === "loser" || !slot.matchId) continue;
2495
+ if (!winnerConsumerByFeederId.has(slot.matchId)) winnerConsumerByFeederId.set(slot.matchId, match.id);
2496
+ }
2497
+ for (const [matchId, feederIds] of previousByMatchId) for (const feederId of feederIds) if (winnerConsumerByFeederId.get(feederId) === matchId) nextByMatchId.set(feederId, matchId);
2498
+ else if (!nextByMatchId.has(feederId)) nextByMatchId.set(feederId, matchId);
2499
+ const relations = [];
2500
+ for (const match of bracket.matches.values()) {
2501
+ const previousMatches = (previousByMatchId.get(match.id) ?? []).map((id) => bracket.matches.get(id)).filter((candidate) => candidate !== void 0);
2502
+ const nextMatchId = nextByMatchId.get(match.id);
2503
+ const nextMatch = nextMatchId ? bracket.matches.get(nextMatchId) : void 0;
2504
+ if (previousMatches.length === 0 && nextMatch) relations.push({
2505
+ type: "nothing-to-one",
2506
+ currentMatch: match,
2507
+ currentRound: match.round,
2508
+ nextMatch,
2509
+ nextRound: nextMatch.round
2510
+ });
2511
+ else if (previousMatches.length === 1 && nextMatch) {
2512
+ const previousMatch = previousMatches[0];
2513
+ if (!previousMatch) continue;
2514
+ relations.push({
2515
+ type: "one-to-one",
2516
+ currentMatch: match,
2517
+ currentRound: match.round,
2518
+ previousMatch,
2519
+ previousRound: previousMatch.round,
2520
+ nextMatch,
2521
+ nextRound: nextMatch.round
2522
+ });
2523
+ } else if (previousMatches.length >= 2 && nextMatch) {
2524
+ const previousUpperMatch = previousMatches[0];
2525
+ const previousLowerMatch = previousMatches[1];
2526
+ if (!previousUpperMatch || !previousLowerMatch) continue;
2527
+ relations.push({
2528
+ type: "two-to-one",
2529
+ currentMatch: match,
2530
+ currentRound: match.round,
2531
+ previousUpperMatch,
2532
+ previousUpperRound: previousUpperMatch.round,
2533
+ previousLowerMatch,
2534
+ previousLowerRound: previousLowerMatch.round,
2535
+ nextMatch,
2536
+ nextRound: nextMatch.round
2537
+ });
2538
+ } else if (previousMatches.length === 1) {
2539
+ const previousMatch = previousMatches[0];
2540
+ if (!previousMatch) continue;
2541
+ relations.push({
2542
+ type: "one-to-nothing",
2543
+ currentMatch: match,
2544
+ currentRound: match.round,
2545
+ previousMatch,
2546
+ previousRound: previousMatch.round
2547
+ });
2548
+ } else if (previousMatches.length >= 2) {
2549
+ const previousUpperMatch = previousMatches[0];
2550
+ const previousLowerMatch = previousMatches[1];
2551
+ if (!previousUpperMatch || !previousLowerMatch) continue;
2552
+ relations.push({
2553
+ type: "two-to-nothing",
2554
+ currentMatch: match,
2555
+ currentRound: match.round,
2556
+ previousUpperMatch,
2557
+ previousUpperRound: previousUpperMatch.round,
2558
+ previousLowerMatch,
2559
+ previousLowerRound: previousLowerMatch.round
2560
+ });
2561
+ }
2562
+ }
2563
+ return relations;
2564
+ };
2565
+ const calculateMatchFactor = (numeratorRound, denominatorRound) => numeratorRound.matchCount / denominatorRound.matchCount;
2566
+ const createNothingToOneRelation = (params) => ({
2567
+ type: "nothing-to-one",
2568
+ currentRound: params.currentRound,
2569
+ nextRound: params.nextRound,
2570
+ nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound)
2571
+ });
2572
+ const createOneToNothingRelation = (params) => ({
2573
+ type: "one-to-nothing",
2574
+ currentRound: params.currentRound,
2575
+ previousRound: params.previousRound,
2576
+ previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),
2577
+ rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound)
2578
+ });
2579
+ const createOneToOneRelation = (params) => ({
2580
+ type: "one-to-one",
2581
+ currentRound: params.currentRound,
2582
+ previousRound: params.previousRound,
2583
+ nextRound: params.nextRound,
2584
+ nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),
2585
+ previousRoundMatchFactor: calculateMatchFactor(params.previousRound, params.currentRound),
2586
+ rootRoundMatchFactor: calculateMatchFactor(params.rootRound, params.currentRound)
2587
+ });
2588
+ const createTwoToOneRelation = (params) => ({
2589
+ type: "two-to-one",
2590
+ currentRound: params.currentRound,
2591
+ previousUpperRound: params.previousUpperRound,
2592
+ previousLowerRound: params.previousLowerRound,
2593
+ nextRound: params.nextRound,
2594
+ nextRoundMatchFactor: calculateMatchFactor(params.nextRound, params.currentRound),
2595
+ previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),
2596
+ previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),
2597
+ upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),
2598
+ lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound)
2599
+ });
2600
+ const createTwoToNothingRelation = (params) => ({
2601
+ type: "two-to-nothing",
2602
+ currentRound: params.currentRound,
2603
+ previousUpperRound: params.previousUpperRound,
2604
+ previousLowerRound: params.previousLowerRound,
2605
+ previousUpperRoundMatchFactor: calculateMatchFactor(params.previousUpperRound, params.currentRound),
2606
+ previousLowerRoundMatchFactor: calculateMatchFactor(params.previousLowerRound, params.currentRound),
2607
+ upperRootRoundMatchFactor: calculateMatchFactor(params.firstUpperRound, params.currentRound),
2608
+ lowerRootRoundMatchFactor: calculateMatchFactor(params.firstLowerRound, params.currentRound)
2609
+ });
2610
+ const isFoldedBackRound = (round) => round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT;
2611
+ const buildRoundsByDepth = (rounds) => {
2612
+ const byDepth = /* @__PURE__ */ new Map();
2613
+ for (const round of rounds) {
2614
+ const slot = byDepth.get(round.logicalIndex) ?? {
2615
+ left: null,
2616
+ right: null,
2617
+ single: null
2618
+ };
2619
+ if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT) slot.left = round;
2620
+ else if (round.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT) slot.right = round;
2621
+ else slot.single = round;
2622
+ byDepth.set(round.logicalIndex, slot);
2623
+ }
2624
+ return byDepth;
2625
+ };
2626
+ const roundAtDepth = (params) => {
2627
+ const slot = params.byDepth.get(params.depth);
2628
+ if (!slot) return null;
2629
+ return (params.side === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? slot.right : slot.left) ?? slot.single ?? null;
2630
+ };
2631
+ const getNavigationContext = (params) => {
2632
+ const { upperRounds, upperRoundsByDepth, currentUpperRoundIndex } = params;
2633
+ const currentUpperRound = upperRounds[currentUpperRoundIndex];
2634
+ if (!currentUpperRound) throw new BracketRuntimeError(BRACKET_ERROR_CODES.ROUND_RELATION_INVALID, "currentUpperRound is null");
2635
+ const isLeftToRight = !currentUpperRound.mirrorRoundType || currentUpperRound.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.LEFT;
2636
+ const isFolded = !!currentUpperRound.mirrorRoundType;
2637
+ const side = currentUpperRound.mirrorRoundType;
2638
+ const depth = currentUpperRound.logicalIndex;
2639
+ const relativePrevious = isFolded ? roundAtDepth({
2640
+ byDepth: upperRoundsByDepth,
2641
+ depth: depth - 1,
2642
+ side
2643
+ }) : upperRounds[currentUpperRoundIndex - 1] || null;
2644
+ const relativeNext = isFolded ? roundAtDepth({
2645
+ byDepth: upperRoundsByDepth,
2646
+ depth: depth + 1,
2647
+ side
2648
+ }) : upperRounds[currentUpperRoundIndex + 1] || null;
2649
+ const previousUpperRound = isFolded || isLeftToRight ? relativePrevious : relativeNext;
2650
+ const flowNext = isFolded || isLeftToRight ? relativeNext : relativePrevious;
2651
+ const nextUpperRound = !isFolded && flowNext?.mirrorRoundType === BRACKET_ROUND_MIRROR_TYPE.RIGHT ? null : flowNext;
2652
+ return {
2653
+ currentUpperRound,
2654
+ previousUpperRound,
2655
+ nextUpperRound,
2656
+ isLastUpperRound: !nextUpperRound,
2657
+ isFinal: currentUpperRound.type === COMMON_BRACKET_ROUND_TYPE.FINAL
2658
+ };
2659
+ };
2660
+ const handleFinalRound = (params) => {
2661
+ const { relations, currentUpperRound, previousUpperRound, nextUpperRound, lowerRounds, firstUpperRound, firstLowerRound, lastLowerRound } = params;
2662
+ const finalLowerRound = lastLowerRound;
2663
+ const isAsyncBracket = nextUpperRound?.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL;
2664
+ if (nextUpperRound) relations.push(createTwoToOneRelation({
2665
+ currentRound: currentUpperRound,
2666
+ previousUpperRound,
2667
+ previousLowerRound: finalLowerRound,
2668
+ nextRound: nextUpperRound,
2669
+ firstUpperRound,
2670
+ firstLowerRound
2671
+ }));
2672
+ else relations.push(createTwoToNothingRelation({
2673
+ currentRound: currentUpperRound,
2674
+ previousUpperRound,
2675
+ previousLowerRound: finalLowerRound,
2676
+ firstUpperRound,
2677
+ firstLowerRound
2678
+ }));
2679
+ const preFinalLowerRound = lowerRounds[lowerRounds.length - 2] || null;
2680
+ if (!preFinalLowerRound) {
2681
+ relations.push(createNothingToOneRelation({
2682
+ currentRound: finalLowerRound,
2683
+ nextRound: currentUpperRound
2684
+ }));
2685
+ return;
2686
+ }
2687
+ relations.push(createOneToOneRelation({
2688
+ currentRound: finalLowerRound,
2689
+ previousRound: preFinalLowerRound,
2690
+ nextRound: currentUpperRound,
2691
+ rootRound: firstLowerRound
2692
+ }));
2693
+ if (!isAsyncBracket) return;
2694
+ const prePreFinalLowerRound = lowerRounds[lowerRounds.length - 3] || null;
2695
+ relations.push(prePreFinalLowerRound ? createOneToOneRelation({
2696
+ currentRound: preFinalLowerRound,
2697
+ previousRound: prePreFinalLowerRound,
2698
+ nextRound: finalLowerRound,
2699
+ rootRound: firstLowerRound
2700
+ }) : createNothingToOneRelation({
2701
+ currentRound: preFinalLowerRound,
2702
+ nextRound: finalLowerRound
2703
+ }));
2704
+ };
2705
+ const handleFirstRound = (params) => {
2706
+ const { relations, currentUpperRound, nextUpperRound, lowerRounds, currentUpperRoundIndex } = params;
2707
+ relations.push(createNothingToOneRelation({
2708
+ currentRound: currentUpperRound,
2709
+ nextRound: nextUpperRound
2710
+ }));
2711
+ const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;
2712
+ const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;
2713
+ if (currentLowerRound && nextLowerRound && !isFoldedBackRound(currentUpperRound)) relations.push(createNothingToOneRelation({
2714
+ currentRound: currentLowerRound,
2715
+ nextRound: nextLowerRound
2716
+ }));
2717
+ };
2718
+ const handleRegularRound = (params) => {
2719
+ const { relations, currentUpperRound, previousUpperRound, nextUpperRound, lowerRounds, currentUpperRoundIndex, firstUpperRound, firstLowerRound } = params;
2720
+ relations.push(createOneToOneRelation({
2721
+ currentRound: currentUpperRound,
2722
+ previousRound: previousUpperRound,
2723
+ nextRound: nextUpperRound,
2724
+ rootRound: firstUpperRound
2725
+ }));
2726
+ const currentLowerRound = lowerRounds[currentUpperRoundIndex] || null;
2727
+ const previousLowerRound = lowerRounds[currentUpperRoundIndex - 1] || null;
2728
+ const nextLowerRound = lowerRounds[currentUpperRoundIndex + 1] || null;
2729
+ if (currentLowerRound && currentUpperRound.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET && previousLowerRound && nextLowerRound && firstLowerRound && !isFoldedBackRound(currentUpperRound)) relations.push(createOneToOneRelation({
2730
+ currentRound: currentLowerRound,
2731
+ previousRound: previousLowerRound,
2732
+ nextRound: nextLowerRound,
2733
+ rootRound: firstLowerRound
2734
+ }));
2735
+ };
2736
+ const generateRoundRelationsNew = (bracketData) => {
2737
+ const relations = [];
2738
+ const allRounds = [...bracketData.rounds.values()].filter((round) => round.matchCount > 0 && round.type !== COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE);
2739
+ const upperRounds = allRounds.filter((r) => r.type !== DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);
2740
+ const lowerRounds = allRounds.filter((r) => r.type === DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET);
2741
+ const upperRoundsByDepth = buildRoundsByDepth(upperRounds);
2742
+ const lowerRoundsByDepth = buildRoundsByDepth(lowerRounds);
2743
+ const lowerFlow = Array.from(lowerRoundsByDepth.keys()).sort((a, b) => a - b).map((depth) => roundAtDepth({
2744
+ byDepth: lowerRoundsByDepth,
2745
+ depth,
2746
+ side: null
2747
+ })).filter((round) => !!round);
2748
+ const firstUpperRound = upperRounds[0];
2749
+ const firstLowerRound = lowerFlow[0] || null;
2750
+ const lastLowerRound = lowerFlow[lowerFlow.length - 1] || null;
2751
+ if (allRounds.length === 0) return relations;
2752
+ const hasLowerRounds = lowerRounds.length > 0;
2753
+ if (firstUpperRound) for (const [currentUpperRoundIndex] of upperRounds.entries()) {
2754
+ const nav = getNavigationContext({
2755
+ upperRounds,
2756
+ upperRoundsByDepth,
2757
+ currentUpperRoundIndex
2758
+ });
2759
+ if (nav.isFinal && hasLowerRounds && lastLowerRound && firstLowerRound && nav.previousUpperRound) handleFinalRound({
2760
+ relations,
2761
+ currentUpperRound: nav.currentUpperRound,
2762
+ previousUpperRound: nav.previousUpperRound,
2763
+ nextUpperRound: nav.nextUpperRound,
2764
+ lowerRounds: lowerFlow,
2765
+ currentUpperRoundIndex,
2766
+ firstUpperRound,
2767
+ firstLowerRound,
2768
+ lastLowerRound
2769
+ });
2770
+ else if (nav.isLastUpperRound && nav.previousUpperRound) relations.push(createOneToNothingRelation({
2771
+ currentRound: nav.currentUpperRound,
2772
+ previousRound: nav.previousUpperRound,
2773
+ rootRound: firstUpperRound
2774
+ }));
2775
+ else if (nav.currentUpperRound.isFirstRound && nav.nextUpperRound) handleFirstRound({
2776
+ relations,
2777
+ currentUpperRound: nav.currentUpperRound,
2778
+ nextUpperRound: nav.nextUpperRound,
2779
+ lowerRounds: lowerFlow,
2780
+ currentUpperRoundIndex
2781
+ });
2782
+ else if (nav.nextUpperRound && !nav.previousUpperRound) relations.push(createNothingToOneRelation({
2783
+ currentRound: nav.currentUpperRound,
2784
+ nextRound: nav.nextUpperRound
2785
+ }));
2786
+ else if (nav.previousUpperRound && nav.nextUpperRound) handleRegularRound({
2787
+ relations,
2788
+ currentUpperRound: nav.currentUpperRound,
2789
+ previousUpperRound: nav.previousUpperRound,
2790
+ nextUpperRound: nav.nextUpperRound,
2791
+ lowerRounds: lowerFlow,
2792
+ currentUpperRoundIndex,
2793
+ firstUpperRound,
2794
+ firstLowerRound
2795
+ });
2796
+ }
2797
+ if (hasLowerRounds && firstLowerRound) {
2798
+ const assignedRoundIds = new Set(relations.map((r) => r.currentRound.id));
2799
+ for (const lowerRound of lowerRounds) {
2800
+ if (assignedRoundIds.has(lowerRound.id)) continue;
2801
+ const side = lowerRound.mirrorRoundType;
2802
+ const depth = lowerRound.logicalIndex;
2803
+ const prevLowerRound = roundAtDepth({
2804
+ byDepth: lowerRoundsByDepth,
2805
+ depth: depth - 1,
2806
+ side
2807
+ });
2808
+ const nextLowerRound = roundAtDepth({
2809
+ byDepth: lowerRoundsByDepth,
2810
+ depth: depth + 1,
2811
+ side
2812
+ });
2813
+ if (nextLowerRound) {
2814
+ if (!prevLowerRound) relations.push(createNothingToOneRelation({
2815
+ currentRound: lowerRound,
2816
+ nextRound: nextLowerRound
2817
+ }));
2818
+ else relations.push(createOneToOneRelation({
2819
+ currentRound: lowerRound,
2820
+ previousRound: prevLowerRound,
2821
+ nextRound: nextLowerRound,
2822
+ rootRound: firstLowerRound
2823
+ }));
2824
+ } else if (prevLowerRound) relations.push(createOneToNothingRelation({
2825
+ currentRound: lowerRound,
2826
+ previousRound: prevLowerRound,
2827
+ rootRound: firstLowerRound
2828
+ }));
2829
+ }
2830
+ }
2831
+ return relations;
2832
+ };
2833
+ const createBracket = (source, options) => {
2834
+ if (!source.rounds.length) throw new BracketRuntimeError(BRACKET_ERROR_CODES.SOURCE_EMPTY, "The bracket source has no rounds to render");
2835
+ const bracketNewBase = createBracketBase(source, options);
2836
+ const rounds = new BracketMap();
2837
+ const roundsByType = new BracketMap();
2838
+ for (const roundBase of bracketNewBase.rounds.values()) {
2839
+ const relation = { type: "none" };
2840
+ const newRound = {
2841
+ ...roundBase,
2842
+ matches: new BracketMap(),
2843
+ relation
2844
+ };
2845
+ relation.currentRound = newRound;
2846
+ rounds.set(roundBase.id, newRound);
2847
+ if (!roundsByType.has(roundBase.type)) roundsByType.set(roundBase.type, new BracketMap());
2848
+ roundsByType.getOrThrow(roundBase.type).set(roundBase.id, newRound);
2849
+ }
2850
+ const participants = new BracketMap();
2851
+ for (const participantBase of bracketNewBase.participants.values()) participants.set(participantBase.id, {
2852
+ ...participantBase,
2853
+ matches: new BracketMap()
2854
+ });
2855
+ const matches = new BracketMap();
2856
+ for (const matchBase of bracketNewBase.matches.values()) {
2857
+ const round = rounds.getOrThrow(matchBase.roundId);
2858
+ const homeParticipant = matchBase.home ? {
2859
+ ...matchBase.home,
2860
+ matches: new BracketMap()
2861
+ } : null;
2862
+ const awayParticipant = matchBase.away ? {
2863
+ ...matchBase.away,
2864
+ matches: new BracketMap()
2865
+ } : null;
2866
+ const relation = {
2867
+ type: "none",
2868
+ currentRound: round
2869
+ };
2870
+ const newMatch = {
2871
+ ...matchBase,
2872
+ home: homeParticipant,
2873
+ away: awayParticipant,
2874
+ winner: null,
2875
+ round,
2876
+ relation
2877
+ };
2878
+ relation.currentMatch = newMatch;
2879
+ if (matchBase.winner) {
2880
+ const winnerParticipant = homeParticipant?.id === matchBase.winner.id ? homeParticipant : awayParticipant;
2881
+ if (!winnerParticipant) throw new BracketRuntimeError(BRACKET_ERROR_CODES.WINNER_NOT_FOUND, `Winner participant with id ${matchBase.winner.id} not found in match base`);
2882
+ newMatch.winner = winnerParticipant;
2883
+ }
2884
+ matches.set(matchBase.id, newMatch);
2885
+ round.matches.set(matchBase.id, newMatch);
2886
+ }
2887
+ const newBracket = {
2888
+ matches,
2889
+ participants,
2890
+ rounds,
2891
+ roundsByType,
2892
+ mode: bracketNewBase.mode
2893
+ };
2894
+ const roundRelations = generateRoundRelationsNew(newBracket);
2895
+ for (const roundRelation of roundRelations) roundRelation.currentRound.relation = roundRelation;
2896
+ const matchRelations = generateMatchRelationsNew(newBracket, {
2897
+ source,
2898
+ previousMatchIds: options.previousMatchIds,
2899
+ onWarning: options.onWarning
2900
+ });
2901
+ for (const matchRelation of matchRelations) matchRelation.currentMatch.relation = matchRelation;
2902
+ for (const match of matches.values()) {
2903
+ if (match.home) participants.getOrThrow(match.home.id).matches.set(match.id, {
2904
+ ...match,
2905
+ me: match.home,
2906
+ opponent: match.away
2907
+ });
2908
+ if (match.away) participants.getOrThrow(match.away.id).matches.set(match.id, {
2909
+ ...match,
2910
+ me: match.away,
2911
+ opponent: match.home
2912
+ });
2913
+ }
2914
+ for (const participant of participants.values()) for (const match of participant.matches.values()) {
2915
+ if (match.home?.id === participant.id) match.home.matches = participant.matches;
2916
+ if (match.away?.id === participant.id) match.away.matches = participant.matches;
2917
+ if (match.winner?.id === participant.id) match.winner.matches = participant.matches;
2918
+ }
2919
+ return newBracket;
2920
+ };
2921
+ const isBracketSlotPredictable = (source) => source?.kind === "match-outcome" || source?.kind === "standing-rank" || source?.kind === "seed";
2922
+ const sourceFor = (match, side) => side === "home" ? match.homeSource : match.awaySource;
2923
+ const participantIdFor = (match, side) => match[side]?.id ?? null;
2924
+ const resolveMatchOutcome = (options) => {
2925
+ const { walk, source } = options;
2926
+ const feeder = walk.lookupMatch(source.matchId);
2927
+ if (!feeder) return null;
2928
+ const homeSource = sourceFor(feeder, "home");
2929
+ const awaySource = sourceFor(feeder, "away");
2930
+ const home = resolveSlot({
2931
+ walk,
2932
+ match: feeder,
2933
+ side: "home"
2934
+ });
2935
+ const away = resolveSlot({
2936
+ walk,
2937
+ match: feeder,
2938
+ side: "away"
2939
+ });
2940
+ if (homeSource?.kind === "bye" && awaySource?.kind !== "bye") return source.role !== "loser" ? away : null;
2941
+ if (awaySource?.kind === "bye" && homeSource?.kind !== "bye") return source.role !== "loser" ? home : null;
2942
+ if (!home || !away) return walk.keepPickWhileFeederSideIsOpen && source.role !== "loser" ? walk.picks.matchWinner(feeder.id) : null;
2943
+ const pickedWinner = walk.picks.matchWinner(feeder.id);
2944
+ if (pickedWinner !== home && pickedWinner !== away) return null;
2945
+ return source.role !== "loser" ? pickedWinner : pickedWinner === home ? away : home;
2946
+ };
2947
+ const resolveSource = (options) => {
2948
+ const { walk, match, side, source } = options;
2949
+ switch (source.kind) {
2950
+ case "match-outcome": return resolveMatchOutcome({
2951
+ walk,
2952
+ source
2953
+ });
2954
+ case "standing-rank": return walk.picks.standingRank({
2955
+ standingId: source.standingId,
2956
+ rank: source.rank,
2957
+ match,
2958
+ side
2959
+ });
2960
+ case "seed":
2961
+ case "swiss-bucket":
2962
+ case "external":
2963
+ case "unknown": return participantIdFor(match, side);
2964
+ case "bye": return null;
2965
+ }
2966
+ };
2967
+ const resolveSlotOccupant = (options) => {
2968
+ const { walk, match, side } = options;
2969
+ const real = participantIdFor(match, side);
2970
+ if (real !== null && walk.realParticipantOutranksPick(match)) return real;
2971
+ const source = sourceFor(match, side);
2972
+ if (!source) return real;
2973
+ const resolved = resolveSource({
2974
+ walk,
2975
+ match,
2976
+ side,
2977
+ source
2978
+ });
2979
+ if (resolved !== null || !walk.fallBackToRealParticipant) return resolved;
2980
+ return source.kind === "match-outcome" || source.kind === "standing-rank" ? real : null;
2981
+ };
2982
+ const resolveSlot = (options) => {
2983
+ const { walk, match, side } = options;
2984
+ const visitKey = `${match.id}:${side}`;
2985
+ const openDepth = walk.visitDepths.get(visitKey);
2986
+ if (openDepth !== void 0) {
2987
+ walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, openDepth);
2988
+ return null;
2989
+ }
2990
+ const resolved = walk.resolved.get(visitKey);
2991
+ if (resolved !== void 0) return resolved;
2992
+ const depth = walk.visitDepths.size;
2993
+ const shallowestCycleHitBefore = walk.shallowestCycleHit;
2994
+ walk.visitDepths.set(visitKey, depth);
2995
+ walk.shallowestCycleHit = Infinity;
2996
+ try {
2997
+ const result = resolveSlotOccupant({
2998
+ walk,
2999
+ match,
3000
+ side
3001
+ });
3002
+ if (walk.shallowestCycleHit >= depth) walk.resolved.set(visitKey, result);
3003
+ return result;
3004
+ } finally {
3005
+ walk.visitDepths.delete(visitKey);
3006
+ walk.shallowestCycleHit = Math.min(walk.shallowestCycleHit, shallowestCycleHitBefore);
3007
+ }
3008
+ };
3009
+ const matchLookupFor = (brackets) => (matchId) => {
3010
+ for (const bracket of brackets) {
3011
+ const match = bracket.matches.get(matchId);
3012
+ if (match) return match;
3013
+ }
3014
+ };
3015
+ const createResolveWalk = (options) => ({
3016
+ lookupMatch: matchLookupFor([options.bracket, ...options.linkedBrackets ?? []]),
3017
+ picks: options.picks,
3018
+ realParticipantOutranksPick: options.realParticipantOutranksPick ?? (() => false),
3019
+ keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen ?? false,
3020
+ fallBackToRealParticipant: options.fallBackToRealParticipant ?? false,
3021
+ visitDepths: /* @__PURE__ */ new Map(),
3022
+ resolved: /* @__PURE__ */ new Map(),
3023
+ shallowestCycleHit: Infinity
3024
+ });
3025
+ const createBracketSlotResolver = (options) => {
3026
+ const walk = createResolveWalk(options);
3027
+ return (matchId, side) => {
3028
+ const match = options.bracket.matches.get(matchId);
3029
+ return match ? resolveSlot({
3030
+ walk,
3031
+ match,
3032
+ side
3033
+ }) : null;
3034
+ };
3035
+ };
3036
+ const resolveBracketSlot = (options) => createBracketSlotResolver(options)(options.matchId, options.side);
3037
+ const roundsOf = (bracket) => {
3038
+ const matchesByKey = /* @__PURE__ */ new Map();
3039
+ const keyByMatchId = /* @__PURE__ */ new Map();
3040
+ for (const round of bracket.rounds.values()) {
3041
+ const key = `${round.type}:${round.logicalIndex}`;
3042
+ const matches = matchesByKey.get(key) ?? [];
3043
+ for (const match of round.matches.values()) {
3044
+ matches.push(match);
3045
+ keyByMatchId.set(match.id, key);
3046
+ }
3047
+ matchesByKey.set(key, matches);
3048
+ }
3049
+ const unsettledFeedersByKey = /* @__PURE__ */ new Map();
3050
+ for (const [key, matches] of matchesByKey) {
3051
+ const feeders = /* @__PURE__ */ new Set();
3052
+ for (const match of matches) for (const source of [match.homeSource, match.awaySource]) {
3053
+ if (source?.kind !== "match-outcome" || !source.matchId) continue;
3054
+ const feederKey = keyByMatchId.get(source.matchId);
3055
+ if (feederKey !== void 0 && feederKey !== key) feeders.add(feederKey);
3056
+ }
3057
+ unsettledFeedersByKey.set(key, feeders);
3058
+ }
3059
+ const ordered = [];
3060
+ while (unsettledFeedersByKey.size) {
3061
+ const keys = [...unsettledFeedersByKey.keys()];
3062
+ const key = keys.find((candidate) => !unsettledFeedersByKey.get(candidate)?.size) ?? keys[0];
3063
+ if (key === void 0) break;
3064
+ ordered.push(matchesByKey.get(key) ?? []);
3065
+ unsettledFeedersByKey.delete(key);
3066
+ for (const feeders of unsettledFeedersByKey.values()) feeders.delete(key);
3067
+ }
3068
+ return ordered;
3069
+ };
3070
+ const migrateBracketPicks = (options) => {
3071
+ const { bracket, pickAsMade } = options;
3072
+ const locked = options.lockedMatchIds ?? /* @__PURE__ */ new Set();
3073
+ const pickByMatchId = {};
3074
+ const movedFromByMatchId = {};
3075
+ const strandedByMatchId = {};
3076
+ const settled = {
3077
+ matchWinner: (matchId) => bracket.matches.has(matchId) ? pickByMatchId[matchId] ?? null : pickAsMade(matchId),
3078
+ standingRank: options.standingRank ?? (() => null)
3079
+ };
3080
+ for (const round of roundsOf(bracket)) {
3081
+ const sidesByMatchId = /* @__PURE__ */ new Map();
3082
+ const travelling = [];
3083
+ const strandedHere = /* @__PURE__ */ new Set();
3084
+ const sidesOf = (matchId) => sidesByMatchId.get(matchId) ?? [null, null];
3085
+ const resolve = createBracketSlotResolver({
3086
+ bracket,
3087
+ linkedBrackets: options.linkedBrackets,
3088
+ picks: settled,
3089
+ realParticipantOutranksPick: options.realParticipantOutranksPick,
3090
+ keepPickWhileFeederSideIsOpen: options.keepPickWhileFeederSideIsOpen,
3091
+ fallBackToRealParticipant: options.fallBackToRealParticipant
3092
+ });
3093
+ for (const match of round) sidesByMatchId.set(match.id, [resolve(match.id, "home"), resolve(match.id, "away")]);
3094
+ for (const match of round) {
3095
+ const pick = pickAsMade(match.id);
3096
+ if (!pick) continue;
3097
+ const [home, away] = sidesOf(match.id);
3098
+ if (pick === home || pick === away) {
3099
+ pickByMatchId[match.id] = pick;
3100
+ continue;
3101
+ }
3102
+ if (locked.has(match.id)) {
3103
+ pickByMatchId[match.id] = pick;
3104
+ strandedByMatchId[match.id] = pick;
3105
+ continue;
3106
+ }
3107
+ travelling.push({
3108
+ matchId: match.id,
3109
+ pick
3110
+ });
3111
+ }
3112
+ for (const { matchId, pick } of travelling) {
3113
+ const target = round.find((candidate) => {
3114
+ if (candidate.id === matchId || locked.has(candidate.id) || pickByMatchId[candidate.id]) return false;
3115
+ if (strandedHere.has(candidate.id)) return false;
3116
+ const [home, away] = sidesOf(candidate.id);
3117
+ return pick === home || pick === away;
3118
+ });
3119
+ if (!target) {
3120
+ strandedByMatchId[matchId] = pick;
3121
+ strandedHere.add(matchId);
3122
+ continue;
3123
+ }
3124
+ pickByMatchId[target.id] = pick;
3125
+ movedFromByMatchId[target.id] = matchId;
3126
+ }
3127
+ for (const matchId of strandedHere) delete pickByMatchId[matchId];
3128
+ }
3129
+ return {
3130
+ pickByMatchId,
3131
+ movedFromByMatchId,
3132
+ strandedByMatchId
3133
+ };
3134
+ };
3135
+ const standingRankSides = (options) => {
3136
+ const match = options.bracket.matches.get(options.matchId);
3137
+ if (!match) return [];
3138
+ return ["home", "away"].flatMap((side) => {
3139
+ const source = side === "home" ? match.homeSource : match.awaySource;
3140
+ if (source?.kind !== "standing-rank") return [];
3141
+ return [{
3142
+ side,
3143
+ standingId: source.standingId,
3144
+ rank: source.rank,
3145
+ standingName: source.standingName ?? null,
3146
+ participantId: match[side]?.id ?? null
3147
+ }];
3148
+ });
3149
+ };
3150
+ const validateBracketSource = (source, options) => {
3151
+ try {
3152
+ createBracket(source, options);
3153
+ return null;
3154
+ } catch (error) {
3155
+ if (error instanceof BracketRuntimeError) return error;
3156
+ throw error;
3157
+ }
3158
+ };
3159
+ const getSwissGroupBoxPadding = (options) => options.swissGroupPadding + options.swissGroupBorderWidth;
3160
+ const calculateSwissColumnMetrics = (groupMap, options) => {
3161
+ const includeHeaders = options.roundHeaderHeight > 0;
3162
+ const boxPadding = getSwissGroupBoxPadding(options);
3163
+ let naturalHeight = 0;
3164
+ let stretchableGapCount = 0;
3165
+ for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {
3166
+ if (groupIndex !== 0) {
3167
+ naturalHeight += options.rowRoundGap;
3168
+ stretchableGapCount++;
3169
+ }
3170
+ if (includeHeaders) naturalHeight += options.roundHeaderHeight + options.roundHeaderGap;
3171
+ const matchGapCount = Math.max(0, group.matches.size - 1);
3172
+ naturalHeight += boxPadding * 2 + group.matches.size * options.matchHeight + matchGapCount * options.rowGap;
3173
+ stretchableGapCount += matchGapCount;
3174
+ }
3175
+ return {
3176
+ naturalHeight,
3177
+ stretchableGapCount
3178
+ };
3179
+ };
3180
+ const createSwissGrid = (bracketData, options, components) => {
3181
+ const swissGroupMaps = generateBracketRoundSwissGroupMaps(bracketData);
3182
+ if (!swissGroupMaps) throw new BracketRuntimeError(BRACKET_ERROR_CODES.SWISS_GROUPING_FAILED, "Unable to generate Swiss groups for the provided bracket data");
3183
+ const grid = createBracketGrid({ spanElementWidth: options.columnWidth });
3184
+ const groupMaps = Array.from(swissGroupMaps.values());
3185
+ const columnMetrics = groupMaps.map((groupMap) => calculateSwissColumnMetrics(groupMap, options));
3186
+ const totalHeight = Math.max(...columnMetrics.map((metrics) => metrics.naturalHeight));
3187
+ const longestColumnIndex = columnMetrics.findIndex((metrics) => metrics.naturalHeight === totalHeight);
3188
+ for (const [groupMapIndex, groupMap] of groupMaps.entries()) {
3189
+ const isLastGroupMap = groupMapIndex === swissGroupMaps.size - 1;
3190
+ const metrics = columnMetrics[groupMapIndex];
3191
+ const heightToFill = totalHeight - metrics.naturalHeight;
3192
+ const isStretched = groupMapIndex < longestColumnIndex && metrics.stretchableGapCount > 0;
3193
+ const gapStretch = isStretched ? heightToFill / metrics.stretchableGapCount : 0;
3194
+ const rowGap = options.rowGap + gapStretch;
3195
+ const rowRoundGap = options.rowRoundGap + gapStretch;
3196
+ const boxPadding = getSwissGroupBoxPadding(options);
3197
+ const { masterColumn, pushSection } = createBracketMasterColumn({
3198
+ columnWidth: options.columnWidth,
3199
+ padding: {
3200
+ bottom: 0,
3201
+ left: 0,
3202
+ right: 0,
3203
+ top: 0
3204
+ }
3205
+ });
3206
+ for (const [groupIndex, group] of Array.from(groupMap.groups.values()).entries()) {
3207
+ const isLastGroup = groupIndex === groupMap.groups.size - 1;
3208
+ if (options.roundHeaderHeight > 0) {
3209
+ const firstMatchRound = group.matches.first()?.round;
3210
+ if (!firstMatchRound) throw new BracketRuntimeError(BRACKET_ERROR_CODES.SWISS_GROUP_EMPTY, "No rounds found in Swiss group");
3211
+ const headerColumnSection = createBracketMasterColumnSection({ type: "round" });
3212
+ const headerSubColumn = createBracketSubColumn({ span: {
3213
+ isStart: true,
3214
+ isEnd: true
3215
+ } });
3216
+ const headerElement = createBracketElement({
3217
+ type: "header",
3218
+ area: `h${group.id}`,
3219
+ partHeights: [options.roundHeaderHeight],
3220
+ elementHeight: options.roundHeaderHeight,
3221
+ component: components.roundHeader,
3222
+ round: firstMatchRound,
3223
+ roundSwissGroup: group
3224
+ });
3225
+ const headerGapElement = createBracketElement({
3226
+ type: "roundHeaderGap",
3227
+ area: ".",
3228
+ partHeights: [options.roundHeaderGap],
3229
+ elementHeight: options.roundHeaderGap
3230
+ });
3231
+ headerSubColumn.pushElement(headerElement, headerGapElement);
3232
+ headerColumnSection.pushSubColumn(headerSubColumn.subColumn);
3233
+ pushSection(headerColumnSection.masterColumnSection);
3234
+ }
3235
+ const { masterColumnSection, pushSubColumn } = createBracketMasterColumnSection({
3236
+ type: "round",
3237
+ padding: {
3238
+ bottom: boxPadding,
3239
+ left: boxPadding,
3240
+ right: boxPadding,
3241
+ top: boxPadding
3242
+ }
3243
+ });
3244
+ const { subColumn, pushElement } = createBracketSubColumn({ span: {
3245
+ isStart: true,
3246
+ isEnd: true
3247
+ } });
3248
+ const elementsToCreate = [];
3249
+ for (const [matchIndex, match] of Array.from(group.matches.values()).entries()) {
3250
+ const isLastMatch = matchIndex === group.matches.size - 1;
3251
+ elementsToCreate.push({
3252
+ type: "match",
3253
+ area: `m${match.shortId}`,
3254
+ partHeights: [options.matchHeight],
3255
+ elementHeight: options.matchHeight,
3256
+ component: components.match,
3257
+ match,
3258
+ round: match.round,
3259
+ roundSwissGroup: group
3260
+ });
3261
+ if (!isLastMatch) elementsToCreate.push({
3262
+ type: "matchGap",
3263
+ area: ".",
3264
+ partHeights: [rowGap],
3265
+ elementHeight: rowGap
3266
+ });
3267
+ }
3268
+ for (const elementData of elementsToCreate) pushElement(createBracketElement(elementData));
3269
+ pushSubColumn(subColumn);
3270
+ pushSection(masterColumnSection);
3271
+ if (!isLastGroup) {
3272
+ const groupGapColumnSection = createBracketMasterColumnSection({ type: "gap" });
3273
+ const groupGapSubColumn = createBracketSubColumn({ span: {
3274
+ isStart: true,
3275
+ isEnd: true
3276
+ } });
3277
+ const groupGapElement = createBracketElement({
3278
+ area: ".",
3279
+ type: "roundGap",
3280
+ elementHeight: rowRoundGap,
3281
+ partHeights: [rowRoundGap]
3282
+ });
3283
+ groupGapSubColumn.pushElement(groupGapElement);
3284
+ groupGapColumnSection.pushSubColumn(groupGapSubColumn.subColumn);
3285
+ pushSection(groupGapColumnSection.masterColumnSection);
3286
+ }
3287
+ }
3288
+ const fillerHeight = isStretched ? 0 : heightToFill;
3289
+ if (fillerHeight > 0) {
3290
+ const fillerColumnSection = createBracketMasterColumnSection({ type: "gap" });
3291
+ const fillerSubColumn = createBracketSubColumn({ span: {
3292
+ isStart: true,
3293
+ isEnd: true
3294
+ } });
3295
+ const fillerElement = createBracketElement({
3296
+ area: ".",
3297
+ type: "colGap",
3298
+ elementHeight: fillerHeight,
3299
+ partHeights: [fillerHeight]
3300
+ });
3301
+ fillerSubColumn.pushElement(fillerElement);
3302
+ fillerColumnSection.pushSubColumn(fillerSubColumn.subColumn);
3303
+ pushSection(fillerColumnSection.masterColumnSection);
3304
+ }
3305
+ grid.pushMasterColumn(masterColumn);
3306
+ if (!isLastGroupMap) grid.pushMasterColumn(createBracketGapMasterColumn({
3307
+ existingMasterColumns: grid.grid.masterColumns,
3308
+ columnGap: options.columnGap
3309
+ }));
3310
+ }
3311
+ grid.calculateDimensions();
3312
+ const finalizedGrid = finalizeBracketGrid(grid);
3313
+ return {
3314
+ raw: grid,
3315
+ columns: finalizedGrid.columns,
3316
+ matchElementMap: finalizedGrid.elementMap
3317
+ };
3318
+ };
3319
+ const bracketSlot = {
3320
+ matchOutcome: (matchId, role, label = null) => ({
3321
+ kind: "match-outcome",
3322
+ matchId,
3323
+ role,
3324
+ label
3325
+ }),
3326
+ standingRank: (standingId, rank, standingName = null, label = null) => ({
3327
+ kind: "standing-rank",
3328
+ standingId,
3329
+ rank,
3330
+ standingName,
3331
+ label
3332
+ }),
3333
+ seed: (seed, label = null) => ({
3334
+ kind: "seed",
3335
+ seed,
3336
+ label
3337
+ }),
3338
+ swissBucket: (label = null) => ({
3339
+ kind: "swiss-bucket",
3340
+ label
3341
+ }),
3342
+ bye: (label = null) => ({
3343
+ kind: "bye",
3344
+ label
3345
+ }),
3346
+ external: (label) => ({
3347
+ kind: "external",
3348
+ label
3349
+ }),
3350
+ unknown: (label = null) => ({
3351
+ kind: "unknown",
3352
+ label
3353
+ })
3354
+ };
3355
+ const LAYOUT_FACTORY_SUGGESTION = {
3356
+ "single-elimination": "singleEliminationBracketLayout()",
3357
+ "double-elimination": "doubleEliminationBracketLayout()",
3358
+ "swiss-with-elimination": "swissBracketLayout()"
3359
+ };
3360
+ const resolveBracketLayout = (layouts, mode) => {
3361
+ const layout = layouts?.find((candidate) => candidate.mode === mode);
3362
+ if (!layout) throw new BracketRuntimeError(BRACKET_ERROR_CODES.LAYOUT_NOT_REGISTERED, `No bracket layout registered for mode "${mode}". Add ${LAYOUT_FACTORY_SUGGESTION[mode]} to provideBracketConfig({ layouts: [...] }) or to the layouts input.`);
3363
+ return layout;
3364
+ };
3365
+ const MIN_PARTICIPANTS = {
3366
+ "single-elimination": 2,
3367
+ "double-elimination": 4
3368
+ };
3369
+ const assertParticipantCount = (shape) => {
3370
+ const { participantCount, mode } = shape;
3371
+ const min = MIN_PARTICIPANTS[mode];
3372
+ const isPowerOfTwo = Number.isInteger(participantCount) && (participantCount & participantCount - 1) === 0;
3373
+ if (participantCount < min || !isPowerOfTwo) throw new BracketRuntimeError(BRACKET_ERROR_CODES.PLACEHOLDER_SHAPE_INVALID, `A ${mode} placeholder bracket needs a power-of-two participantCount of at least ${min}, got ${participantCount}.`);
3374
+ };
3375
+ const halvingCounts = (from) => {
3376
+ const counts = [];
3377
+ for (let n = from; n >= 1; n = n / 2) counts.push(n);
3378
+ return counts;
3379
+ };
3380
+ const createPlaceholderBracketSource = (shape) => {
3381
+ assertParticipantCount(shape);
3382
+ const rounds = [];
3383
+ const matches = [];
3384
+ const addRound = (round) => {
3385
+ const { id, type, matchCount } = round;
3386
+ rounds.push({
3387
+ id,
3388
+ type,
3389
+ name: "",
3390
+ data: null
3391
+ });
3392
+ for (let index = 0; index < matchCount; index++) matches.push({
3393
+ id: `${id}-m${index}`,
3394
+ roundId: id,
3395
+ home: null,
3396
+ away: null,
3397
+ winner: null,
3398
+ status: "pending",
3399
+ data: null
3400
+ });
3401
+ };
3402
+ const { participantCount } = shape;
3403
+ if (shape.mode === TOURNAMENT_MODE.SINGLE_ELIMINATION) {
3404
+ const counts = halvingCounts(participantCount / 2);
3405
+ counts.forEach((matchCount, index) => {
3406
+ const isFinal = index === counts.length - 1;
3407
+ addRound({
3408
+ id: isFinal ? "final" : `r${index}`,
3409
+ type: isFinal ? COMMON_BRACKET_ROUND_TYPE.FINAL : SINGLE_ELIMINATION_BRACKET_ROUND_TYPE.SINGLE_ELIMINATION_BRACKET,
3410
+ matchCount
3411
+ });
3412
+ });
3413
+ if (shape.includeThirdPlace) addRound({
3414
+ id: "third-place",
3415
+ type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,
3416
+ matchCount: 1
3417
+ });
3418
+ return {
3419
+ mode: TOURNAMENT_MODE.SINGLE_ELIMINATION,
3420
+ rounds,
3421
+ matches
3422
+ };
3423
+ }
3424
+ const { includeFinal = true, includeReverseFinal = true, includeThirdPlace = false } = shape;
3425
+ halvingCounts(participantCount / 2).forEach((matchCount, index) => addRound({
3426
+ id: `ub-r${index}`,
3427
+ type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.UPPER_BRACKET,
3428
+ matchCount
3429
+ }));
3430
+ halvingCounts(participantCount / 4).flatMap((matchCount) => [matchCount, matchCount]).forEach((matchCount, index) => addRound({
3431
+ id: `lb-r${index}`,
3432
+ type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.LOWER_BRACKET,
3433
+ matchCount
3434
+ }));
3435
+ if (includeFinal) {
3436
+ addRound({
3437
+ id: "final",
3438
+ type: COMMON_BRACKET_ROUND_TYPE.FINAL,
3439
+ matchCount: 1
3440
+ });
3441
+ if (includeReverseFinal) addRound({
3442
+ id: "reverse-final",
3443
+ type: DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE.REVERSE_FINAL,
3444
+ matchCount: 1
3445
+ });
3446
+ }
3447
+ if (includeThirdPlace) addRound({
3448
+ id: "third-place",
3449
+ type: COMMON_BRACKET_ROUND_TYPE.THIRD_PLACE,
3450
+ matchCount: 1
3451
+ });
3452
+ return {
3453
+ mode: TOURNAMENT_MODE.DOUBLE_ELIMINATION,
3454
+ rounds,
3455
+ matches
3456
+ };
3457
+ };
3458
+ const STANDING_PICK_OUTCOME = {
3459
+ EXACT: "exact",
3460
+ PARTIAL: "partial",
3461
+ WRONG: "wrong"
3462
+ };
3463
+ const standingPickOutcome = (options) => {
3464
+ const { predictedPosition, actualPosition, advancingCount } = options;
3465
+ if (predictedPosition <= advancingCount !== actualPosition <= advancingCount) return STANDING_PICK_OUTCOME.WRONG;
3466
+ if (predictedPosition === actualPosition) return STANDING_PICK_OUTCOME.EXACT;
3467
+ return STANDING_PICK_OUTCOME.PARTIAL;
3468
+ };
3469
+ const standingPickStartOrder = (options) => {
3470
+ const { participantIds, picks } = options;
3471
+ const field = new Set(participantIds);
3472
+ const byPosition = /* @__PURE__ */ new Map();
3473
+ const placed = /* @__PURE__ */ new Set();
3474
+ for (const pick of [...picks].sort((left, right) => left.position - right.position)) {
3475
+ if (!(Number.isInteger(pick.position) && pick.position >= 1 && pick.position <= participantIds.length && field.has(pick.participantId) && !placed.has(pick.participantId) && !byPosition.has(pick.position))) continue;
3476
+ byPosition.set(pick.position, pick.participantId);
3477
+ placed.add(pick.participantId);
3478
+ }
3479
+ const rest = participantIds.filter((id) => !placed.has(id));
3480
+ const order = [];
3481
+ for (let position = 1; position <= participantIds.length; position++) {
3482
+ const id = byPosition.get(position) ?? rest.shift();
3483
+ if (id !== void 0) order.push(id);
3484
+ }
3485
+ return order;
3486
+ };
3487
+ const swapStandingRank = (options) => {
3488
+ const { order, rank, participantId } = options;
3489
+ const next = [...order];
3490
+ const to = rank - 1;
3491
+ const from = next.indexOf(participantId);
3492
+ if (from < 0 || !Number.isInteger(rank) || to < 0 || to >= next.length) return next;
3493
+ [next[from], next[to]] = [next[to], participantId];
3494
+ return next;
3495
+ };
3496
+ export { BRACKET_DATA_LAYOUT, BRACKET_ERROR_CODES, BRACKET_FINAL_ALIGNMENT, BRACKET_ROUND_MIRROR_TYPE, BRACKET_SECTION_DEFAULT_NAMES, BRACKET_SECTION_KEY, BRACKET_SWISS_GROUP_COLOR_TYPE, BracketMap, BracketRuntimeError, COMMON_BRACKET_ROUND_TYPE, DOUBLE_ELIMINATION_BRACKET_ROUND_TYPE, GROUP_BRACKET_ROUND_TYPE, SINGLE_ELIMINATION_BRACKET_ROUND_TYPE, STANDING_PICK_OUTCOME, SWISS_ADVANCE_WINS, SWISS_BRACKET_ROUND_TYPE, SWISS_ELIMINATE_LOSSES, TERMINAL_ROUND_SORT_PRIORITY, TOURNAMENT_MODE, bracketGridNaturalWidth, bracketSlot, calculateColumnSplitFactor, calculateLowerRoundIndex, calculateUpperLowerRatio, calculateUpperRoundIndex, createBracket, createBracketBase, createBracketContinueMasterColumn, createBracketElement, createBracketElementPart, createBracketGapMasterColumn, createBracketGrid, createBracketGridSections, createBracketMasterColumn, createBracketMasterColumnSection, createBracketSlotResolver, createBracketSubColumn, createDoubleEliminationGrid, createFoldedThirdPlaceSection, createMatchesMapBase, createNewMatchParticipantBase, createParticipantsMapBase, createPlaceholderBracketSource, createRoundBracketSubColumnRelativeToFirstRound, createRoundsMapBase, createSingleEliminationGrid, createSwissGrid, curvePath, doubleEliminationRoundSection, drawMan, drawSwissMan, finalizeBracketGrid, generateBracketRoundSwissGroupMaps, generateMatchPosition, generateMatchRelationPositions, generateMatchRelationsNew, generateRoundRelationsNew, getAvailableSwissGroupsForRound, getBracketContinueMatches, getSwissGroupColorType, gutterPath, isBracketContinueMatch, isBracketSlotPredictable, linePath, migrateBracketPicks, path, resolveBracketGridRowSpan, resolveBracketLayout, resolveBracketSlot, standingPickOutcome, standingPickStartOrder, standingRankSides, swapStandingRank, validateBracketSource, verticalPath, createStackedDoubleEliminationGrid as ɵcreateStackedDoubleEliminationGrid };
3497
+
3498
+ //# sourceMappingURL=ethlete-components-bracket.mjs.map