]> git.sesse.net Git - ultimatescore/blob - carousel.js
Switch to a different spreadsheet.
[ultimatescore] / carousel.js
1 'use strict';
2
3 function addheading(carousel, colspan, content)
4 {
5         let thead = document.createElement("thead");
6         let tr = document.createElement("tr");
7         let th = document.createElement("th");
8         th.innerHTML = content;
9         th.setAttribute("colspan", colspan);
10         tr.appendChild(th);
11         thead.appendChild(tr);
12         carousel.appendChild(thead);
13 };
14 function addtd(tr, className, content) {
15         let td = document.createElement("td");
16         td.appendChild(document.createTextNode(content));
17         td.className = className;
18         tr.appendChild(td);
19 };
20 function addth(tr, className, content) {
21         let th = document.createElement("th");
22         th.appendChild(document.createTextNode(content));
23         th.className = className;
24         tr.appendChild(th);
25 };
26
27 function subrank_partitions(games, parts, start_rank, tiebreakers) {
28         let result = [];
29         for (let i = 0; i < parts.length; ++i) {
30                 let part = rank(games, parts[i], start_rank, tiebreakers);
31                 for (let j = 0; j < part.length; ++j) {
32                         result.push(part[j]);
33                 }
34                 start_rank += part.length;
35         }
36         return result;
37 };
38
39 function partition(teams, compare)
40 {
41         teams.sort(compare);
42
43         let parts = [];
44         let curr_part = [teams[0]];
45         for (let i = 1; i < teams.length; ++i) {
46                 if (compare(teams[i], curr_part[0]) != 0) {
47                         parts.push(curr_part);
48                         curr_part = [];
49                 }
50                 curr_part.push(teams[i]);
51         }
52         if (curr_part.length != 0) {
53                 parts.push(curr_part);
54         }
55         return parts;
56 };
57
58 function explain_tiebreaker(parts, rule_name)
59 {
60         let result = [];
61         for (let i = 0; i < parts.length; ++i) {
62                 result.push(parts[i].map(function(x) { return x.shortname; }).join("/"));
63         }
64         return result.join(" > ") + " (" + rule_name + ")";
65 }
66
67 function make_teams_to_idx(teams)
68 {
69         let teams_to_idx = [];
70         for (let i = 0; i < teams.length; i++) {
71                 teams_to_idx[teams[i].name] = i;
72         }
73         return teams_to_idx;
74 }
75
76 function partition_by_beat(games, teams)
77 {
78         // Head-to-head score by way of components. First construct the beat matrix.
79         let n = teams.length;
80         let beat = new Array(n);
81         let teams_to_idx = make_teams_to_idx(teams);
82         for (let i = 0; i < n; i++) {
83                 beat[i] = new Array(n);
84                 for (let j = 0; j < n; j++) {
85                         beat[i][j] = 0;
86                 }
87         }
88         for (let i = 0; i < games.length; ++i) {
89                 let idx1 = teams_to_idx[games[i].name1];
90                 let idx2 = teams_to_idx[games[i].name2];
91                 if (idx1 !== undefined && idx2 !== undefined) {
92                         if (games[i].score1 > games[i].score2) {
93                                 beat[idx1][idx2] = 1;
94                         }
95                         if (games[i].score1 < games[i].score2) {
96                                 beat[idx2][idx1] = 1;
97                         }
98                 }
99         }
100         // Floyd-Warshall for transitive closure.
101         for (let k = 0; k < n; ++k) {
102                 for (let i = 0; i < n; ++i) {
103                         for (let j = 0; j < n; ++j) {
104                                 if (beat[i][k] && beat[k][j]) {
105                                         beat[i][j] = 1;
106                                 }
107                         }
108                 }
109         }
110
111         // See if we can find any team that is comparable to all others.
112         for (let pivot_idx = 0; pivot_idx < n; pivot_idx++) {
113                 let incomparable = false;
114                 for (let i = 0; i < n; ++i) {
115                         if (i != pivot_idx && beat[pivot_idx][i] == 0 && beat[i][pivot_idx] == 0) {
116                                 incomparable = true;
117                                 break;
118                         }
119                 }
120                 if (!incomparable) {
121                         // Split the teams into three partitions:
122                         let better_than_pivot = [], equal = [], worse_than_pivot = [];
123                         for (let i = 0; i < n; ++i) {
124                                 let we_beat = (beat[pivot_idx][i] == 1);
125                                 let they_beat = (beat[i][pivot_idx] == 1);
126                                 if ((i == pivot_idx) || (we_beat && they_beat)) {
127                                         equal.push(teams[i]);
128                                 } else if (we_beat && !they_beat) {
129                                         worse_than_pivot.push(teams[i]);
130                                 } else if (they_beat && !we_beat) {
131                                         better_than_pivot.push(teams[i]);
132                                 } else {
133                                         console.log("this shouldn't happen");
134                                 }
135                         } 
136                         let result = [];
137                         if (better_than_pivot.length > 0) {
138                                 result = partition_by_beat(games, better_than_pivot);
139                         }
140                         result.push(equal);  // Obviously can't be partitioned further.
141                         if (worse_than_pivot.length > 0) {
142                                 result = result.concat(partition_by_beat(games, worse_than_pivot));
143                         }
144                         return result;
145                 }
146         }
147
148         // No usable pivot was found, so the graph is inherently
149         // disconnected, and we cannot partition it.
150         return [teams];
151 }
152
153 // Takes in an array, gives every element a rank starting with 1, and returns.
154 function rank(games, teams, start_rank, tiebreakers) {
155         if (teams.length <= 1) {
156                 // Only one team, so trivial.
157                 teams[0].rank = start_rank;
158                 return teams;
159         }
160
161         // Rule #0: Partition the teams by score.
162         let score_parts = partition(teams, function(a, b) { return b.pts - a.pts });
163         if (score_parts.length > 1) {
164                 return subrank_partitions(games, score_parts, start_rank, tiebreakers);
165         }
166
167         // Rule #1: Head-to-head wins.
168         let beat_parts = partition_by_beat(games, teams);
169         if (beat_parts.length > 1) {
170                 tiebreakers.push(explain_tiebreaker(beat_parts, 'head-to-head'));
171                 return subrank_partitions(games, beat_parts, start_rank, tiebreakers);
172         }
173
174         // Rule #2: Number of games played (fewer is better).
175         // Actually the rule says “fewest losses”, but fewer games is equivalent
176         // as long as teams have the same amount of points and ties don't exist.
177         let nplayed_parts = partition(teams, function(a, b) { return a.nplayed - b.nplayed });
178         if (nplayed_parts.length > 1) {
179                 tiebreakers.push(explain_tiebreaker(nplayed_parts, 'fewer losses'));
180                 return subrank_partitions(games, nplayed_parts, start_rank, tiebreakers);
181         }
182
183         // Rule #3: Head-to-head goal difference. 
184         let teams_to_idx = make_teams_to_idx(teams);
185         for (let i = 0; i < teams.length; i++) {
186                 teams[i].h2h_gd = 0;
187                 teams[i].h2h_goals = 0;
188         }
189         for (let i = 0; i < games.length; ++i) {
190                 let idx1 = teams_to_idx[games[i].name1];
191                 let idx2 = teams_to_idx[games[i].name2];
192                 if (idx1 !== undefined && idx2 !== undefined &&
193                     !isNaN(games[i].score1) && isNaN(games[i].score2)) {
194                         teams[idx1].h2h_gd += games[i].score1;
195                         teams[idx1].h2h_gd -= games[i].score2;
196                         teams[idx2].h2h_gd += games[i].score2;
197                         teams[idx2].h2h_gd -= games[i].score1;
198
199                         teams[idx1].h2h_goals += games[i].score1;
200                         teams[idx2].h2h_goals += games[i].score2;
201                 }
202         }
203         let h2h_gd_parts = partition(teams, function(a, b) { return b.h2h_gd - a.h2h_gd });
204         if (h2h_gd_parts.length > 1) {
205                 tiebreakers.push(explain_tiebreaker(h2h_gd_parts, 'head-to-head goal difference'));
206                 return subrank_partitions(games, h2h_gd_parts, start_rank, tiebreakers);
207         }
208
209         // Rule #4: Global goal difference. (Well, not strictly, but good enough.)
210         let gd_parts = partition(teams, function(a, b) { return b.gd - a.gd });
211         if (gd_parts.length > 1) {
212                 tiebreakers.push(explain_tiebreaker(gd_parts, 'overall goal difference'));
213                 return subrank_partitions(games, gd_parts, start_rank, tiebreakers);
214         }
215
216         // Rule #5: Head-to-head scored goals.
217         let h2h_goals_parts = partition(teams, function(a, b) { return b.h2h_goals - a.h2h_goals });
218         if (h2h_goals_parts.length > 1) {
219                 tiebreakers.push(explain_tiebreaker(h2h_goals_parts, 'head-to-head scored goals'));
220                 return subrank_partitions(games, h2h_goals_parts, start_rank, tiebreakers);
221         }
222
223         // Rule #6: Overall scored goals. (Same caveat as #4.)
224         let goals_parts = partition(teams, function(a, b) { return b.goals - a.goals });
225         if (goals_parts.length > 1) {
226                 tiebreakers.push(explain_tiebreaker(goals_parts, 'scored goals'));
227                 return subrank_partitions(games, goals_parts, start_rank, tiebreakers);
228         }
229
230         // OK, it's a tie. Give them all the same rank.
231         let result = [];
232         for (let i = 0; i < teams.length; ++i) {
233                 result.push(teams[i]);
234                 result[i].rank = start_rank;
235         }
236         return result; 
237 }; 
238
239 function parse_teams_from_spreadsheet(response) {
240         let teams = [];
241         for (let i = 2; response.values[i].length >= 1; ++i) {
242                 teams.push({
243                         "name": response.values[i][0],
244                         "mediumname": response.values[i][1],
245                         "shortname": response.values[i][2],
246                         "tags": response.values[i][3],
247                         "nplayed": 0,
248                         "gd": 0,
249                         "pts": 0,
250                         "goals": 0
251                 });
252         }
253         return teams;
254 };
255
256 function parse_games_from_spreadsheet(response, group_name, include_unplayed) {
257         let games = [];
258         let i;
259         for (i = 0; i < response.values.length; ++i) {
260                 if (response.values[i][0] === 'Results') {
261                         i += 2;
262                         break;
263                 }
264         }
265
266         for ( ; response.values[i] !== undefined && response.values[i].length >= 1; ++i) {
267                 if ((response.values[i][2] && response.values[i][3]) || include_unplayed) {
268                         let real_group_name = response.values[i][9];
269                         if (real_group_name === undefined) {
270                                 real_group_name = group_name;
271                         }
272                         games.push({
273                                 "name1": response.values[i][0],
274                                 "name2": response.values[i][1],
275                                 "score1": parseInt(response.values[i][2]),
276                                 "score2": parseInt(response.values[i][3]),
277                                 "streamday": response.values[i][7],
278                                 "streamtime": response.values[i][8],
279                                 "group_name": real_group_name
280                         });
281                 }
282         }
283         return games;
284 };
285
286 function display_group(response, group_name)
287 {
288         let teams = parse_teams_from_spreadsheet(response);
289         let games = parse_games_from_spreadsheet(response, group_name, false);
290         display_group_parsed(teams, games, group_name);
291 };
292
293 function display_group_parsed(teams, games, group_name)
294 {
295         document.getElementById('entire-bug').style.display = 'none';
296
297         let teams_to_idx = make_teams_to_idx(teams);
298         for (let i = 0; i < games.length; ++i) {
299                 let idx1 = teams_to_idx[games[i].name1];
300                 let idx2 = teams_to_idx[games[i].name2];
301                 if (games[i].score1 === undefined || games[i].score2 === undefined ||
302                     isNaN(games[i].score1) || isNaN(games[i].score2) ||
303                     idx1 === undefined || idx2 === undefined ||
304                     games[i].score1 == games[i].score2) {
305                         continue;
306                 }
307                 ++teams[idx1].nplayed;
308                 ++teams[idx2].nplayed;
309                 teams[idx1].goals += games[i].score1;
310                 teams[idx2].goals += games[i].score2;
311                 teams[idx1].gd += games[i].score1;
312                 teams[idx2].gd += games[i].score2;
313                 teams[idx1].gd -= games[i].score2;
314                 teams[idx2].gd -= games[i].score1;
315                 if (games[i].score1 > games[i].score2) {
316                         teams[idx1].pts += 2;
317                 } else {
318                         teams[idx2].pts += 2;
319                 }
320         }
321
322         let tiebreakers = [];
323         teams = rank(games, teams, 1, tiebreakers);
324
325         let carousel = document.getElementById('carousel');
326         clear_carousel(carousel);
327
328         addheading(carousel, 5, "Current standings, Trøndisk 2017<br />" + group_name);
329         let tr = document.createElement("tr");
330         tr.className = "subfooter";
331         addth(tr, "rank", "");
332         addth(tr, "team", "");
333         addth(tr, "nplayed", "P");
334         addth(tr, "gd", "GD");
335         addth(tr, "pts", "Pts");
336         carousel.appendChild(tr);
337
338         let row_num = 2;
339         for (let i = 0; i < teams.length; ++i) {
340                 let tr = document.createElement("tr");
341
342                 addth(tr, "rank", teams[i].rank);
343                 addtd(tr, "team", teams[i].name);
344                 addtd(tr, "nplayed", teams[i].nplayed);
345                 addtd(tr, "gd", teams[i].gd.toString().replace(/-/, '−'));
346                 addtd(tr, "pts", teams[i].pts);
347
348                 carousel.appendChild(tr);
349         }
350
351         if (tiebreakers.length > 0) {
352                 let tie_tr = document.createElement("tr");
353                 tie_tr.className = "footer";
354                 let td = document.createElement("td");
355                 td.appendChild(document.createTextNode("Tiebreaks applied: " + tiebreakers.join(', ')));
356                 td.setAttribute("colspan", "5");
357                 tie_tr.appendChild(td);
358                 carousel.appendChild(tie_tr);
359         }
360
361         let footer_tr = document.createElement("tr");
362         footer_tr.className = "footer";
363         let td = document.createElement("td");
364         td.appendChild(document.createTextNode("www.trondheimfrisbeeklubb.no | #trøndisk"));
365         td.setAttribute("colspan", "5");
366         footer_tr.appendChild(td);
367         carousel.appendChild(footer_tr);
368
369         fade_in_rows(carousel);
370
371         carousel.style.display = 'table';
372 };
373
374 function fade_in_rows(table)
375 {
376         let trs = table.getElementsByTagName("tr");
377         for (let i = 1; i < trs.length; ++i) {  // The header already has its own fade-in.
378                 if (trs[i].className === "footer") {
379                         trs[i].style = "-webkit-animation: fade-in 1.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
380                 } else {
381                         trs[i].style = "-webkit-animation: fade-in 2.0s ease; -webkit-animation-delay: " + (0.25 * i) + "s; -webkit-animation-fill-mode: both;";
382                 }
383         }
384 };
385
386 function fade_out_rows(table)
387 {
388         let trs = table.getElementsByTagName("tr");
389         for (let i = 0; i < trs.length; ++i) {
390                 if (trs[i].className === "footer") {
391                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
392                 } else {
393                         trs[i].style = "-webkit-animation: fade-out 1.0s ease; -webkit-animation-delay: " + (0.125 * i) + "s; -webkit-animation-fill-mode: both;";
394                 }
395         }
396 };
397
398 function clear_carousel(table)
399 {
400         while (table.childNodes.length > 0) {
401                 table.removeChild(table.firstChild);
402         }
403 };
404
405 // Stream schedule
406 let max_list_len = 8;
407
408 function display_stream_schedule(response, group_name) {
409         let teams = parse_teams_from_spreadsheet(response);
410         let games = parse_games_from_spreadsheet(response, group_name, true);
411         display_stream_schedule_parsed(teams, games, 0);
412 };
413
414 function sort_game_list(games) {
415         games = games.filter(function(game) { return game.streamtime !== undefined && game.streamtime.match(/[0-9]+:[0-9]+/) != null; });
416         games.sort(function(a, b) {
417                 if (a.streamday !== b.streamday) {
418                         return a.streamday - b.streamday;
419                 }
420
421                 let m1 = a.streamtime.match(/([0-9]+):([0-9]+)/);
422                 let m2 = b.streamtime.match(/([0-9]+):([0-9]+)/);
423                 return (m1[1] * 60 + m1[2]) - (m2[1] * 60 + m2[2]);
424         });
425         return games;
426 }
427
428 function find_game_start_idx(games) {
429         // Pick out a reasonable place to start the list. We'll show the last
430         // completed match and start from there.
431         let start_idx = games.length - 1;
432         for (let i = 0; i < games.length; ++i) {
433                 if (isNaN(games[i].score1) || isNaN(games[i].score2) &&
434                     games[i].score1 === games[i].score2) {
435                         start_idx = i;
436                         break;
437                 }
438         }
439         if (start_idx > 0) start_idx--;
440         if (games.length >= max_list_len) {
441                 start_idx = Math.min(start_idx, games.length - max_list_len);
442         }
443         return start_idx;
444 }
445
446 function find_num_pages(games) {
447         games = sort_game_list(games);
448         let start_idx = find_game_start_idx(games);
449         return Math.ceil((games.length - start_idx) / max_list_len);
450 }
451
452 function display_stream_schedule_parsed(teams, games, page) {
453         document.getElementById('entire-bug').style.display = 'none';
454
455         games = sort_game_list(games);
456         let start_idx = find_game_start_idx(games);
457
458         start_idx += page * max_list_len;
459         if (start_idx >= games.length) {
460                 // Error.
461                 return;
462         }
463
464         let days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
465         let shortdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
466         let today = days[(new Date).getDay()];
467
468         let covered_days = [];
469         let row_num = 0;
470         for (let i = start_idx; i < games.length && row_num++ < max_list_len; ++i) {
471                 if (i == start_idx || games[i].streamday != games[i - 1].streamday) {
472                         covered_days.push(days[games[i].streamday]);
473                 }
474         }
475         
476         let carousel = document.getElementById('carousel');
477         clear_carousel(carousel);
478         addheading(carousel, 3, "Stream schedule, Trøndisk 2017<br />" + covered_days.join('/') + " (all times CET)");
479
480         let teams_to_idx = make_teams_to_idx(teams);
481         row_num = 0;
482         for (let i = start_idx; i < games.length && row_num < max_list_len; ++i) {
483                 let tr = document.createElement("tr");
484
485                 let name1 = teams[teams_to_idx[games[i].name1]].mediumname;
486                 let name2 = teams[teams_to_idx[games[i].name2]].mediumname;
487
488                 addtd(tr, "matchup", name1 + "–" + name2);
489                 addtd(tr, "group", games[i].group_name);
490
491                 if (!isNaN(games[i].score1) && !isNaN(games[i].score2) &&
492                     games[i].score1 !== games[i].score2) {
493                         addtd(tr, "streamtime", games[i].score1 + "–" + games[i].score2);
494                 } else {
495                         let streamtime = games[i].streamtime;
496                         let streamday = days[games[i].streamday];
497                         if (streamday !== today) {
498                                 streamtime = shortdays[games[i].streamday] + " " + streamtime;
499                         }
500                         addth(tr, "streamtime", streamtime);
501                 }
502
503                 row_num++;
504                 carousel.appendChild(tr);
505         }
506
507         fade_in_rows(carousel);
508
509         carousel.style.display = 'table';
510 };
511
512 function get_group(group_name, cb)
513 {
514         let req = new XMLHttpRequest();
515         req.onload = function(e) {
516                 cb(JSON.parse(req.responseText), group_name);
517         };
518         req.open('GET', 'https://sheets.googleapis.com/v4/spreadsheets/122tIwrXTi5ug0Vv6Np5w3pVwEWE2KkjWxtzQQfGtOZA/values/\'' + group_name + '\'!A1:J50?key=AIzaSyAuP9yQn8g0bSay6r_RpGtpFeIbwprH1TU');
519         req.send();
520 };
521
522 function showgroup(group_name)
523 {
524         get_group(group_name, display_group);
525 };
526
527 function showgroup_from_state()
528 {
529         showgroup(state['group_name']);
530 };
531
532 let carousel_timeout = null;
533
534 function hidetable()
535 {
536         fade_out_rows(document.getElementById('carousel'));
537 };
538
539 function showschedule(page)
540 {
541         let teams = [];
542         let games = [];
543         let num_left = 3;
544
545         let cb = function(response, group_name) {
546                 teams = teams.concat(parse_teams_from_spreadsheet(response));
547                 games = games.concat(parse_games_from_spreadsheet(response, group_name, true));
548                 if (--num_left == 0) {
549                         display_stream_schedule_parsed(teams, games, 0);
550                 }
551         };
552
553         get_group('Group A', cb);
554         get_group('Group B', cb);
555         get_group('Playoffs', cb);
556 };
557
558 function do_series(series)
559 {
560         do_series_internal(series, 0);
561 };
562
563 function do_series_internal(series, idx)
564 {
565         (series[idx][1])();
566         if (idx + 1 < series.length) {
567                 carousel_timeout = setTimeout(function() { do_series_internal(series, idx + 1); }, series[idx][0]);
568         }
569 };
570
571 function showcarousel()
572 {
573         let teams_per_group = [];
574         let games_per_group = [];
575         let combined_teams = [];
576         let combined_games = [];
577         let num_left = 3;
578
579         let cb = function(response, group_name) {
580                 let teams = parse_teams_from_spreadsheet(response);
581                 let games = parse_games_from_spreadsheet(response, group_name, true);
582                 teams_per_group[group_name] = teams;
583                 games_per_group[group_name] = games;
584
585                 combined_teams = combined_teams.concat(teams);
586                 combined_games = combined_games.concat(games);
587                 if (--num_left == 0) {
588                         let series = [
589                                 [ 13000, function() { display_group_parsed(teams_per_group['Group A'], games_per_group['Group A'], 'Group A'); } ],
590                                 [ 2000, function() { hidetable(); } ],
591                                 [ 13000, function() { display_group_parsed(teams_per_group['Group B'], games_per_group['Group B'], 'Group B'); } ],
592                                 [ 2000, function() { hidetable(); } ]
593                         ];
594                         let num_pages = find_num_pages(combined_games);
595                         for (let page = 0; page < num_pages; ++page) {
596                                 series.push([ 13000, function() { display_stream_schedule_parsed(combined_teams, combined_games, page); } ]);
597                                 series.push([ 2000, function() { hidetable(); } ]);
598                         }
599
600                         do_series(series);
601                 }
602         };
603
604         get_group('Group A', cb);
605         get_group('Group B', cb);
606         get_group('Playoffs', cb);
607 };
608
609 function stopcarousel()
610 {
611         if (carousel_timeout !== null) {
612                 hidetable();
613                 clearTimeout(carousel_timeout);
614                 carousel_timeout = null;
615         }
616 };
617
618 function hidescorebug()
619 {
620         document.getElementById('entire-bug').style.display = 'none';
621 }
622
623 function showscorebug()
624 {
625         document.getElementById('entire-bug').style.display = null;
626 };
627