-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
1392 lines (1210 loc) · 62.1 KB
/
index.js
File metadata and controls
1392 lines (1210 loc) · 62.1 KB
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/** @typedef {import('./types.js').Bracket} Bracket */
/** @typedef {import('./types.js').Ruleset} Ruleset */
/** @typedef {import('./types.js').Team} Team */
// DOM ELEMENTS
const DIALOG_REFERENCE = document.querySelector("dialog");
/** @type {HTMLDivElement} */
const DIALOG_TITLE = DIALOG_REFERENCE.querySelector("div.kwbg-dialog-title");
/** @type {HTMLUListElement} */
const DIALOG_REQUIREMENTS = DIALOG_REFERENCE.querySelector("ul.kwbg-dialog-requirements");
/** @type {HTMLSelectElement} */
const DIALOG_MAPPOOL_ROUND_SELECTOR = DIALOG_REFERENCE.querySelector("select.kwbg-dialog-round-select");
const DIALOG_FORM = DIALOG_REFERENCE.querySelector("form");
/** @type {HTMLButtonElement} */
const DIALOG_HELPER_UPLOAD_BUTTON = DIALOG_FORM.querySelector("button.kwbg-dialog-upload-button-helper");
/** @type {HTMLButtonElement} */
const DIALOG_MAIN_UPLOAD_BUTTON = DIALOG_FORM.querySelector("button.kwbg-dialog-upload-button-main");
/** @type {HTMLDivElement} */
const DIALOG_UPLOAD_STATUS = DIALOG_REFERENCE.querySelector("div.kwbg-dialog-upload-status");
/** @type {HTMLSelectElement} */
const RULESET_SELECTOR = document.querySelector("select.kwbg-ruleset");
/** @type {HTMLSelectElement} */
const TOURNEY_TYPE_SELECTOR = document.querySelector("select.kwbg-tourney-type");
/** @type {HTMLDivElement} */
const THIRD_PLACE_MATCH_SETTING = document.querySelector("div.kwbg-third-place-match-setting");
/** @type {HTMLInputElement} */
const THIRD_PLACE_MATCH_CHECKBOX = document.querySelector("input.kwbg-third-place-match");
/** @type {HTMLSelectElement} */
const FIRST_ROUND_SELECTOR = document.querySelector("select.kwbg-first-round");
/** @type {HTMLButtonElement} */
const TEAMS_BUTTON = document.querySelector("button.kwbg-button-teams");
/** @type {HTMLButtonElement} */
const SEEDINGS_BUTTON = document.querySelector("button.kwbg-button-seedings");
/** @type {HTMLButtonElement} */
const MATCHES_BUTTON = document.querySelector("button.kwbg-button-matches");
/** @type {HTMLButtonElement} */
const MAPPOOL_BUTTON = document.querySelector("button.kwbg-button-mappool");
// VARIABLES & CONSTANTS
/** @type {Bracket} */
let bracket = {
"Ruleset": {},
"Matches": [],
"Rounds": [],
"Teams": [],
"Progressions": [],
"ChromaKeyWidth": 1024,
"PlayersPerTeam": 4,
"AutoProgressScreens": true,
"SplitMapPoolByMods": true,
"DisplayTeamSeeds": false
};
/** @type {Array<Team>} */
let teamsFromLatestFile = [];
/** @type {Object.<string, number>} */
let seedingsMappoolFromLatestFile = {};
let seedingsSuccessfullyUploaded = false;
/** @type {Array<{ left: Team, right: Team }>} */
let initialMatchesFromMainFile = [];
// Object key is a round value, beatmap key is a mod
/** @type {Object.<number, { bestOf: number, banCount: number, beatmaps: Object.<string, number> }>} */
let mappoolsFromLatestFile = {};
const MIN_TEAM_COUNT = 4;
// TODO: Team seeds can be arbitrary now, keep the checks only for mod and map seeds
const MAX_TEAM_COUNT = 256;
const MAX_SEED_ALLOWED = 256;
const BRACKET_GAP = 300;
const Y_DISTANCE_BASE = 100;
const X_POSITION_OFFSET = 200;
// EVENT LISTENERS
window.addEventListener("load", () => {
DIALOG_FORM.reset();
RULESET_SELECTOR.value = "osu";
bracket.Ruleset = {
"ShortName": "osu",
"Name": "osu!",
"InstantiationInfo": "osu.Game.Rulesets.Osu.OsuRuleset, osu.Game.Rulesets.Osu",
"Available": true,
};
TEAMS_BUTTON.addEventListener("click", () => showDialog("teams"));
SEEDINGS_BUTTON.addEventListener("click", () => showDialog("seedings"));
MATCHES_BUTTON.addEventListener("click", () => showDialog("matches"));
MAPPOOL_BUTTON.addEventListener("click", () => showDialog("mappool"));
TOURNEY_TYPE_SELECTOR.value = "single";
THIRD_PLACE_MATCH_CHECKBOX.checked = false;
FIRST_ROUND_SELECTOR.disabled = true;
SEEDINGS_BUTTON.disabled = true;
MATCHES_BUTTON.disabled = true;
MAPPOOL_BUTTON.disabled = true;
DIALOG_HELPER_UPLOAD_BUTTON.addEventListener("click", () => DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-helper").click());
DIALOG_MAIN_UPLOAD_BUTTON.addEventListener("click", () => DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-main").click());
setTextboxContent("bracket");
});
RULESET_SELECTOR.addEventListener("change", (event) => {
updateRulesetInBracketJSON(event.target.value);
setTextboxContent("bracket");
});
TOURNEY_TYPE_SELECTOR.addEventListener("change", (event) => {
// Show the "Include the match for the 3rd place" only if the tournament uses the single elimination format.
THIRD_PLACE_MATCH_SETTING.style.display = event.target.value === "single" ? "grid" : "none";
regenerateBracketJSON(teamsFromLatestFile.length, event.target.value === "double", false);
setTextboxContent("bracket");
});
THIRD_PLACE_MATCH_CHECKBOX.addEventListener("click", () => {
regenerateBracketJSON(teamsFromLatestFile.length, TOURNEY_TYPE_SELECTOR.value === "double", false);
setTextboxContent("bracket");
});
FIRST_ROUND_SELECTOR.addEventListener("change", (event) => {
// This is to prevent the bracket being created multiple times at once when uploading teams.
if (event.target.value !== "<upload teams first>") {
regenerateBracketJSON(event.target.value, TOURNEY_TYPE_SELECTOR.value === "double", false);
}
setTextboxContent("bracket");
});
// MAIN FUNCTIONS
/**
* Shows a file(-s) upload dialog to the user with instructions based on the category.
* @param {FileUploadCategory} category
*/
function showDialog(category) {
DIALOG_MAPPOOL_ROUND_SELECTOR.parentElement.style.display = "none";
removeAllChildElements(DIALOG_MAPPOOL_ROUND_SELECTOR);
DIALOG_HELPER_UPLOAD_BUTTON.style.display = "none";
DIALOG_MAIN_UPLOAD_BUTTON.disabled = false;
DIALOG_UPLOAD_STATUS.innerText = null;
DIALOG_FORM.reset();
let helperFileChangeListener = (event) => handleHelperFile(event, category);
let mainFileChangeListener = (event) => handleMainFile(event, category);
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-main").addEventListener("change", mainFileChangeListener);
switch (category) {
case "teams": {
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.innerText = "Upload teams...";
DIALOG_TITLE.innerText = "Upload teams";
DIALOG_REQUIREMENTS.innerHTML = "<li>Every line in the file must have the following order (no header for this one):<br><code>team name</code>;<code>team flag</code>;<code>team acronym</code>;<code>last year placing</code>;<code>list of players</code></li>" +
"<li>Solo teams can be represented with a simplified syntax:<br><code>player name</code>;<code>last year placing</code>;<code>player id</code>. The first 3 characters of the player's name will be used for the team acronym and the full name for the team flag</li>" +
"<li><code>Last year placing</code> can be set to 0 if not applicable, osu!(lazer) will show it as <code>N/A</code></li>" +
"<li>Examples:</li>" +
"<ul><li>Solo team: <code>KapiWilq</code>;<code>KA</code>;<code>KAP</code>;<code>0</code>;<code>8734129</code> OR <code>KapiWilq</code>;<code>0</code>;<code>8734129</code></li>" +
"<li>Regular team: <code>The Trash Network</code>;<code>TN</code>;<code>DNK</code>;<code>2</code>;<code>36458031</code>;<code>14857735</code>;<code>404169</code>;<code>6565046</code></li>" +
'<li><a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/teams-regular.tsv" target="_blank" rel="noopener noreferrer">Regular teams file (multiple people)</a> (<a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/teams-regular-importable.tsv" target="_blank" rel="noopener noreferrer">spreadsheet-friendly version</a>)</li>' +
'<li><a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/teams-solo.tsv" target="_blank" rel="noopener noreferrer">Solo teams file</a> (<a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/teams-solo-importable.tsv" target="_blank" rel="noopener noreferrer">spreadsheet-friendly version</a>)</li></ul>';
break;
}
case "seedings": {
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-helper").addEventListener("change", helperFileChangeListener);
DIALOG_HELPER_UPLOAD_BUTTON.style.display = "inline";
DIALOG_MAIN_UPLOAD_BUTTON.disabled = true;
DIALOG_HELPER_UPLOAD_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
DIALOG_HELPER_UPLOAD_BUTTON.innerText = "Upload the mappool...";
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.innerText = "Upload seedings...";
if (Object.keys(seedingsMappoolFromLatestFile).length > 0) {
DIALOG_MAIN_UPLOAD_BUTTON.disabled = false;
DIALOG_HELPER_UPLOAD_BUTTON.classList.add("kwbg-button-imported");
}
DIALOG_TITLE.innerText = "Upload seedings";
DIALOG_REQUIREMENTS.innerHTML = "<li>You need two files: the mappool and results with scores and seeds</li>" +
"<ul><li>The mappool is simple: first line is for mods for each map, e.g. NM1, DT3, HD2, AC3</li>" +
"<li>The second line is for IDs of each map</li></ul>" +
'<li>The seedings file is a modified version of <a href="https://github.com/DRCallaghan/osu-lazer-qualifier-results-bracket-generator/blob/06844c18bbf9aa505558b152572df5483a35c10e/db/scores.SAMPLE.csv" target="_blank" rel="noopener noreferrer">D I O\'s sample file</a> (header is optional here)</li>' +
"<li>Differences:</li>" +
"<ul><li>No <code>flag ISO</code> column</li>" +
"<li>No <code>team size</code> column</li>" +
"<li>No columns after the <code>team size</code> one</li></ul>" +
"<li>This generator supports every winning condition!</li>" +
"<ul><li>Accuracy must be either a number from 0 to 1 (untested) OR a percentage, e.g. both <code>0.9933</code> and <code>99.33%</code> would show as <code>9933</code> in the tournament client</li>" +
"<li>Combo (untested) must be a whole number AND OPTIONALLY have an <code>x</code> at the end (case-insensitive)</li></ul>" +
'<li>Examples: <a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/qualifiers-mappool.tsv" target="_blank" rel="noopener noreferrer">mappool</a> | <a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/qualifiers-results.tsv" target="_blank" rel="noopener noreferrer">seedings (regular teams; score; zoom out for this one)</a> (<a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/qualifiers-results-importable.tsv" target="_blank" rel="noopener noreferrer">spreadsheet-friendly version</a>)</li>';
break;
}
case "matches": {
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.innerText = "Upload initial matches...";
DIALOG_TITLE.innerText = "Upload initial matches";
DIALOG_REQUIREMENTS.innerHTML = "<li>Every line is only two columns: <code>left team name</code> and <code>right team name</code></li>" +
"<li>You can also put <code>acronym</code>, or <code>team seed</code> at the very first line of the file to tell the generator to use something else</li>" +
'<li>Examples: <a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/initial-matches-name.tsv" target="_blank" rel="noopener noreferrer">team name</a> (<a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/initial-matches-name-importable.tsv" target="_blank" rel="noopener noreferrer">spreadsheet-friendly version</a>) | <a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/initial-matches-acronym.tsv" target="_blank" rel="noopener noreferrer">team acronyms</a> | <a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/initial-matches-seed.tsv" target="_blank" rel="noopener noreferrer">team seeds</a></li>';
break;
}
case "mappool": {
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.innerText = "Upload the mappool...";
DIALOG_TITLE.innerText = "Upload the mappool for a specific round"
DIALOG_REQUIREMENTS.innerHTML = "<li>First line is optional: it's just <code>ban count</code> and <code>best of</code></li>" +
"<li>Next line is for mods for each map, e.g. NM1, DT3, HD2, AC3</li>" +
"<li>The last line is for IDs of each map</li>" +
'<li><a href="https://raw.githubusercontent.com/KapiWilq/bracket/main/examples/grand-finals-mappool.tsv" target="_blank" rel="noopener noreferrer">Example file</a></li>';
DIALOG_MAPPOOL_ROUND_SELECTOR.parentElement.style.display = "flex";
let firstRound = Number(FIRST_ROUND_SELECTOR.value);
for (let currentRoundValue = firstRound; currentRoundValue >= 1; currentRoundValue /= 2) {
let option = document.createElement("option");
option.value = currentRoundValue;
option.innerText = getRoundName(currentRoundValue);
if (currentRoundValue !== 1 || (currentRoundValue === 1 & TOURNEY_TYPE_SELECTOR.value === "double")) {
DIALOG_MAPPOOL_ROUND_SELECTOR.appendChild(option);
}
}
break;
}
default: {
setTextboxContent(`The "${category}" dialog type does not exist`);
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-helper").removeEventListener("change", helperFileChangeListener);
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-main").removeEventListener("change", mainFileChangeListener);
return;
}
}
DIALOG_REFERENCE.querySelector("button#kwbg-dialog-close").addEventListener("click", () => {
DIALOG_REFERENCE.close();
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-helper").removeEventListener("change", helperFileChangeListener);
DIALOG_FORM.querySelector("input.kwbg-dialog-upload-input-main").removeEventListener("change", mainFileChangeListener);
});
DIALOG_REFERENCE.showModal();
}
/**
* Reads the contents of the main file in order to pass correct options to the parser.
* @param {Event & { target: HTMLInputElement }} event
* @param {FileUploadCategory} category
* @returns
*/
function handleMainFile(event, category) {
if (event.target.files.length === 0) {
return;
}
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onloadend = () => {
try {
const fileContents = reader.result;
if (fileContents.includes(",")) {
tryParseMainFile(fileContents, category, ",");
} else if (fileContents.includes(";")) {
tryParseMainFile(fileContents, category, ";");
} else if (fileContents.includes("\t")) {
tryParseMainFile(fileContents, category, "\t");
} else {
throw new Error("Cannot parse the file; every line has an unsupported delimiter");
}
DIALOG_UPLOAD_STATUS.innerHTML = `${capitalizeFirstLetterOfString(category)} file imported successfully!`;
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.classList.add("kwbg-button-imported");
document.querySelector(`button.kwbg-button-${category}`).classList.remove("kwbg-button-failed");
document.querySelector(`button.kwbg-button-${category}`).classList.add("kwbg-button-imported");
} catch (error) {
DIALOG_UPLOAD_STATUS.innerHTML = `ERROR: ${error.message}`;
DIALOG_MAIN_UPLOAD_BUTTON.classList.remove("kwbg-button-imported");
DIALOG_MAIN_UPLOAD_BUTTON.classList.add("kwbg-button-failed");
document.querySelector(`button.kwbg-button-${category}`).classList.remove("kwbg-button-imported");
document.querySelector(`button.kwbg-button-${category}`).classList.add("kwbg-button-failed");
setTextboxContent("bracket");
}
};
}
/**
* Reads the contents of the helper file in order to pass correct options to the parser.
* @param {Event & { target: HTMLInputElement }} event
* @param {FileUploadCategory} category
* @returns
*/
function handleHelperFile(event, category) {
if (event.target.files.length === 0) {
return;
}
let file = event.target.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onloadend = () => {
try {
const fileContents = reader.result;
if (fileContents.includes(",")) {
tryParseHelperFile(fileContents, category, ",");
} else if (fileContents.includes(";")) {
tryParseHelperFile(fileContents, category, ";");
} else if (fileContents.includes("\t")) {
tryParseHelperFile(fileContents, category, "\t");
} else {
throw new Error("Cannot parse the file; every line has an unsupported delimiter");
}
// TODO: Make this text dynamic
DIALOG_UPLOAD_STATUS.innerHTML = "Qualifiers mappool file imported successfully!";
DIALOG_HELPER_UPLOAD_BUTTON.classList.remove("kwbg-button-failed");
DIALOG_HELPER_UPLOAD_BUTTON.classList.add("kwbg-button-imported");
DIALOG_MAIN_UPLOAD_BUTTON.disabled = false;
} catch (error) {
DIALOG_UPLOAD_STATUS.innerHTML = `ERROR: ${error.message}`;
DIALOG_HELPER_UPLOAD_BUTTON.classList.remove("kwbg-button-imported");
DIALOG_HELPER_UPLOAD_BUTTON.classList.add("kwbg-button-failed");
DIALOG_MAIN_UPLOAD_BUTTON.disabled = true;
document.querySelector(`button.kwbg-button-${category}`).classList.remove("kwbg-button-imported");
document.querySelector(`button.kwbg-button-${category}`).classList.add("kwbg-button-failed");
}
};
}
/**
* Tries to parse information about teams.
* @param {string} teamsFile
* @param {ValidDelimiter} delimiter
*/
function tryParseTeamsFile(teamsFile, delimiter) {
if (teamsFile.length === 0) {
throw new Error('The file might be empty (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
if (teamsFile.length < MIN_TEAM_COUNT) {
throw new Error(`Please upload at least ${MIN_TEAM_COUNT} teams`);
}
// TODO: Remove this maybe???
if (teamsFile.length > MAX_TEAM_COUNT) {
throw new Error(`You can only have up to ${MAX_TEAM_COUNT} teams`);
}
teamsFromLatestFile = [];
initialMatchesFromMainFile = [];
bracket.Matches = [];
bracket.Rounds = [];
bracket.Teams = teamsFromLatestFile;
bracket.Progressions = [];
const CONSTANTS = {
TEAM_NAME_IDX: 0,
TEAM_ACRONYM_LENGTH_MAX: 3,
LAST_YEAR_PLACEMENT_MAX: 256,
SOLO_TEAM_COLUMN_COUNT: 3,
SOLO_TEAM_LAST_YEAR_PLACEMENT_IDX: 1,
SOLO_TEAM_PLAYER_ID_IDX: 2
}
let potentialHeader = teamsFile[0].split(delimiter).filter((column) => column.trim() !== "");
// TODO: This is a very bandaid solution
if (potentialHeader.includes("NM1") || potentialHeader.includes("HD1") || potentialHeader.includes("HR1") || potentialHeader.includes("DT1") || potentialHeader.includes("EZ1")) {
throw new Error('This might be a wrong file (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
if (potentialHeader.length === 2 && isNaN(potentialHeader[1])) {
potentialHeader = teamsFile.shift();
} else if (potentialHeader.length >= 4 && isNaN(potentialHeader[3])) {
potentialHeader = teamsFile.shift();
}
/** @type {Set<string>} */
let acronyms = new Set();
for (let teamIdx = 0; teamIdx < teamsFile.length; teamIdx += 1) {
let teamSpec = teamsFile[teamIdx].split(delimiter).filter((column) => column.trim() !== "");
let teamName = sanitize(teamSpec[CONSTANTS.TEAM_NAME_IDX].trim());
// Regular teams have at least 5 columns worth of information.
if (teamSpec.length === 4 || teamSpec.length < CONSTANTS.SOLO_TEAM_COLUMN_COUNT) {
throw new Error(`Team "${teamName}" has an incorrect amount of information`);
}
if (teamSpec.length === CONSTANTS.SOLO_TEAM_COLUMN_COUNT) {
if (isNaN(teamSpec[CONSTANTS.SOLO_TEAM_LAST_YEAR_PLACEMENT_IDX]) || isNaN(teamSpec[CONSTANTS.SOLO_TEAM_PLAYER_ID_IDX])) {
throw new Error(`Team "${teamName}" has an invalid information order (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`);
}
if (Number(teamSpec[CONSTANTS.SOLO_TEAM_LAST_YEAR_PLACEMENT_IDX]) > CONSTANTS.LAST_YEAR_PLACEMENT_MAX || Number(teamSpec[CONSTANTS.SOLO_TEAM_LAST_YEAR_PLACEMENT_IDX]) < 0) {
throw new Error(`Team "${teamName}"'s last year placing cannot be a negative number or bigger than ${CONSTANTS.LAST_YEAR_PLACEMENT_MAX}`);
}
let acronym = String(teamSpec[CONSTANTS.TEAM_NAME_IDX]).trim().toUpperCase().substring(0, CONSTANTS.TEAM_ACRONYM_LENGTH_MAX);
if (acronyms.has(acronym)) {
throw new Error(`Team "${teamName}"'s acronym collides with team "${sanitize(teamsFromLatestFile.find((team) => team.Acronym === acronym).FullName)}"'s acronym`);
}
teamsFromLatestFile.push({
"FullName": String(teamSpec[CONSTANTS.TEAM_NAME_IDX]).trim(),
// This uses full name to minimize file name collisions
// Also remove characters from flag names that make operating systems complain
"FlagName": String(teamSpec[CONSTANTS.TEAM_NAME_IDX]).trim().toUpperCase().replace(/[*@"/<>:|?]/gu, ""),
"Acronym": acronym,
"SeedingResults": [],
"LastYearPlacing": Number(teamSpec[CONSTANTS.SOLO_TEAM_LAST_YEAR_PLACEMENT_IDX]),
"Players": [{ "id": Number(teamSpec[CONSTANTS.SOLO_TEAM_PLAYER_ID_IDX]) }]
});
} else {
let players = [];
for (let i = 4; i < teamSpec.length; i += 1) {
if (isNaN(teamSpec[i])) {
throw new Error(`Player #${i - 3} in team "${teamName}" has an invalid ID (${sanitize(teamSpec[i])})`);
}
players.push({ "id": Number(teamSpec[i]) });
}
// TODO: this is now a string in lazer, doesn't seem to enforce any concrete value, so probably remove?
if (Number(teamSpec[3]) > 256 || Number(teamSpec[3]) < 0) {
throw new Error(`Team "${teamName}"'s last year placing cannot be a negative number or bigger than 256`);
}
let acronym = String(teamSpec[2]).trim().toUpperCase().substring(0, 3);
if (acronyms.has(acronym)) {
throw new Error(`Team ${teamName} will create an acronym collision with team "${sanitize(teamsFromLatestFile.find((team) => team.Acronym === acronym).FullName)}"`);
}
teamsFromLatestFile.push({
"FullName": String(teamSpec[0]).trim(),
"FlagName": String(teamSpec[1]).trim(),
"Acronym": acronym,
"SeedingResults": [],
"LastYearPlacing": Number(teamSpec[3]),
"Players": players
});
}
}
teamsFromLatestFile.sort((a, b) => a.FullName.localeCompare(b.FullName));
bracket.Teams = teamsFromLatestFile;
SEEDINGS_BUTTON.disabled = false;
MATCHES_BUTTON.disabled = false;
MAPPOOL_BUTTON.disabled = false;
}
/**
* Tries to parse information about the results of qualifiers.
* @param {string} seedingsFile
* @param {ValidDelimiter} delimiter
*/
function tryParseSeedingsFile(seedingsFile, delimiter) {
let mods = Object.keys(seedingsMappoolFromLatestFile);
let uniqueMods = Array.from(new Set(mods.map((mod) => mod.substring(0, 2))));
for (let teamIdx = 0; teamIdx < seedingsFile.length; teamIdx += 1) {
let teamSpec = seedingsFile[teamIdx].split(delimiter).filter((column) => column.trim() !== "");
let teamName = sanitize(teamSpec[0].trim());
if (teamSpec.length < 1 + mods.length + 1 + uniqueMods.length + mods.length) {
throw new Error(`Team "${teamName}" is missing information (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`);
} else if (teamSpec.length > 1 + mods.length + 1 + uniqueMods.length + mods.length) {
throw new Error(`Team "${teamName}" might have too much information (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`);
}
let teamInBracket = bracket.Teams.find((team) => team.FullName === teamSpec[0].trim());
if (typeof (teamInBracket) === "undefined") {
throw new Error(`Team "${teamName}" does not exist in the bracket.json`);
}
teamInBracket.SeedingResults = [];
// Team seed
if (isNaN(teamSpec[1 + mods.length])) {
throw new Error(`Team seed of team ${teamName} is invalid (${sanitize(teamSpec[1 + mods.length])})`);
}
// TODO: Apparently this can be an arbitrary string now, remove
if (Number(teamSpec[1 + mods.length]) > MAX_SEED_ALLOWED || Number(teamSpec[1 + mods.length]) <= 0) {
throw new Error(`Team seed of team "${teamName}" is not a positive number that is ${MAX_SEED_ALLOWED} or smaller (${teamSpec[1 + mods.length]})`);
}
teamInBracket.Seed = String(teamSpec[1 + mods.length]).trim();
// Mod-specific seed (also initialize the beatmaps array for map-specific seeds)
for (let i = 0; i < uniqueMods.length; i += 1) {
if (isNaN(teamSpec[1 + mods.length + 1 + i])) {
throw new Error(`${uniqueMods[i]} seed for team ${teamName} is invalid (${sanitize(teamSpec[1 + mods.length + 1 + i])})`)
}
if (Number(teamSpec[1 + mods.length + 1 + i]) > MAX_SEED_ALLOWED || Number(teamSpec[1 + mods.length + 1 + i]) <= 0) {
throw new Error(`${uniqueMods[i]} seed for team "${teamName}" is not a positive number that is ${MAX_SEED_ALLOWED} or smaller (${teamSpec[1 + mods.length + 1 + i]})`);
}
teamInBracket.SeedingResults.push({
"Beatmaps": [],
"Mod": String(uniqueMods[i]),
"Seed": Number(teamSpec[1 + mods.length + 1 + i])
});
}
// Map-specific seeds
for (let i = 0; i < mods.length; i += 1) {
if (isNaN(teamSpec[1 + mods.length + 1 + uniqueMods.length + 1])) {
throw new Error(`${mods[i]} seed for team ${teamName} is invalid (${sanitize(teamSpec[1 + mods.length + 1 + uniqueMods.length + 1])})`);
}
if (Number(teamSpec[1 + mods.length + 1 + uniqueMods.length + i]) > MAX_SEED_ALLOWED || Number(teamSpec[1 + mods.length + 1 + uniqueMods.length + i]) <= 0) {
throw new Error(`${mods[i]} seed for team "${teamName}" is not a positive number that is ${MAX_SEED_ALLOWED} or smaller (${teamSpec[1 + mods.length + 1 + uniqueMods.length + i]})`);
}
let finalScore = 0;
// Accuracy: decimal number [0...1]
if (!isNaN(teamSpec[1 + i]) && Number(teamSpec[1 + i]) <= 1) {
finalScore = Number(Number(teamSpec[1 + i]).toFixed(4)) * 10000;
if (finalScore > 10000) {
throw new Error(`${mods[i]} accuracy for team "${teamName}" is weird (${finalScore / 100}%; if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`);
}
// Accuracy: percentage
} else if (isNaN(teamSpec[1 + i]) && String(teamSpec[1 + i]).includes('%')) {
finalScore = Number(Number(String(teamSpec[1 + i]).replace('%', '')).toFixed(2)) * 100;
if (finalScore > 10000) {
throw new Error(`${mods[i]} accuracy for team "${teamName}" is weird (${finalScore / 100}%; if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`);
}
// Combo
} else if (isNaN(teamSpec[1 + i]) && String(teamSpec[1 + i]).toLowerCase().includes('x')) {
finalScore = Number(String(teamSpec[1 + i]).toLowerCase().replace('x', ''));
if (Number(Math.ceil(finalScore)) !== Number(Math.floor(finalScore))) {
throw new Error(`${mods[i]} combo for team "${teamName}" must be a whole number (${sanitize(finalScore)}x)`);
}
// Score
} else if (!isNaN(teamSpec[1 + i])) {
finalScore = Number(teamSpec[1 + i]);
} else {
throw new Error(`${mods[i]} score for team "${teamName} is weird (${sanitize(finalScore)}; if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)`)
}
if (finalScore === NaN) {
throw new Error(`Couldn't parse ${mods[i]} seed for team "${teamName}", <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>`);
}
let modSpecificSeed = teamInBracket.SeedingResults.find((result) => result.Mod === String(mods[i].substring(0, 2)))
modSpecificSeed.Beatmaps.push({
"ID": Number(seedingsMappoolFromLatestFile[mods[i]]),
"Score": Number(finalScore),
"Seed": Number(teamSpec[1 + mods.length + 1 + uniqueMods.length + i])
});
}
}
}
/**
* Tries to parse information about initial matches.
* @param {string} matchesFile
* @param {ValidDelimiter} delimiter
* @param {"name" | "acronym" | "team seed"} fileMode
* @returns {Array<{ left: Team, right: Team }>}
*/
function tryParseMatchesFile(matchesFile, delimiter, fileMode) {
/** @type {Array<{ left: Team, right: Team }>} */
let matchList = [];
/** @type {Set<string>} */
let values = new Set();
for (let i = 0; i < matchesFile.length; i += 1) {
let matchSpec = matchesFile[i].split(delimiter).filter((column) => column.trim() !== "");
if (matchSpec.length > 2) {
throw new Error(`Line ${i + 1} has too much information`);
}
if (matchSpec.length < 2) {
throw new Error(`Line ${i + 1} has too little information`);
}
/** @type {Team} */
let leftTeam;
/** @type {Team} */
let rightTeam;
const LEFT_TEAM_IDX = 0, RIGHT_TEAM_IDX = 1;
if (fileMode === "name") {
leftTeam = bracket.Teams.find((team) => team.FullName === String(matchSpec[LEFT_TEAM_IDX]).trim());
// This replace HAS to be here
rightTeam = bracket.Teams.find((team) => team.FullName === String(matchSpec[RIGHT_TEAM_IDX]).trim().replace('\r', ''));
} else if (fileMode === "acronym") {
leftTeam = bracket.Teams.find((team) => team.Acronym === String(matchSpec[LEFT_TEAM_IDX]).trim());
rightTeam = bracket.Teams.find((team) => team.Acronym === String(matchSpec[RIGHT_TEAM_IDX]).trim().replace('\r', ''));
// } else if (fileMode === "flag") {
// leftTeam = bracket.Teams.find((team) => team.FlagName === String(matchSpec[LEFT_TEAM_IDX]).trim());
// rightTeam = bracket.Teams.find((team) => team.FlagName === String(matchSpec[RIGHT_TEAM_IDX]).trim().replace('\r', ''));
} else if (fileMode === "team seed") {
if (seedingsSuccessfullyUploaded === false) {
throw new Error('You need to upload seedings first to use the "team seed" mode');
}
if (isNaN(matchSpec[LEFT_TEAM_IDX])) {
throw new Error(`${sanitize(matchSpec[LEFT_TEAM_IDX])} is an invalid seed`);
}
if (isNaN(matchSpec[RIGHT_TEAM_IDX])) {
throw new Error(`${sanitize(matchSpec[RIGHT_TEAM_IDX])} is an invalid seed`);
}
if (Number(matchSpec[LEFT_TEAM_IDX]) > MAX_SEED_ALLOWED || Number(matchSpec[LEFT_TEAM_IDX]) < 0) {
throw new Error(`${sanitize(matchSpec[LEFT_TEAM_IDX])} is not a positive number that is ${MAX_SEED_ALLOWED} or smaller`);
}
if (Number(matchSpec[RIGHT_TEAM_IDX]) > MAX_SEED_ALLOWED || Number(matchSpec[RIGHT_TEAM_IDX]) < 0) {
throw new Error(`${sanitize(matchSpec[LEFT_TEAM_IDX])} is not a positive number that is ${MAX_SEED_ALLOWED} or smaller`);
}
leftTeam = bracket.Teams.find((team) => team.Seed === String(Number(matchSpec[LEFT_TEAM_IDX])));
rightTeam = bracket.Teams.find((team) => team.Seed === String(Number(matchSpec[RIGHT_TEAM_IDX])));
} else {
throw new Error(`Unsupported file mode "${fileMode}"`);
}
if (typeof (leftTeam) === "undefined") {
throw new Error(`Couldn't find the left team by its ${fileMode} (${sanitize(matchSpec[LEFT_TEAM_IDX])}, line ${i + 1})`);
} else {
if (values.has(String(matchSpec[LEFT_TEAM_IDX]).trim())) {
throw new Error(`The "${sanitize(matchSpec[LEFT_TEAM_IDX])}" ${fileMode} is duplicated`);
}
values.add(String(matchSpec[LEFT_TEAM_IDX]).trim());
}
if (typeof (rightTeam) === "undefined") {
throw new Error(`Couldn't find the right team by its ${fileMode} (${sanitize(matchSpec[RIGHT_TEAM_IDX].replace('\r', ''))}, line ${i + 1})`);
} else {
if (values.has(String(matchSpec[RIGHT_TEAM_IDX]).trim())) {
throw new Error(`The "${sanitize(matchSpec[RIGHT_TEAM_IDX])}" ${fileMode} is duplicated`);
}
values.add(String(matchSpec[RIGHT_TEAM_IDX]).trim());
}
matchList.push({
left: leftTeam,
right: rightTeam
});
}
return matchList;
}
/**
* Tries to parse information about the mappool for a specific round.
* @param {string} mappoolFile
* @param {ValidDelimiter} delimiter
*/
function tryParseMappoolFile(mappoolFile, delimiter) {
let banCount = 1, bestOf = 9;
let potentialHeader = mappoolFile[0].split(delimiter);
if (mappoolFile.length === 3 && potentialHeader.length === 2 && !isNaN(potentialHeader[0]) && !isNaN(potentialHeader[1])) {
banCount = Number(potentialHeader[0]);
bestOf = Number(potentialHeader[1]);
potentialHeader = mappoolFile.shift();
} else if (mappoolFile.length < 2 || mappoolFile.length > 3) {
throw new Error("The file must have either 2 or 3 lines");
}
if (banCount < 0) {
throw new Error(`Mappool cannot have a negative amount of bans (currently ${banCount})`);
}
if (banCount > 5) {
throw new Error(`Mappool can only have up to 5 bans (currently ${banCount})`);
}
if (bestOf < 3) {
throw new Error(`The "best of" value must be at least 3 (currently ${bestOf})`);
}
if (bestOf > 23) {
throw new Error(`The "best of" value must be at most 23 (currently ${bestOf})`);
}
if (bestOf % 2 === 0) {
throw new Error(`The "best of" value must be an odd number (currently ${bestOf})`);
}
let mods = mappoolFile[0].split(delimiter);
let uniqueMods = Array.from(new Set(mods));
let maps = mappoolFile[1].split(delimiter);
if (!mods.includes("NM1") && !mods.includes("HD1") && !mods.includes("HR1") && !mods.includes("DT1") && !mods.includes("EZ1")) {
throw new Error('This might be a wrong file (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
if (!isNaN(mods[1])) {
throw new Error('The mappool must be "horizontal" (see the example above)');
}
if (mods.length !== uniqueMods.length) {
throw new Error("At least one mod is duplicated");
}
if (mods.length !== maps.length) {
throw new Error("The amount of mods doesn't match the amount of map IDs");
}
mappoolsFromLatestFile[DIALOG_MAPPOOL_ROUND_SELECTOR.value] = {
banCount: banCount,
bestOf: bestOf,
beatmaps: mods.reduce((beatmaps, mod, index) => {
beatmaps[mod] = Number(maps[index]);
return beatmaps;
}, {})
};
}
/**
* Tries to parse the main file used to populate the `bracket.json`.
* @param {string} file
* @param {FileUploadCategory} category
* @param {ValidDelimiter} delimiter
*/
function tryParseMainFile(file, category, delimiter) {
if (delimiter !== "\t" && delimiter !== "," && delimiter !== ";") {
throw new Error("Cannot parse the file; every line has an unsupported delimiter");
}
switch (category) {
case "teams": {
Array.from(document.querySelector("div.kwbg-upload-buttons").children).forEach((button) => {
button.classList.remove("kwbg-button-imported", "kwbg-button-failed");
});
SEEDINGS_BUTTON.disabled = true;
MATCHES_BUTTON.disabled = true;
MAPPOOL_BUTTON.disabled = true;
removeAllChildElements(FIRST_ROUND_SELECTOR);
let optionPlaceholder = document.createElement("option");
optionPlaceholder.innerText = "<upload teams first>";
optionPlaceholder.value = "<upload teams first>";
FIRST_ROUND_SELECTOR.appendChild(optionPlaceholder);
FIRST_ROUND_SELECTOR.disabled = true;
const teamsFile = file.replace("\r\n", "\n").replace("\r", "\n").split("\n").filter((team) => team.trim() !== "");
tryParseTeamsFile(teamsFile, delimiter);
regenerateBracketJSON(teamsFromLatestFile.length, TOURNEY_TYPE_SELECTOR.value === "double");
break;
}
case "seedings": {
SEEDINGS_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
let seedingsFile = file.replace("\r\n", "\n").replace("\r", "\n").split("\n").filter((seeding) => seeding.trim() !== "");
if (seedingsFile.length === 0) {
throw new Error('The file might be empty (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
let potentialHeader = seedingsFile[0].split(delimiter).filter((column) => column.trim() !== "");
if (isNaN(potentialHeader[1])) {
potentialHeader = seedingsFile.shift();
}
tryParseSeedingsFile(seedingsFile, delimiter);
SEEDINGS_BUTTON.classList.add("kwbg-button-imported");
seedingsSuccessfullyUploaded = true;
break;
}
case "matches": {
MATCHES_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
let matchesFile = file.replace('\r\n', '\n').replace("\r", "\n").split("\n").filter((match) => match.trim() !== "");
if (matchesFile.length === 0) {
throw new Error('The file might be empty (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
let fileMode = matchesFile[0].split(delimiter);
if (fileMode.length === 1) {
fileMode = String(sanitize(matchesFile.shift()));
} else {
fileMode = "name";
}
// Reset
initialMatchesFromMainFile = [];
regenerateBracketJSON(teamsFromLatestFile.length, TOURNEY_TYPE_SELECTOR.value === "double", false);
initialMatchesFromMainFile = tryParseMatchesFile(matchesFile, delimiter, fileMode);
regenerateBracketJSON(teamsFromLatestFile.length, TOURNEY_TYPE_SELECTOR.value === "double", false);
break;
}
case "mappool": {
MAPPOOL_BUTTON.classList.remove("kwbg-button-imported", "kwbg-button-failed");
let mappoolFile = file.replace('\r\n', '\n').replace("\r", "\n").split("\n").filter((match) => match.trim() !== "");
if (mappoolFile.length === 0) {
throw new Error('The file might be empty (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
tryParseMappoolFile(mappoolFile, delimiter);
regenerateBracketJSON(teamsFromLatestFile.length, TOURNEY_TYPE_SELECTOR.value === "double", false);
break;
}
default: {
throw new Error(`Unsupported file category (${sanitize(category)})`);
}
}
setTextboxContent("bracket");
}
/**
* Tries to parse the helper file used to populate the `bracket.json`. Currently it's only used for the qualifiers mappool.
* @param {string} file
* @param {FileUploadCategory} category
* @param {ValidDelimiter} delimiter
*/
function tryParseHelperFile(file, category, delimiter) {
if (delimiter !== "\t" && delimiter !== "," && delimiter !== ";") {
throw new Error("Cannot parse the file; every line has an unsupported delimiter");
}
switch (category) {
case "seedings": {
SEEDINGS_BUTTON.classList.remove("kwbg-button-failed", "kwbg-button-imported");
seedingsSuccessfullyUploaded = false;
let mappoolFile = file.replace("\r\n", "\n").replace("\r", "\n").split("\n").filter((line) => line.trim() !== "");
if (mappoolFile.length !== 2) {
throw new Error("Incorrect amount of lines (must be two)");
}
let mods = mappoolFile[0].split(delimiter);
let uniqueMods = Array.from(new Set(mods));
let maps = mappoolFile[1].split(delimiter);
if (!mods.includes("NM1") && !mods.includes("HD1") && !mods.includes("HR1") && !mods.includes("DT1") && !mods.includes("EZ1")) {
throw new Error('This might be a wrong file (if not, <a href="https://github.com/KapiWilq/bracket#how-to-yell-at-dev" target="_blank" rel="noopener noreferrer">yell at dev</a>)');
}
if (!isNaN(mods[1])) {
throw new Error('The mappool must be "horizontal" (see the example above)');
}
if (mods.length !== uniqueMods.length) {
throw new Error("At least one mod is duplicated");
}
if (mods.length !== maps.length) {
throw new Error("The amount of mods doesn't match the amount of map IDs");
}
seedingsMappoolFromLatestFile = mods.reduce((mappool, mod, index) => {
mappool[sanitize(mod)] = Number(maps[index]);
return mappool;
}, {});
break;
}
default: {
throw new Error(`Unsupported file category (${sanitize(category)})`);
}
}
}
/**
* Main function that generates the `bracket.json` file.
* @param {number} teamsCount Number of teams to be in the file.
* @param {boolean} isDoubleElimination Whether or not the tournament uses the double elimination format.
* @param {boolean} [regenerateFirstRoundDropdown=true] Whether or not to regenerate the round picker dropdown on the main screen.
*/
function regenerateBracketJSON(teamsCount, isDoubleElimination, regenerateFirstRoundDropdown = true) {
if (teamsCount === 0) {
return;
}
bracket.Matches = [];
bracket.Rounds = [];
bracket.Progressions = [];
const firstRoundValue = getFirstRoundValue(teamsCount, regenerateFirstRoundDropdown);
if (regenerateFirstRoundDropdown === true) {
repopulateFirstRoundDropdown(firstRoundValue);
}
generateRounds(firstRoundValue, isDoubleElimination);
populateMappoolsInRounds(firstRoundValue);
/** @type {BracketCache} */
let cache = {
matchID: 1,
roundNumber: 1,
xPosition: 0,
yDistanceMultiplier: 1,
yStartingOffsetForRound: 0,
yStartingAnchor: 0,
idOffset: firstRoundValue / 4
}
cache = generateWinnersBracket(firstRoundValue, isDoubleElimination, cache);
if (initialMatchesFromMainFile.length > 0) {
generateInitialMatches(firstRoundValue);
}
if (isDoubleElimination === true) {
cache = generateLosersBracket(firstRoundValue, cache);
generateGrandFinals(cache.matchID);
} else if (THIRD_PLACE_MATCH_CHECKBOX.checked === true) {
generateThirdPlaceMatch(cache.matchID);
}
}
// HELPER FUNCTIONS
/**
* Sets the text content of the output textbox, usually the finished `bracket.json`.
* @param {"bracket"} message
*/
function setTextboxContent(message) {
document.querySelector("textarea.kwbg-output").value = message === "bracket"
? JSON.stringify(bracket, null, 2)
: message;
}
/**
* Updates the `Ruleset` object in the `bracket.json`.
* @param {Ruleset} ruleset
*/
function updateRulesetInBracketJSON(ruleset) {
switch (ruleset) {
case "osu": {
bracket.Ruleset = {
"ShortName": "osu",
"Name": "osu!",
"InstantiationInfo": "osu.Game.Rulesets.Osu.OsuRuleset, osu.Game.Rulesets.Osu",
"Available": true,
}
return;
}
case "taiko": {
bracket.Ruleset = {
"ShortName": "taiko",
"OnlineID": 1,
"Name": "osu!taiko",
"InstantiationInfo": "osu.Game.Rulesets.Taiko.TaikoRuleset, osu.Game.Rulesets.Taiko",
"Available": true,
}
return;
}
case "fruits": {
bracket.Ruleset = {
"ShortName": "fruits",
"OnlineID": 2,
"Name": "osu!catch",
"InstantiationInfo": "osu.Game.Rulesets.Catch.CatchRuleset, osu.Game.Rulesets.Catch",
"Available": true,
}
return;
}
case "mania": {
bracket.Ruleset = {
"ShortName": "mania",
"OnlineID": 3,
"Name": "osu!mania",
"InstantiationInfo": "osu.Game.Rulesets.Mania.ManiaRuleset, osu.Game.Rulesets.Mania",
"Available": true,
}
return;
}
default: {
setTextboxContent(`The "${ruleset}" ruleset is not supported`);
return;
}
}
}
/**
* Removes all child elements of an HTML element.
* @param {HTMLElement} element
*/
function removeAllChildElements(element) {
if (element === undefined) { return; }
while (element.firstChild !== null) { element.removeChild(element.lastChild); }
}
/**
* Capitalizes the first letter of a string.
* @param {any} str
* @returns {string}
*/
function capitalizeFirstLetterOfString(str) {
return String(str).charAt(0).toUpperCase() + String(str).slice(1);
}
/**
* Sanitizes anything for use anywhere.
* @param {any} toBeSanitized
* @returns {string}
*/
function sanitize(toBeSanitized) {
return String(toBeSanitized).replaceAll(/&/g, "&")
.replaceAll(/</g, "<")