-
Notifications
You must be signed in to change notification settings - Fork 43
/
main.ts
616 lines (512 loc) · 24.6 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
import './style.scss';
import { Participant, Match, ParticipantResult, Stage, Status, GroupType, FinalType } from 'brackets-model';
import { splitBy, getRanking, getOriginAbbreviation, findRoot, completeWithBlankMatches, sortBy } from './helpers';
import * as dom from './dom';
import * as lang from './lang';
import { Locale } from './lang';
import { helpers } from 'brackets-manager';
import {
Config,
Connection,
OriginHint,
ParticipantContainers,
RankingItem,
RoundNameGetter,
ViewerData,
ParticipantImage,
Side,
MatchClickCallback,
RoundNameInfo,
} from './types';
export class BracketsViewer {
readonly participantRefs: Record<number, HTMLElement[]> = {};
private participants: Participant[] = [];
private participantImages: ParticipantImage[] = [];
private stage!: Stage;
private config!: Config;
private skipFirstRound = false;
private alwaysConnectFirstRound = false;
// eslint-disable-next-line jsdoc/require-jsdoc
private getRoundName(info: RoundNameInfo, fallbackGetter: RoundNameGetter): string {
return this.config.customRoundName?.(info, lang.t) || fallbackGetter(info, lang.t);
}
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private _onMatchClick: MatchClickCallback = (match: Match): void => { };
/**
* @deprecated Use `onMatchClick` in the `config` parameter of `viewer.render()`.
* @param callback A callback to be called when a match is clicked.
*/
public set onMatchClicked(callback: MatchClickCallback) {
this._onMatchClick = callback;
}
/**
* Renders data generated with `brackets-manager.js`. If multiple stages are given, they will all be displayed.
*
* Stages won't be discriminated visually based on the tournament they belong to.
*
* @param data The data to display.
* @param config An optional configuration for the viewer.
*/
// eslint-disable-next-line @typescript-eslint/require-await -- Keep this async for backwards compatibility.
public async render(data: ViewerData, config?: Partial<Config>): Promise<void> {
const root = document.createDocumentFragment();
this.config = {
customRoundName: config?.customRoundName,
participantOriginPlacement: config?.participantOriginPlacement || 'before',
separatedChildCountLabel: config?.separatedChildCountLabel !== undefined ? config.separatedChildCountLabel : false,
showSlotsOrigin: config?.showSlotsOrigin !== undefined ? config.showSlotsOrigin : true,
showLowerBracketSlotsOrigin: config?.showLowerBracketSlotsOrigin !== undefined ? config.showLowerBracketSlotsOrigin : true,
highlightParticipantOnHover: config?.highlightParticipantOnHover !== undefined ? config.highlightParticipantOnHover : true,
showRankingTable: config?.showRankingTable !== undefined ? config.showRankingTable : true,
};
if (this.config.onMatchClick)
this._onMatchClick = this.config.onMatchClick;
this.participants = data.participants;
data.participants.forEach(participant => this.participantRefs[participant.id] = []);
data.stages.forEach(stage => this.renderStage(root, {
...data,
stages: [stage],
matches: data.matches.filter(match => match.stage_id === stage.id),
}));
findRoot(config?.selector).append(root);
}
/**
* Updates the results of an existing match.
*
* @param match The match to update.
*/
public updateMatch(match: Match): void {
// TODO: finish this function (update win/loss/forfeit, scoreboard in round-robin, etc.)
const matchContainer = document.querySelector(`[data-match-id='${match.id}']`);
if (!matchContainer) throw Error('Match not found.');
matchContainer.setAttribute('data-match-status', match.status.toString());
const result1 = matchContainer.querySelector('.participant:nth-of-type(1) .result');
if (result1 && match.opponent1?.score) result1.innerHTML = match.opponent1?.score?.toString();
const result2 = matchContainer.querySelector('.participant:nth-of-type(2) .result');
if (result2 && match.opponent2?.score) result2.innerHTML = match.opponent2?.score?.toString();
}
/**
* Sets the images which will be rendered for every participant.
*
* @param images The participant images.
*/
public setParticipantImages(images: ParticipantImage[]): void {
this.participantImages = images;
}
/**
* Adds a locale to the available i18n bundles.
*
* @param name Name of the locale.
* @param locale Contents of the locale.
*/
public async addLocale(name: string, locale: Locale): Promise<void> {
await lang.addLocale(name, locale);
}
/**
* Renders a stage (round-robin, single or double elimination).
*
* @param root The root element.
* @param data The data to display.
*/
private renderStage(root: DocumentFragment, data: ViewerData): void {
const stage = data.stages[0];
const matchesByGroup = splitBy(data.matches, 'group_id');
this.stage = stage;
this.skipFirstRound = stage.settings.skipFirstRound || false;
switch (stage.type) {
case 'round_robin':
this.renderRoundRobin(root, stage, matchesByGroup);
break;
case 'single_elimination':
case 'double_elimination':
this.renderElimination(root, stage, matchesByGroup);
break;
default:
throw Error(`Unknown bracket type: ${stage.type as string}`);
}
}
/**
* Renders a round-robin stage.
*
* @param root The root element.
* @param stage The stage to render.
* @param matchesByGroup A list of matches for each group.
*/
private renderRoundRobin(root: DocumentFragment, stage: Stage, matchesByGroup: Match[][]): void {
const container = dom.createRoundRobinContainer(stage.id);
container.append(dom.createTitle(stage.name));
let groupNumber = 1;
for (const groupMatches of matchesByGroup) {
const groupId = groupMatches[0].group_id;
const groupContainer = dom.createGroupContainer(groupId, lang.getGroupName(groupNumber++));
const matchesByRound = splitBy(groupMatches, 'round_id').map(matches => sortBy(matches, 'number'));
let roundNumber = 1;
for (const roundMatches of matchesByRound) {
const roundId = roundMatches[0].round_id;
const roundName = this.getRoundName({
roundNumber,
roundCount: 0,
groupType: lang.toI18nKey('round_robin'),
}, lang.getRoundName);
const roundContainer = dom.createRoundContainer(roundId, roundName);
for (const match of roundMatches)
roundContainer.append(this.createMatch(match));
groupContainer.append(roundContainer);
roundNumber++;
}
if (this.config.showRankingTable)
groupContainer.append(this.createRanking(groupMatches));
container.append(groupContainer);
}
root.append(container);
}
/**
* Renders an elimination stage (single or double).
*
* @param root The root element.
* @param stage The stage to render.
* @param matchesByGroup A list of matches for each group.
*/
private renderElimination(root: DocumentFragment, stage: Stage, matchesByGroup: Match[][]): void {
const container = dom.createEliminationContainer(stage.id);
container.append(dom.createTitle(stage.name));
if (stage.type === 'single_elimination')
this.renderSingleElimination(container, matchesByGroup);
else
this.renderDoubleElimination(container, matchesByGroup);
root.append(container);
}
/**
* Renders a single elimination stage.
*
* @param container The container to render into.
* @param matchesByGroup A list of matches for each group.
*/
private renderSingleElimination(container: HTMLElement, matchesByGroup: Match[][]): void {
const hasFinal = matchesByGroup[1] !== undefined;
const bracketMatches = splitBy(matchesByGroup[0], 'round_id').map(matches => sortBy(matches, 'number'));
this.renderBracket(container, bracketMatches, lang.getRoundName, 'single_bracket');
if (hasFinal) {
const finalMatches = sortBy(matchesByGroup[1], 'number');
this.renderFinal(container, 'consolation_final', finalMatches);
}
}
/**
* Renders a double elimination stage.
*
* @param container The container to render into.
* @param matchesByGroup A list of matches for each group.
*/
private renderDoubleElimination(container: HTMLElement, matchesByGroup: Match[][]): void {
const hasLoserBracket = matchesByGroup[1] !== undefined;
const hasFinal = matchesByGroup[2] !== undefined;
const winnerBracketMatches = splitBy(matchesByGroup[0], 'round_id').map(matches => sortBy(matches, 'number'));
this.renderBracket(container, winnerBracketMatches, lang.getWinnerBracketRoundName, 'winner_bracket', hasFinal);
if (hasLoserBracket) {
const loserBracketMatches = splitBy(matchesByGroup[1], 'round_id').map(matches => sortBy(matches, 'number'));
this.renderBracket(container, loserBracketMatches, lang.getLoserBracketRoundName, 'loser_bracket');
}
if (hasFinal) {
const finalMatches = sortBy(matchesByGroup[2], 'number');
this.renderFinal(container, 'grand_final', finalMatches);
}
}
/**
* Renders a bracket.
*
* @param container The container to render into.
* @param matchesByRound A list of matches for each round.
* @param getRoundName A function giving a round's name based on its number.
* @param bracketType Type of the bracket.
* @param connectFinal Whether to connect the last match of the bracket to the final.
*/
private renderBracket(container: HTMLElement, matchesByRound: Match[][], getRoundName: RoundNameGetter, bracketType: GroupType, connectFinal?: boolean): void {
const groupId = matchesByRound[0][0].group_id;
const roundCount = matchesByRound.length;
const bracketContainer = dom.createBracketContainer(groupId, lang.getBracketName(this.stage, bracketType));
const roundsContainer = dom.createRoundsContainer();
const { matches: completedMatches, fromToornament } = completeWithBlankMatches(bracketType, matchesByRound[0], matchesByRound[1]);
this.alwaysConnectFirstRound = !fromToornament;
for (let roundIndex = 0; roundIndex < matchesByRound.length; roundIndex++) {
const roundId = matchesByRound[roundIndex][0].round_id;
const roundNumber = roundIndex + 1;
const roundName = this.getRoundName({
roundNumber,
roundCount,
fractionOfFinal: helpers.getFractionOfFinal(roundNumber, roundCount),
groupType: lang.toI18nKey(bracketType as Exclude<GroupType, 'final_group'>),
}, getRoundName);
const roundContainer = dom.createRoundContainer(roundId, roundName);
const roundMatches = fromToornament && roundNumber === 1 ? completedMatches : matchesByRound[roundIndex];
for (const match of roundMatches)
roundContainer.append(match && this.createBracketMatch(roundNumber, roundCount, match, bracketType, connectFinal) || this.skipBracketMatch());
roundsContainer.append(roundContainer);
}
bracketContainer.append(roundsContainer);
container.append(bracketContainer);
}
/**
* Renders a final group.
*
* @param container The container to render into.
* @param finalType Type of the final.
* @param matches Matches of the final.
*/
private renderFinal(container: HTMLElement, finalType: FinalType, matches: Match[]): void {
const upperBracket = container.querySelector('.bracket .rounds');
if (!upperBracket) throw Error('Upper bracket not found.');
const winnerWb = matches[0].opponent1;
const displayCount = winnerWb?.id === null || winnerWb?.result === 'win' ? 1 : 2;
const finalMatches = matches.slice(0, displayCount);
const roundCount = finalMatches.length;
for (let roundIndex = 0; roundIndex < finalMatches.length; roundIndex++) {
const roundNumber = roundIndex + 1;
const roundName = this.getRoundName({
roundNumber,
roundCount,
groupType: lang.toI18nKey('final_group'),
finalType: lang.toI18nKey(finalType)
}, lang.getRoundName);
const roundContainer = dom.createRoundContainer(finalMatches[roundIndex].round_id, roundName);
roundContainer.append(this.createFinalMatch(finalType, finalMatches, roundNumber, roundCount));
upperBracket.append(roundContainer);
}
}
/**
* Creates a ranking table based on matches of a round-robin stage.
*
* @param matches The list of matches.
*/
private createRanking(matches: Match[]): HTMLElement {
const table = dom.createTable();
const ranking = getRanking(matches);
table.append(dom.createRankingHeaders(ranking));
for (const item of ranking)
table.append(this.createRankingRow(item));
return table;
}
/**
* Creates a row of the ranking table.
*
* @param item Item of the ranking.
*/
private createRankingRow(item: RankingItem): HTMLElement {
const row = dom.createRow();
const notRanked = item.played === 0;
for (const key in item) {
const prop = key as keyof RankingItem;
const data = item[prop];
if (prop === 'id') {
const participant = this.participants.find(participant => participant.id === data);
if (participant !== undefined) {
const cell = dom.createCell(participant.name);
this.setupMouseHover(participant.id, cell);
row.append(cell);
continue;
}
}
if (notRanked && (prop === 'rank' || prop === 'points')) {
row.append(dom.createCell('-'));
continue;
}
row.append(dom.createCell(data));
}
return row;
}
/**
* Creates a match in a bracket.
*
* @param roundNumber Number of the round.
* @param roundCount Count of rounds.
* @param match Information about the match.
* @param matchLocation Location of the match.
* @param connectFinal Whether to connect this match to the final if it happens to be the last one of the bracket.
*/
private createBracketMatch(roundNumber: number, roundCount: number, match: Match, matchLocation: GroupType, connectFinal?: boolean): HTMLElement {
const connection = dom.getBracketConnection(this.alwaysConnectFirstRound, roundNumber, roundCount, match, matchLocation, connectFinal);
const matchLabel = lang.getMatchLabel(match.number, roundNumber, roundCount, matchLocation);
const originHint = lang.getOriginHint(roundNumber, roundCount, this.skipFirstRound, matchLocation);
return this.createMatch(match, matchLocation, connection, matchLabel, originHint, roundNumber);
}
/**
* Creates a match in a final.
*
* @param type Type of the final.
* @param matches Matches of the final.
* @param roundNumber Number of the round.
* @param roundCount Count of rounds.
*/
private createFinalMatch(type: FinalType, matches: Match[], roundNumber: number, roundCount: number): HTMLElement {
const roundIndex = roundNumber - 1;
const connection = dom.getFinalConnection(type, roundNumber, matches.length);
const matchLabel = lang.getFinalMatchLabel(type, roundNumber, roundCount);
const originHint = lang.getFinalOriginHint(type, roundNumber);
return this.createMatch(matches[roundIndex], 'final_group', connection, matchLabel, originHint);
}
/**
* Creates a hidden empty match to act as a placeholder.
*/
private skipBracketMatch(): HTMLElement {
const matchContainer = dom.createMatchContainer();
const opponents = dom.createOpponentsContainer();
const participant1 = this.createParticipant(null);
const participant2 = this.createParticipant(null);
opponents.append(participant1, participant2);
matchContainer.append(opponents);
matchContainer.style.visibility = 'hidden';
return matchContainer;
}
/**
* Creates a match based on its results.
*
* @param match Results of the match.
* @param matchLocation Location of the match.
* @param connection Connection of this match with the others.
* @param label Label of the match.
* @param originHint Origin hint for the match.
* @param roundNumber Number of the round.
*/
private createMatch(match: Match, matchLocation?: GroupType, connection?: Connection, label?: string, originHint?: OriginHint, roundNumber?: number): HTMLElement {
const matchContainer = dom.createMatchContainer(match.id, match.status);
const opponents = dom.createOpponentsContainer(() => this._onMatchClick(match));
if (match.status >= Status.Completed)
originHint = undefined;
const participant1 = this.createParticipant(match.opponent1, 'opponent1', originHint, matchLocation, roundNumber);
const participant2 = this.createParticipant(match.opponent2, 'opponent2', originHint, matchLocation, roundNumber);
this.renderMatchLabel(opponents, match, label);
opponents.append(participant1, participant2);
matchContainer.append(opponents);
if (!connection)
return matchContainer;
dom.setupConnection(opponents, matchContainer, connection);
return matchContainer;
}
/**
* Creates a participant for a match.
*
* @param participant Information about the participant.
* @param side Side of the participant.
* @param originHint Origin hint for the match.
* @param matchLocation Location of the match.
* @param roundNumber Number of the round.
*/
private createParticipant(participant: ParticipantResult | null, side?: Side, originHint?: OriginHint, matchLocation?: GroupType, roundNumber?: number): HTMLElement {
const containers: ParticipantContainers = {
participant: dom.createParticipantContainer(participant && participant.id),
name: dom.createNameContainer(),
result: dom.createResultContainer(),
};
if (participant === null || participant === undefined)
dom.setupBye(containers.name);
else
this.renderParticipant(containers, participant, side, originHint, matchLocation, roundNumber);
containers.participant.append(containers.name, containers.result);
if (participant && participant.id !== null)
this.setupMouseHover(participant.id, containers.participant);
return containers.participant;
}
/**
* Renders a participant.
*
* @param containers Containers for the participant.
* @param participant The participant result.
* @param side Side of the participant.
* @param originHint Origin hint for the match.
* @param matchLocation Location of the match.
* @param roundNumber Number of the round.
*/
private renderParticipant(containers: ParticipantContainers, participant: ParticipantResult, side?: Side, originHint?: OriginHint, matchLocation?: GroupType, roundNumber?: number): void {
const found = this.participants.find(item => item.id === participant.id);
if (found) {
containers.name.innerText = found.name;
containers.participant.setAttribute('title', found.name);
this.renderParticipantImage(containers.name, found.id);
this.renderParticipantOrigin(containers.name, participant, side, matchLocation, roundNumber);
} else
this.renderHint(containers.name, participant, originHint, matchLocation);
containers.result.innerText = `${participant.score === undefined ? '-' : participant.score}`;
dom.setupWin(containers.participant, containers.result, participant);
dom.setupLoss(containers.participant, containers.result, participant);
}
/**
* Renders a participant image.
*
* @param nameContainer The name container.
* @param participantId ID of the participant.
*/
private renderParticipantImage(nameContainer: HTMLElement, participantId: number): void {
const found = this.participantImages.find(item => item.participantId === participantId);
if (found) dom.addParticipantImage(nameContainer, found.imageUrl);
}
/**
* Renders a match label.
*
* @param opponents The opponents container.
* @param match Results of the match.
* @param label Label of the match.
*/
private renderMatchLabel(opponents: HTMLElement, match: Match, label = ''): void {
if (this.config.separatedChildCountLabel) {
opponents.append(dom.createMatchLabel(label, lang.getMatchStatus(match.status)));
if (match.child_count > 0)
opponents.append(dom.createChildCountLabel(lang.t('common.best-of-x', { x: match.child_count })));
return;
}
if (match.child_count > 0) {
const childCountLabel = lang.t('common.best-of-x', { x: match.child_count });
const joined = label ? `${label}, ${childCountLabel}` : childCountLabel;
opponents.append(dom.createMatchLabel(joined, lang.getMatchStatus(match.status)));
}
}
/**
* Renders an origin hint for a participant.
*
* @param nameContainer The name container.
* @param participant The participant result.
* @param originHint Origin hint for the participant.
* @param matchLocation Location of the match.
*/
private renderHint(nameContainer: HTMLElement, participant: ParticipantResult, originHint?: OriginHint, matchLocation?: GroupType): void {
if (originHint === undefined || participant.position === undefined) return;
if (!this.config.showSlotsOrigin) return;
if (!this.config.showLowerBracketSlotsOrigin && matchLocation === 'loser_bracket') return;
dom.setupHint(nameContainer, originHint(participant.position));
}
/**
* Renders a participant's origin.
*
* @param nameContainer The name container.
* @param participant The participant result.
* @param side Side of the participant.Side of the participant.
* @param matchLocation Location of the match.
* @param roundNumber Number of the round.
*/
private renderParticipantOrigin(nameContainer: HTMLElement, participant: ParticipantResult, side?: Side, matchLocation?: GroupType, roundNumber?: number): void {
if (participant.position === undefined || matchLocation === undefined) return;
if (!this.config.participantOriginPlacement || this.config.participantOriginPlacement === 'none') return;
if (!this.config.showSlotsOrigin) return;
if (!this.config.showLowerBracketSlotsOrigin && matchLocation === 'loser_bracket') return;
const abbreviation = getOriginAbbreviation(matchLocation, this.skipFirstRound, roundNumber, side);
if (!abbreviation) return;
const origin = `${abbreviation}${participant.position}`;
dom.addParticipantOrigin(nameContainer, origin, this.config.participantOriginPlacement);
}
/**
* Sets mouse hover events for a participant.
*
* @param participantId ID of the participant.
* @param element The dom element to add events to.
*/
private setupMouseHover(participantId: number, element: HTMLElement): void {
if (!this.config.highlightParticipantOnHover) return;
const refs = this.participantRefs[participantId];
if (!refs) throw Error(`The participant (id: ${participantId}) does not exist in the participants table.`);
refs.push(element);
element.addEventListener('mouseover', () => {
refs.forEach(el => el.classList.add('hover'));
});
element.addEventListener('mouseleave', () => {
refs.forEach(el => el.classList.remove('hover'));
});
}
}