Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
968 lines (863 loc) · 33.1 KB
/
Copy pathscript.js
File metadata and controls
968 lines (863 loc) · 33.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
const MEDAL_CLASS = {
金: "medal-gold",
银: "medal-silver",
铜: "medal-bronze",
冠军: "podium-champion",
亚军: "podium-runner-up",
季军: "podium-third",
};
const MEDAL_ORDER = ["金", "银", "铜"];
const PODIUM_ORDER = ["冠军", "亚军", "季军"];
const STATISTIC_ORDER = ["冠军", "亚军", "季军", ...MEDAL_ORDER];
const STATISTIC_LABEL = { 冠军: "冠", 亚军: "亚", 季军: "季" };
const PLAYER_MEDAL_POINTS = { 金: 4, 银: 2, 铜: 1 };
const FINAL_CONTESTS = new Set(["ICPC EC Final", "CCPC Final"]);
const collator = new Intl.Collator("zh-CN", { numeric: true });
const seasonList = document.querySelector("#season-list");
const loadingStatus = document.querySelector("#loading-status");
const awardFilterButtons = document.querySelectorAll(".filter-switch");
const playerList = document.querySelector("#player-list");
const playerLoadingStatus = document.querySelector("#player-loading-status");
const playerTimeDecayInput = document.querySelector("#player-time-decay");
const playerTimeDecayValue = document.querySelector("#player-time-decay-value");
const personDialog = document.querySelector("#person-dialog");
const personName = document.querySelector("#person-name");
const personSummary = document.querySelector("#person-summary");
const personRecordsBody = document.querySelector("#person-records-body");
const contestDialog = document.querySelector("#contest-dialog");
const contestName = document.querySelector("#contest-name");
const contestRecordsBody = document.querySelector("#contest-records-body");
const menuToggle = document.querySelector("#menu-toggle");
const menuClose = document.querySelector("#menu-close");
const siteSidebar = document.querySelector("#site-sidebar");
const sidebarBackdrop = document.querySelector("#sidebar-backdrop");
const sidebarFolderToggles = document.querySelectorAll(".sidebar-folder-toggle");
const boardTree = document.querySelector("#board-tree");
const documentTree = document.querySelector("#document-tree");
const pageTitle = document.querySelector("#page-title");
const awardsPage = document.querySelector("#awards-page");
const playersPage = document.querySelector("#players-page");
const boardPage = document.querySelector("#board-page");
const boardFrame = document.querySelector("#board-frame");
const calendarPage = document.querySelector("#calendar-page");
const calendarMonth = document.querySelector("#calendar-month");
const calendarGrid = document.querySelector("#calendar-grid");
const calendarPrevious = document.querySelector("#calendar-previous");
const calendarNext = document.querySelector("#calendar-next");
const introductionPath = "documents/社团与竞赛简介.pdf";
const introductionTitle = "社团与竞赛简介";
if (!window.location.hash) window.location.replace("#introduction");
let records = [];
let wfQualifications = [];
let firstBloodIndex = new Map();
let boardTreeData = [];
let documentTreeData = [];
let activeArchivePath = "";
let calendarEvents = [];
let displayedCalendarMonth = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
let seasonsRendered = false;
let playersRendered = false;
let playerTimeDecay = 0.8;
let latestAwardSeasonStart = 0;
const awardFilters = {
source: new Set(["ICPC", "CCPC"]),
type: new Set(["regional", "final", "women"]),
};
function createElement(tag, className, text) {
const element = document.createElement(tag);
if (className) element.className = className;
if (text !== undefined) element.textContent = text;
return element;
}
function seasonLabel(season) {
return season.replace("-", "—");
}
function seasonStart(season) {
return Number.parseInt(season.split("-")[0], 10);
}
function contestSource(contest) {
return contest.startsWith("CCPC") ? "CCPC" : "ICPC";
}
function contestType(contest) {
if (FINAL_CONTESTS.has(contest)) return "final";
if (contest === "CCPC 女生赛") return "women";
return "regional";
}
function recordMatchesFilters(record) {
return (
awardFilters.source.has(contestSource(record.contest)) &&
awardFilters.type.has(contestType(record.contest))
);
}
function filteredRecords() {
return records.filter(recordMatchesFilters);
}
function countMedals(items) {
const counts = { 冠军: 0, 亚军: 0, 季军: 0, 金: 0, 银: 0, 铜: 0 };
for (const item of items) {
counts[item.award] += 1;
if (item.podium) counts[item.podium] += 1;
}
return counts;
}
function validateRecords(data) {
if (!Array.isArray(data)) throw new Error("奖项数据不是数组");
return data.map((record) => {
const validAward = MEDAL_ORDER.includes(record.award);
const validRank = record.rank === null || Number.isInteger(record.rank);
const validPodium =
record.podium === undefined || record.podium === null || PODIUM_ORDER.includes(record.podium);
if (
!record.season ||
!record.contest ||
!record.team ||
!Array.isArray(record.members) ||
record.members.length === 0 ||
!validAward ||
!validRank ||
!validPodium ||
(record.podium && record.award !== "金")
) {
throw new Error("发现格式不正确的奖项记录");
}
return record;
});
}
function validateWfQualifications(data) {
if (!Array.isArray(data)) throw new Error("WF 数据不是数组");
return data.map((qualification) => {
if (!qualification.season || !qualification.team) {
throw new Error("发现格式不正确的 WF 记录");
}
return qualification;
});
}
function validateFirstBlood(data) {
if (!Array.isArray(data)) throw new Error("一血数据不是数组");
return data.map((firstBlood) => {
if (
!firstBlood.season ||
!firstBlood.contest ||
!firstBlood.team ||
!firstBlood.problem ||
!firstBlood.color ||
!firstBlood.textColor
) {
throw new Error("发现格式不正确的一血记录");
}
return firstBlood;
});
}
function validateArchiveTree(data, label) {
if (!Array.isArray(data)) throw new Error(`${label}数据不是数组`);
function validateNodes(nodes) {
return nodes.map((node) => {
if (!node.title || (!node.path && !Array.isArray(node.children))) {
throw new Error(`发现格式不正确的${label}记录`);
}
if (node.children) {
if (!Array.isArray(node.children)) throw new Error(`${label}目录格式不正确`);
node.children = validateNodes(node.children);
}
return node;
});
}
return validateNodes(data);
}
function validateBoards(data) {
return validateArchiveTree(data, "比赛榜单");
}
function validateDocuments(data) {
return validateArchiveTree(data, "资料与通知");
}
function validateCalendar(data) {
if (!data || !Array.isArray(data.events)) throw new Error("比赛日历数据不是数组");
return data.events.map((event) => {
if (
!/^\d{4}-\d{2}-\d{2}$/.test(event.date) ||
!event.type ||
!event.city ||
!event.school
) {
throw new Error("发现格式不正确的比赛日历记录");
}
return event;
});
}
function recordKey(record) {
return JSON.stringify([record.season, record.contest, record.team]);
}
function indexFirstBlood(items) {
const index = new Map();
for (const item of items) {
const key = recordKey(item);
if (!index.has(key)) index.set(key, []);
index.get(key).push(item);
}
return index;
}
function archiveNodeByPath(nodes, path) {
for (const node of nodes) {
if (node.path === path) return node;
if (node.children) {
const found = archiveNodeByPath(node.children, path);
if (found) return found;
}
}
return null;
}
function boardFormat(path) {
const extension = path.split(/[?#]/, 1)[0].split(".").pop().toLowerCase();
if (extension === "pdf") return "pdf";
if (extension === "mhtml" || extension === "mht") return "mhtml";
return "html";
}
function renderArchiveTree(nodes, parent, route, dataAttribute) {
for (const node of nodes) {
if (node.children) {
const folder = createElement("details", "board-folder");
const summary = createElement("summary", "board-folder-summary", node.title);
const children = createElement("div", "board-folder-children");
folder.append(summary, children);
parent.append(folder);
renderArchiveTree(node.children, children, route, dataAttribute);
continue;
}
const link = createElement("a", "board-link", node.title);
link.href = `#${route}=${encodeURIComponent(node.path)}`;
link.dataset[dataAttribute] = node.path;
parent.append(link);
}
}
function renderArchiveMenus() {
boardTree.replaceChildren();
documentTree.replaceChildren();
renderArchiveTree(boardTreeData, boardTree, "board", "boardPath");
renderArchiveTree(documentTreeData, documentTree, "document", "documentPath");
}
function calendarDateKey(year, month, day) {
return `${year}-${String(month + 1).padStart(2, "0")}-${String(day).padStart(2, "0")}`;
}
function appendCalendarEvents(cell, dateKey, eventsByDate) {
for (const event of eventsByDate.get(dateKey) || []) {
const item = createElement("div", "calendar-event");
item.append(
createElement("strong", "calendar-event-type", event.type),
createElement("span", "calendar-event-detail", `${event.city} · ${event.school}`),
);
cell.append(item);
}
}
function renderCalendar() {
const year = displayedCalendarMonth.getFullYear();
const month = displayedCalendarMonth.getMonth();
const today = new Date();
const eventsByDate = new Map();
for (const event of calendarEvents) {
if (!eventsByDate.has(event.date)) eventsByDate.set(event.date, []);
eventsByDate.get(event.date).push(event);
}
calendarMonth.textContent = `${year} 年 ${month + 1} 月`;
calendarGrid.replaceChildren();
for (const weekday of ["一", "二", "三", "四", "五", "六", "日"]) {
calendarGrid.append(createElement("div", "calendar-weekday", `周${weekday}`));
}
const leadingDays = (new Date(year, month, 1).getDay() + 6) % 7;
const previousMonthDays = new Date(year, month, 0).getDate();
for (let day = previousMonthDays - leadingDays + 1; day <= previousMonthDays; day += 1) {
const cell = createElement("article", "calendar-day calendar-day-adjacent");
cell.append(createElement("h3", "calendar-day-number", String(day)));
const previousMonth = new Date(year, month - 1, day);
appendCalendarEvents(
cell,
calendarDateKey(previousMonth.getFullYear(), previousMonth.getMonth(), day),
eventsByDate,
);
calendarGrid.append(cell);
}
const daysInMonth = new Date(year, month + 1, 0).getDate();
for (let day = 1; day <= daysInMonth; day += 1) {
const dateKey = calendarDateKey(year, month, day);
const cell = createElement("article", "calendar-day");
if (year === today.getFullYear() && month === today.getMonth() && day === today.getDate()) {
cell.classList.add("is-today");
}
cell.append(createElement("h3", "calendar-day-number", String(day)));
appendCalendarEvents(cell, dateKey, eventsByDate);
calendarGrid.append(cell);
}
const trailingDays = (7 - ((leadingDays + daysInMonth) % 7)) % 7;
for (let day = 1; day <= trailingDays; day += 1) {
const cell = createElement("article", "calendar-day calendar-day-adjacent");
cell.append(createElement("h3", "calendar-day-number", String(day)));
const nextMonth = new Date(year, month + 1, day);
appendCalendarEvents(
cell,
calendarDateKey(nextMonth.getFullYear(), nextMonth.getMonth(), day),
eventsByDate,
);
calendarGrid.append(cell);
}
}
function setMenuOpen(open) {
siteSidebar.classList.toggle("is-open", open);
sidebarBackdrop.hidden = !open;
siteSidebar.setAttribute("aria-hidden", String(!open));
menuToggle.setAttribute("aria-expanded", String(open));
menuToggle.setAttribute("aria-label", open ? "关闭菜单" : "打开菜单");
document.body.classList.toggle("menu-open", open);
}
function renderPage() {
const hash = window.location.hash;
const boardMatch = hash.match(/^#board=(.*)$/);
const documentMatch = hash.match(/^#document=(.*)$/);
const boardPath = boardMatch ? decodeURIComponent(boardMatch[1]) : "";
const documentPath = documentMatch ? decodeURIComponent(documentMatch[1]) : "";
const board = boardPath ? archiveNodeByPath(boardTreeData, boardPath) : null;
const documentItem = documentPath ? archiveNodeByPath(documentTreeData, documentPath) : null;
const archiveItem = board || documentItem;
const isIntroduction = hash === "#introduction";
const isCalendar = hash === "#calendar";
const isPlayers = hash === "#players";
if (archiveItem || isIntroduction) {
const path = archiveItem ? archiveItem.path : introductionPath;
const title = archiveItem ? archiveItem.title : introductionTitle;
const format = archiveItem ? archiveItem.format || boardFormat(path) : "pdf";
activeArchivePath = archiveItem ? path : "";
awardsPage.hidden = true;
playersPage.hidden = true;
boardPage.hidden = false;
calendarPage.hidden = true;
boardFrame.dataset.format = format;
if (boardFrame.getAttribute("src") !== path) boardFrame.src = path;
boardFrame.title = title;
pageTitle.textContent = title;
document.title = `${title} · WHU ACM-ICPC`;
} else {
if (activeArchivePath || boardFrame.hasAttribute("src")) {
boardFrame.removeAttribute("src");
delete boardFrame.dataset.format;
}
activeArchivePath = "";
awardsPage.hidden = isCalendar || isPlayers;
playersPage.hidden = !isPlayers;
boardPage.hidden = true;
calendarPage.hidden = !isCalendar;
pageTitle.textContent = isCalendar ? "比赛日历" : isPlayers ? "选手名录" : "奖牌陈列室";
document.title = `${pageTitle.textContent} · WHU ACM-ICPC`;
if (isCalendar) renderCalendar();
}
for (const link of boardTree.querySelectorAll("[data-board-path]")) {
link.classList.toggle("is-active", link.dataset.boardPath === activeArchivePath);
}
for (const link of documentTree.querySelectorAll("[data-document-path]")) {
link.classList.toggle("is-active", link.dataset.documentPath === activeArchivePath);
}
for (const link of document.querySelectorAll("[data-page]")) {
link.classList.toggle(
"is-active",
(link.dataset.page === "medals" &&
!archiveItem &&
!isIntroduction &&
!isCalendar &&
!isPlayers) ||
(link.dataset.page === "introduction" && isIntroduction) ||
(link.dataset.page === "players" && isPlayers) ||
(link.dataset.page === "calendar" && isCalendar),
);
}
}
function wfBadge(className = "") {
const badge = createElement("span", `wf-badge ${className}`.trim(), "WF");
badge.title = "World Finals";
badge.setAttribute("aria-label", "World Finals");
return badge;
}
function seasonWfTeams(season, seasonRecords) {
const visibleIcpcTeams = new Set(
seasonRecords
.filter((record) => contestSource(record.contest) === "ICPC")
.map((record) => record.team),
);
return wfQualifications
.filter((qualification) => qualification.season === season)
.filter((qualification) => visibleIcpcTeams.has(qualification.team))
.map((qualification) => qualification.team);
}
function medalCountElement(award, count) {
const item = createElement("span", `medal-count ${MEDAL_CLASS[award]}`);
item.append(
createElement("span", "", STATISTIC_LABEL[award] || award),
createElement("strong", "", count),
);
return item;
}
function personHasWfQualification(honors) {
return honors.some(
(honor) =>
contestSource(honor.contest) === "ICPC" &&
wfQualifications.some(
(qualification) =>
qualification.season === honor.season && qualification.team === honor.team,
),
);
}
function resultLabel(record) {
return record.podium || `${record.award}奖`;
}
function personButton(name) {
const button = createElement("button", "person-button", name);
button.type = "button";
button.dataset.person = name;
button.setAttribute("aria-label", `查看 ${name} 的获奖记录`);
return button;
}
function contestButton(contest) {
const button = createElement("button", "contest-button", contest);
button.type = "button";
button.dataset.contest = contest;
button.setAttribute("aria-label", `查看 ${contest} 的获奖记录`);
return button;
}
function firstBloodElement(firstBlood) {
const balloon = createElement("span", "first-blood-balloon", firstBlood.problem);
balloon.style.setProperty("--balloon-color", firstBlood.color);
balloon.style.setProperty("--balloon-text", firstBlood.textColor);
balloon.title = `${firstBlood.problem} 题全场一血`;
balloon.setAttribute("aria-label", `${firstBlood.problem} 题全场一血`);
return balloon;
}
function resultElement(record, includeRank = true) {
const label = resultLabel(record);
const result = createElement("span", `result ${MEDAL_CLASS[record.podium || record.award]}`);
result.append(document.createTextNode(label));
if (includeRank && record.rank !== null) {
result.append(createElement("span", "result-rank", ` · ${record.rank}`));
}
for (const firstBlood of firstBloodIndex.get(recordKey(record)) || []) {
result.append(firstBloodElement(firstBlood));
}
result.title = record.rank === null ? label : `${label},第 ${record.rank} 名`;
return result;
}
function teamScore(team) {
const counts = countMedals(team.records);
return [counts.金, counts.银, counts.铜, team.records.length];
}
function teamBestRank(team) {
const ranks = team.records
.map((record) => record.rank)
.filter((rank) => Number.isInteger(rank));
return ranks.length > 0 ? Math.min(...ranks) : Number.POSITIVE_INFINITY;
}
function compareTeams(left, right) {
const leftScore = teamScore(left);
const rightScore = teamScore(right);
for (let index = 0; index < leftScore.length; index += 1) {
if (leftScore[index] !== rightScore[index]) return rightScore[index] - leftScore[index];
}
const leftBestRank = teamBestRank(left);
const rightBestRank = teamBestRank(right);
if (leftBestRank !== rightBestRank) return leftBestRank - rightBestRank;
return collator.compare(left.team, right.team);
}
function comparePlayers(left, right) {
const leftScore = weightedPlayerScore(left);
const rightScore = weightedPlayerScore(right);
for (let index = 0; index < leftScore.length; index += 1) {
const difference = rightScore[index] - leftScore[index];
if (Math.abs(difference) > 1e-9) return difference;
}
const leftBestRank = teamBestRank(left);
const rightBestRank = teamBestRank(right);
if (leftBestRank !== rightBestRank) return leftBestRank - rightBestRank;
return collator.compare(left.name, right.name);
}
function weightedPlayerScore(player) {
const weightedCounts = { 金: 0, 银: 0, 铜: 0 };
let points = 0;
for (const record of player.records) {
const elapsedSeasons = Math.max(0, latestAwardSeasonStart - seasonStart(record.season));
const timeWeight = playerTimeDecay ** elapsedSeasons;
const type = contestType(record.contest);
const contestWeight = type === "final" ? 1.5 : type === "women" ? 1 / 1.5 : 1;
const weight = timeWeight * contestWeight;
weightedCounts[record.award] += weight;
points += PLAYER_MEDAL_POINTS[record.award] * weight;
}
return [points, weightedCounts.金, weightedCounts.银, weightedCounts.铜];
}
function playerHistoryTable(honors, name) {
const wrap = createElement("div", "player-history-wrap");
const table = createElement("table", "person-records player-history-table");
const head = document.createElement("thead");
const headRow = document.createElement("tr");
for (const label of ["赛季", "队伍", "比赛", "成绩"]) {
const heading = createElement("th", "", label);
heading.scope = "col";
headRow.append(heading);
}
head.append(headRow);
const body = document.createElement("tbody");
const sortedHonors = [...honors].sort(
(left, right) =>
seasonStart(right.season) - seasonStart(left.season) ||
collator.compare(left.contest, right.contest) ||
(left.rank ?? Number.POSITIVE_INFINITY) - (right.rank ?? Number.POSITIVE_INFINITY),
);
for (const honor of sortedHonors) {
const row = document.createElement("tr");
row.append(
createElement("td", "", seasonLabel(honor.season)),
createElement("td", "", honor.team),
createElement("td", "", honor.contest),
);
const result = document.createElement("td");
result.append(resultElement(honor));
row.append(result);
body.append(row);
}
table.append(head, body);
wrap.append(table);
wrap.setAttribute("aria-label", `${name} 的历次奖牌`);
return wrap;
}
function renderPlayer(player) {
const details = createElement("details", "player-entry");
details.dataset.playerName = player.name;
const summary = document.createElement("summary");
const identity = createElement("span", "player-identity");
const name = createElement("span", "player-name", player.name);
const latestSeason = player.records.reduce((latest, record) => {
if (!latest || seasonStart(record.season) > seasonStart(latest)) return record.season;
return latest;
}, "");
const lastSeason = createElement(
"span",
"player-last-season",
`最后参赛于 ${seasonLabel(latestSeason)} 赛季`,
);
identity.append(name, lastSeason);
const counts = countMedals(player.records);
const countGroup = createElement("span", "player-summary-medals medal-counts");
if (personHasWfQualification(player.records)) {
countGroup.append(wfBadge("wf-person-badge player-wf-badge"));
}
for (const award of STATISTIC_ORDER) {
countGroup.append(medalCountElement(award, counts[award]));
}
const toggle = createElement("span", "player-toggle");
toggle.setAttribute("aria-hidden", "true");
summary.append(identity, countGroup, toggle);
details.append(summary, playerHistoryTable(player.records, player.name));
return details;
}
function renderPlayers() {
const expandedPlayers = new Set(
[...playerList.querySelectorAll(".player-entry[open]")].map(
(player) => player.dataset.playerName,
),
);
const players = new Map();
for (const record of filteredRecords()) {
for (const member of new Set(record.members)) {
if (!players.has(member)) players.set(member, { name: member, records: [] });
players.get(member).records.push(record);
}
}
const sortedPlayers = [...players.values()].sort(comparePlayers);
playerList.replaceChildren();
if (sortedPlayers.length === 0) {
playerList.append(createElement("p", "award-filter-empty", "当前筛选条件下没有选手记录。"));
playersRendered = records.length > 0;
return;
}
for (const player of sortedPlayers) {
const playerElement = renderPlayer(player);
playerElement.open = playersRendered && expandedPlayers.has(player.name);
playerList.append(playerElement);
}
playersRendered = true;
}
function seasonTable(seasonRecords, season) {
const contests = [...new Set(seasonRecords.map((record) => record.contest))];
const wfTeams = new Set(seasonWfTeams(season, seasonRecords));
const teams = new Map();
for (const record of seasonRecords) {
const key = JSON.stringify([record.team, [...record.members].sort(collator.compare)]);
if (!teams.has(key)) {
teams.set(key, {
team: record.team,
members: record.members,
records: [],
results: new Map(),
});
}
const team = teams.get(key);
team.records.push(record);
if (!team.results.has(record.contest)) team.results.set(record.contest, []);
team.results.get(record.contest).push(record);
}
const wrap = createElement("div", "season-table-wrap");
wrap.tabIndex = 0;
wrap.setAttribute("role", "region");
wrap.setAttribute("aria-label", `${seasonLabel(season)} 赛季成绩表,可横向滚动`);
const table = createElement("table", "season-table");
const head = document.createElement("thead");
const headRow = document.createElement("tr");
const teamHeading = createElement("th", "team-heading", "队伍名");
const memberHeading = createElement("th", "member-heading", "队员");
teamHeading.scope = "col";
memberHeading.scope = "col";
headRow.append(teamHeading, memberHeading);
for (const contest of contests) {
const heading = createElement("th", "contest-heading");
heading.scope = "col";
heading.append(contestButton(contest));
headRow.append(heading);
}
head.append(headRow);
const body = document.createElement("tbody");
for (const team of [...teams.values()].sort(compareTeams)) {
const row = document.createElement("tr");
const teamCell = createElement("td", "team-cell");
if (wfTeams.has(team.team)) {
teamCell.append(wfBadge("wf-team-badge"), document.createTextNode(team.team));
} else {
teamCell.textContent = team.team;
}
row.append(teamCell);
const membersCell = createElement("td", "member-cell");
team.members.forEach((member, index) => {
if (index > 0) membersCell.append(createElement("span", "member-separator", " · "));
membersCell.append(personButton(member));
});
row.append(membersCell);
for (const contest of contests) {
const cell = createElement("td", "result-cell");
for (const record of team.results.get(contest) || []) {
cell.append(resultElement(record));
}
row.append(cell);
}
body.append(row);
}
table.append(head, body);
wrap.append(table);
return wrap;
}
function renderSeason(season, seasonRecords, index) {
const details = createElement("details", "season");
details.open = index === 0;
const summary = document.createElement("summary");
const title = createElement("span", "season-title");
title.append(createElement("span", "season-years", seasonLabel(season)));
const counts = countMedals(seasonRecords);
const countGroup = createElement("span", "medal-counts");
const wfTeams = seasonWfTeams(season, seasonRecords);
if (wfTeams.length > 0) {
countGroup.append(wfBadge("wf-season-badge"));
} else {
const placeholder = createElement("span", "wf-season-placeholder");
placeholder.setAttribute("aria-hidden", "true");
countGroup.append(placeholder);
}
for (const award of STATISTIC_ORDER) {
countGroup.append(medalCountElement(award, counts[award]));
}
const toggle = createElement("span", "season-toggle");
toggle.setAttribute("aria-hidden", "true");
summary.append(title, countGroup, toggle);
const content = createElement("div", "season-content");
content.append(seasonTable(seasonRecords, season));
details.append(summary, content);
return details;
}
function renderSeasons() {
const expandedSeasons = new Set(
[...seasonList.querySelectorAll(".season[open]")].map((season) => season.dataset.season),
);
const visibleRecords = filteredRecords();
const grouped = new Map();
for (const record of visibleRecords) {
if (!grouped.has(record.season)) grouped.set(record.season, []);
grouped.get(record.season).push(record);
}
const seasons = [...grouped.keys()].sort((left, right) => seasonStart(right) - seasonStart(left));
seasonList.replaceChildren();
if (seasons.length === 0) {
seasonList.append(createElement("p", "award-filter-empty", "当前筛选条件下没有获奖记录。"));
seasonsRendered = records.length > 0;
return;
}
seasons.forEach((season, index) => {
const seasonElement = renderSeason(season, grouped.get(season), index);
seasonElement.dataset.season = season;
seasonElement.open = seasonsRendered ? expandedSeasons.has(season) : index === 0;
seasonList.append(seasonElement);
});
seasonsRendered = true;
}
function showPerson(name) {
const honors = filteredRecords()
.filter((record) => record.members.includes(name))
.sort((left, right) => seasonStart(right.season) - seasonStart(left.season));
personName.textContent = name;
const counts = countMedals(honors);
const summaryItems = STATISTIC_ORDER.map((award) => medalCountElement(award, counts[award]));
if (personHasWfQualification(honors)) summaryItems.unshift(wfBadge("wf-person-badge"));
personSummary.replaceChildren(...summaryItems);
personRecordsBody.replaceChildren();
for (const honor of honors) {
const row = document.createElement("tr");
row.append(
createElement("td", "", seasonLabel(honor.season)),
createElement("td", "", honor.team),
createElement("td", "", honor.contest),
);
const result = document.createElement("td");
result.append(resultElement(honor));
row.append(result);
personRecordsBody.append(row);
}
personDialog.showModal();
}
function showContest(contest) {
const honors = filteredRecords()
.filter((record) => record.contest === contest)
.sort(
(left, right) =>
seasonStart(right.season) - seasonStart(left.season) ||
collator.compare(left.team, right.team),
);
contestName.textContent = contest;
contestRecordsBody.replaceChildren();
for (const honor of honors) {
const row = document.createElement("tr");
row.append(
createElement("td", "", seasonLabel(honor.season)),
createElement("td", "", honor.team),
);
const award = createElement("td");
award.append(resultElement(honor));
row.append(award);
contestRecordsBody.append(row);
}
contestDialog.showModal();
}
document.addEventListener("click", (event) => {
const contest = event.target.closest("[data-contest]");
if (contest) {
showContest(contest.dataset.contest);
return;
}
const person = event.target.closest("[data-person]");
if (person) showPerson(person.dataset.person);
});
function syncAwardFilterButtons() {
for (const button of awardFilterButtons) {
const enabled = awardFilters[button.dataset.filterGroup].has(button.dataset.filterValue);
button.setAttribute("aria-checked", String(enabled));
}
}
function renderFilteredAwardViews() {
renderSeasons();
renderPlayers();
}
for (const button of awardFilterButtons) {
button.addEventListener("click", () => {
const group = button.dataset.filterGroup;
const value = button.dataset.filterValue;
const enabled = !awardFilters[group].has(value);
if (enabled) awardFilters[group].add(value);
else awardFilters[group].delete(value);
syncAwardFilterButtons();
renderFilteredAwardViews();
});
}
playerTimeDecayInput.addEventListener("input", () => {
playerTimeDecay = Number.parseFloat(playerTimeDecayInput.value);
playerTimeDecayValue.value = playerTimeDecay.toFixed(2);
renderPlayers();
});
menuToggle.addEventListener("click", () => setMenuOpen(!siteSidebar.classList.contains("is-open")));
menuClose.addEventListener("click", () => setMenuOpen(false));
sidebarBackdrop.addEventListener("click", () => setMenuOpen(false));
for (const folderToggle of sidebarFolderToggles) {
folderToggle.addEventListener("click", () => {
const expanded = folderToggle.getAttribute("aria-expanded") === "true";
const tree = document.querySelector(`#${folderToggle.dataset.treeTarget}`);
folderToggle.setAttribute("aria-expanded", String(!expanded));
tree.hidden = expanded;
});
}
calendarPrevious.addEventListener("click", () => {
displayedCalendarMonth = new Date(
displayedCalendarMonth.getFullYear(),
displayedCalendarMonth.getMonth() - 1,
1,
);
renderCalendar();
});
calendarNext.addEventListener("click", () => {
displayedCalendarMonth = new Date(
displayedCalendarMonth.getFullYear(),
displayedCalendarMonth.getMonth() + 1,
1,
);
renderCalendar();
});
document.addEventListener("keydown", (event) => {
if (event.key === "Escape" && siteSidebar.classList.contains("is-open")) {
setMenuOpen(false);
}
});
window.addEventListener("hashchange", () => {
renderPage();
setMenuOpen(false);
});
for (const recordDialog of [personDialog, contestDialog]) {
const shell = recordDialog.querySelector(".dialog-shell");
const close = recordDialog.querySelector(".dialog-close");
close.addEventListener("click", () => recordDialog.close());
recordDialog.addEventListener("click", (event) => {
if (event.target === recordDialog) recordDialog.close();
});
shell.addEventListener("click", (event) => event.stopPropagation());
}
function fetchJson(path) {
return fetch(path).then((response) => {
if (!response.ok) throw new Error(`无法读取数据(${response.status})`);
return response.json();
});
}
Promise.all([
fetchJson("data/awards.json"),
fetchJson("data/wf.json"),
fetchJson("data/first_blood.json"),
fetchJson("data/boards.json"),
fetchJson("data/documents.json"),
fetchJson("data/calendar.json"),
])
.then(([awardData, wfData, firstBloodData, boardsData, documentsData, calendarData]) => {
records = validateRecords(awardData);
latestAwardSeasonStart = records.reduce(
(latest, record) => Math.max(latest, seasonStart(record.season)),
0,
);
wfQualifications = validateWfQualifications(wfData);
firstBloodIndex = indexFirstBlood(validateFirstBlood(firstBloodData));
boardTreeData = validateBoards(boardsData);
documentTreeData = validateDocuments(documentsData);
calendarEvents = validateCalendar(calendarData);
renderArchiveMenus();
renderFilteredAwardViews();
renderPage();
loadingStatus.hidden = true;
playerLoadingStatus.hidden = true;
})
.catch((error) => {
loadingStatus.textContent = `${error.message}。请稍后重试。`;
playerLoadingStatus.textContent = `${error.message}。请稍后重试。`;
console.error(error);
});