3 // No frameworks, no compilers, no npm, just JavaScript. :-)
6 let global_filters = {};
7 let next_filterset_id = 2; // Arbitrary IDs are fine as long as they never collide.
9 addEventListener('hashchange', () => { process_matches(global_json, global_filters); });
10 addEventListener('click', possibly_close_menu);
11 fetch('ultimate.json')
12 .then(response => response.json())
13 .then(response => { global_json = response; process_matches(global_json, global_filters); });
15 function format_time(t)
17 const ms = t % 1000 + '';
18 t = Math.floor(t / 1000);
19 const sec = t % 60 + '';
20 t = Math.floor(t / 60);
21 const min = t % 60 + '';
22 const hour = Math.floor(t / 60) + '';
23 return hour + ':' + min.padStart(2, '0') + ':' + sec.padStart(2, '0') + '.' + ms.padStart(3, '0');
26 function attribute_player_time(player, to, from, offense) {
28 if (player.on_field_since > from) {
29 // Player came in while play happened (without a stoppage!?).
30 delta_time = to - player.on_field_since;
32 delta_time = to - from;
34 player.playing_time_ms += delta_time;
35 if (offense === true) {
36 player.offensive_playing_time_ms += delta_time;
37 } else if (offense === false) {
38 player.defensive_playing_time_ms += delta_time;
42 function take_off_field(player, t, live_since, offense, keep) {
44 if (live_since === null) {
45 // Play isn't live, so nothing to do.
47 attribute_player_time(player, t, live_since, offense);
49 if (player.on_field_since !== null) { // Just a safeguard; out without in should never happen.
50 player.field_time_ms += t - player.on_field_since;
53 player.on_field_since = null;
56 function add_cell(tr, element_type, text) {
57 let element = document.createElement(element_type);
58 element.textContent = text;
59 tr.appendChild(element);
63 function add_th(tr, text, colspan) {
64 let element = document.createElement('th');
65 let link = document.createElement('a');
66 link.style.cursor = 'pointer';
67 link.addEventListener('click', (e) => {
69 process_matches(global_json, global_filters);
71 link.textContent = text;
72 element.appendChild(link);
73 tr.appendChild(element);
76 element.setAttribute('colspan', colspan);
78 element.setAttribute('colspan', '3');
83 function add_3cell(tr, text, cls) {
84 let p1 = add_cell(tr, 'td', '');
85 let element = add_cell(tr, 'td', text);
86 let p2 = add_cell(tr, 'td', '');
88 p1.classList.add('pad');
89 p2.classList.add('pad');
90 if (cls === undefined) {
91 element.classList.add('num');
93 element.classList.add(cls);
98 function add_3cell_with_filler_ci(tr, text, cls) {
99 let element = add_3cell(tr, text, cls);
101 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
102 svg.classList.add('fillerci');
103 svg.setAttribute('width', ci_width);
104 svg.setAttribute('height', ci_height);
105 element.appendChild(svg);
110 function add_3cell_ci(tr, ci) {
112 add_3cell_with_filler_ci(tr, 'N/A');
117 if (ci.format === 'percentage') {
118 text = (100 * ci.val).toFixed(0) + '%';
119 } else if (ci.decimals !== undefined) {
120 text = ci.val.toFixed(ci.decimals);
122 text = ci.val.toFixed(2);
124 if (ci.unit !== undefined) {
125 text += ' '+ ci.unit;
127 let element = add_3cell(tr, text);
128 let to_x = (val) => { return ci_width * (val - ci.min) / (ci.max - ci.min); };
131 let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
132 if (ci.inverted === true) {
133 svg.classList.add('invertedci');
135 svg.classList.add('ci');
137 svg.setAttribute('width', ci_width);
138 svg.setAttribute('height', ci_height);
140 // The good (green) and red (bad) ranges.
141 let s0 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
142 s0.classList.add('range');
143 s0.classList.add('s0');
144 s0.setAttribute('width', to_x(ci.desired));
145 s0.setAttribute('height', ci_height);
146 s0.setAttribute('x', '0');
148 let s1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
149 s1.classList.add('range');
150 s1.classList.add('s1');
151 s1.setAttribute('width', ci_width - to_x(ci.desired));
152 s1.setAttribute('height', ci_height);
153 s1.setAttribute('x', to_x(ci.desired));
156 let bar = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
157 bar.classList.add('bar');
158 bar.setAttribute('width', to_x(ci.upper_ci) - to_x(ci.lower_ci));
159 bar.setAttribute('height', ci_height / 3);
160 bar.setAttribute('x', to_x(ci.lower_ci));
161 bar.setAttribute('y', ci_height / 3);
163 // Marker line for average.
164 let marker = document.createElementNS('http://www.w3.org/2000/svg', 'line');
165 marker.classList.add('marker');
166 marker.setAttribute('x1', to_x(ci.val));
167 marker.setAttribute('x2', to_x(ci.val));
168 marker.setAttribute('y1', ci_height / 6);
169 marker.setAttribute('y2', ci_height * 5 / 6);
173 svg.appendChild(bar);
174 svg.appendChild(marker);
176 element.appendChild(svg);
179 function calc_stats(json, filters) {
181 for (const player of json['players']) {
182 players[player['player_id']] = {
183 'name': player['name'],
184 'gender': player['gender'],
185 'number': player['number'],
201 'playing_time_ms': 0,
202 'offensive_playing_time_ms': 0,
203 'defensive_playing_time_ms': 0,
207 'offensive_points_completed': 0,
208 'offensive_points_won': 0,
209 'defensive_points_completed': 0,
210 'defensive_points_won': 0,
212 'offensive_soft_plus': 0,
213 'offensive_soft_minus': 0,
214 'defensive_soft_plus': 0,
215 'defensive_soft_minus': 0,
222 'last_point_seen': null,
223 'on_field_since': null,
228 players['globals'] = {
230 'playing_time_ms': 0,
231 'offensive_playing_time_ms': 0,
232 'defensive_playing_time_ms': 0,
235 'offensive_points_completed': 0,
236 'offensive_points_won': 0,
239 'defensive_points_completed': 0,
240 'defensive_points_won': 0,
245 'their_clean_holds': 0,
246 'their_clean_breaks': 0,
248 'touches_for_turnover': 0,
249 'touches_for_goal': 0,
250 'time_for_turnover': [],
252 'their_time_for_turnover': [],
253 'their_time_for_goal': [],
255 let globals = players['globals'];
257 for (const match of json['matches']) {
258 if (!keep_match(match['match_id'], filters)) {
264 let between_points = true;
266 let handler_got_by_interception = false; // Only relevant if handler !== null.
267 let prev_handler = null;
268 let live_since = null;
269 let offense = null; // True/false/null (unknown).
271 let pull_started = null;
272 let last_pull_was_ours = null; // Effectively whether we're playing an O or D point (not affected by turnovers).
274 let game_started = null;
275 let last_goal = null;
276 let current_predominant_gender = null;
277 let current_num_players_on_field = null;
279 let we_lost_disc = false;
280 let they_lost_disc = false;
281 let touches_this_possession = 0;
282 let possession_started = null;
283 let extra_ms_this_possession = 0; // Used at stoppages.
285 // The last used formations of the given kind, if any; they may be reused
286 // when the point starts, if nothing else is set.
287 let last_offensive_formation = null;
288 let last_defensive_formation = null;
290 // Formations we've set, but haven't really had the chance to use yet
291 // (e.g., we get a “use zone defense” event while we're still on offense).
292 let pending_offensive_formation = null;
293 let pending_defensive_formation = null;
295 // Formations that we have played at least once this point, after all
296 // heuristics and similar.
297 let formations_used_this_point = new Set();
299 for (const [q,p] of Object.entries(players)) {
300 p.on_field_since = null;
301 p.last_point_seen = null;
303 for (const e of match['events']) {
305 let type = e['type'];
306 let p = players[e['player']];
309 let keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
310 if (type === 'in' && p.on_field_since === null) {
311 p.on_field_since = t;
312 if (!keep && keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
313 // A player needed for the filters went onto the field,
314 // so pretend people walked on right now (to start their
316 for (const [q,p2] of Object.entries(players)) {
317 if (p2.on_field_since !== null) {
318 p2.on_field_since = t;
322 } else if (type === 'out') {
323 take_off_field(p, t, live_since, offense, keep);
324 if (keep && !keep_event(players, formations_used_this_point, last_pull_was_ours, filters)) {
325 // A player needed for the filters went off the field,
326 // so we need to attribute time for all the others.
327 // Pretend they walked off and then immediately on again.
329 // TODO: We also need to take care of this to get the globals right.
330 for (const [q,p2] of Object.entries(players)) {
331 if (p2.on_field_since !== null) {
332 take_off_field(p2, t, live_since, offense, keep);
333 p2.on_field_since = t;
339 keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters); // Recompute after in/out.
341 if (match['gender_rule_a']) {
342 if (type === 'restart' && !between_points) {
343 let predominant_gender = find_predominant_gender(players);
344 let num_players_on_field = find_num_players_on_field(players);
345 if (predominant_gender !== current_predominant_gender && current_predominant_gender !== null) {
346 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed predominant gender from ' + current_predominant_gender + ' to ' + predominant_gender);
348 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
349 console.log(match['description'] + ' ' + format_time(t) + ': Stoppage changed number of players on field from ' + current_num_players_on_field + ' to ' + num_players_on_field);
351 current_predominant_gender = predominant_gender;
352 current_num_players_on_field = num_players_on_field;
353 } else if (type === 'pull' || type === 'their_pull') {
354 let predominant_gender = find_predominant_gender(players);
355 let num_players_on_field = find_num_players_on_field(players);
356 let changed = (predominant_gender !== current_predominant_gender);
357 if (point_num !== 0) {
358 let should_change = (point_num % 4 == 1 || point_num % 4 == 3); // ABBA changes on 1 and 3.
359 if (changed && !should_change) {
360 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have stayed the same, changed to predominance of ' + predominant_gender);
361 } else if (!changed && should_change) {
362 console.log(match['description'] + ' ' + format_time(t) + ': Gender ratio should have changed, remained predominantly ' + predominant_gender);
364 if (num_players_on_field !== current_num_players_on_field && current_num_players_on_field !== null) {
365 console.log(match['description'] + ' ' + format_time(t) + ': Number of players on field changed from ' + current_num_players_on_field + ' to ' + num_players_on_field);
368 current_predominant_gender = predominant_gender;
369 current_num_players_on_field = num_players_on_field;
372 if (match['gender_pull_rule']) {
373 if (type === 'pull') {
374 if (current_predominant_gender !== null &&
375 p.gender !== current_predominant_gender) {
376 console.log(match['description'] + ' ' + format_time(t) + ': ' + p.name + ' pulled, should have been ' + current_predominant_gender);
381 // Liveness management
382 if (type === 'pull' || type === 'their_pull' || type === 'restart') {
384 if (type !== 'restart') {
385 between_points = false;
387 } else if (type === 'catch' && last_pull_was_ours === null) {
388 // Someone forgot to add the pull, so we'll need to wing it.
389 console.log(match['description'] + ' ' + format_time(t) + ': Missing pull on ' + our_score + '\u2013' + their_score + '; pretending to have one.');
391 last_pull_was_ours = !offense;
392 between_points = false;
393 } else if (type === 'goal' || type === 'their_goal' || type === 'stoppage') {
394 if (type === 'goal') {
395 if (keep) ++p.touches;
396 ++touches_this_possession;
398 for (const [q,p] of Object.entries(players)) {
399 if (p.on_field_since === null) {
402 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
404 // In case the player did nothing this point,
405 // not even subbing in.
406 p.last_point_seen = point_num;
410 if (keep) attribute_player_time(p, t, live_since, offense);
412 if (type !== 'stoppage') {
414 if (last_pull_was_ours === true) { // D point.
415 ++p.defensive_points_completed;
416 if (type === 'goal') {
417 ++p.defensive_points_won;
419 } else if (last_pull_was_ours === false) { // O point.
420 ++p.offensive_points_completed;
421 if (type === 'goal') {
422 ++p.offensive_points_won;
430 if (type !== 'stoppage') {
432 ++globals.points_played;
433 if (last_pull_was_ours === true) { // D point.
434 ++globals.defensive_points_completed;
435 if (type === 'goal') {
436 ++globals.defensive_points_won;
438 } else if (last_pull_was_ours === false) { // O point.
439 ++globals.offensive_points_completed;
440 if (type === 'goal') {
441 ++globals.offensive_points_won;
445 if (live_since !== null) {
446 globals.playing_time_ms += t - live_since;
447 if (offense === true) {
448 globals.offensive_playing_time_ms += t - live_since;
449 } else if (offense === false) {
450 globals.defensive_playing_time_ms += t - live_since;
459 if (type === 'goal') {
461 } else if (type === 'their_goal') {
465 // Point count management
466 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
468 p.last_point_seen = point_num;
472 if (type === 'goal' || type === 'their_goal') {
476 if (type !== 'out' && game_started === null) {
481 if (type === 'pull') {
482 puller = e['player'];
484 keep = keep_event(players, formations_used_this_point, /*last_pull_was_ours=*/true, filters); // Will change below. This is an ugly hack.
486 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
487 // No effect on pull.
488 } else if (type === 'pull_landed' && puller !== null) {
489 if (keep) players[puller].pull_times.push(t - pull_started);
490 } else if (type === 'pull_oob' && puller !== null) {
491 if (keep) ++players[puller].oob_pulls;
493 // Not pulling (if there was one, we never recorded its outcome, but still count it).
494 puller = pull_started = null;
497 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
499 if (type === 'goal' && !we_lost_disc) {
500 if (last_pull_was_ours === false) { // O point.
501 ++globals.clean_holds;
502 } else if (last_pull_was_ours === true) {
503 ++globals.clean_breaks;
505 } else if (type === 'their_goal' && !they_lost_disc) {
506 if (last_pull_was_ours === true) { // O point for them.
507 ++globals.their_clean_holds;
508 } else if (last_pull_was_ours === false) {
509 ++globals.their_clean_breaks;
514 // Offense/defense management
515 let last_offense = offense;
516 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
519 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
520 ++globals.turnovers_lost;
521 globals.touches_for_turnover += touches_this_possession;
522 if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
523 } else if (keep && type === 'goal') {
524 globals.touches_for_goal += touches_this_possession;
525 if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
527 touches_this_possession = 0;
528 possession_started = null;
529 extra_ms_this_possession = 0;
530 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
532 they_lost_disc = true;
533 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
534 ++globals.turnovers_won;
535 if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
536 } else if (keep && type === 'their_goal') {
537 if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
539 touches_this_possession = 0;
540 possession_started = null;
541 extra_ms_this_possession = 0;
543 if (type === 'goal' || type === 'their_goal') {
544 between_points = true;
545 we_lost_disc = false;
546 they_lost_disc = false;
547 touches_this_possession = 0;
549 if (last_offense !== offense && live_since !== null) {
550 // Switched offense/defense status, so attribute this drive as needed,
551 // and update live_since to take that into account.
553 for (const [q,p] of Object.entries(players)) {
554 if (p.on_field_since === null) {
557 attribute_player_time(p, t, live_since, last_offense);
559 globals.playing_time_ms += t - live_since;
560 if (offense === true) {
561 globals.offensive_playing_time_ms += t - live_since;
562 } else if (offense === false) {
563 globals.defensive_playing_time_ms += t - live_since;
568 // The rules for possessions are slightly different; we want to start at pulls,
569 // not previous goals.
570 if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
571 type === 'pull' || type === 'their_pull') {
572 possession_started = t;
573 } else if (type === 'stoppage') {
574 if (possession_started !== null) {
575 extra_ms_this_possession = t - possession_started;
576 possession_started = null;
578 } else if (type === 'restart' && live_since !== null && !between_points) {
579 possession_started = t;
582 // O/D-point management.
583 if (type === 'pull') {
584 last_pull_was_ours = true;
585 } else if (type === 'their_pull') {
586 last_pull_was_ours = false;
587 } else if (type === 'set_offense' && last_pull_was_ours === null) {
588 // set_offense could either be “changed to offense for some reason
589 // we could not express”, or “we started in the middle of a point,
590 // and we are offense”. We assume that if we already saw the pull,
591 // it's the former, and if not, it's the latter; thus, the === null
592 // test above. (It could also be “we set offense before the pull,
593 // so that we get the right button enabled”, in which case it will
594 // be overwritten by the next pull/their_pull event anyway.)
595 last_pull_was_ours = false;
596 } else if (type === 'set_defense' && last_pull_was_ours === null) {
598 last_pull_was_ours = true;
599 } else if (type === 'goal' || type === 'their_goal') {
600 last_pull_was_ours = null;
603 // Formation management
604 if (type === 'formation_offense' || type === 'formation_defense') {
605 let id = e.formation === null ? 0 : e.formation;
606 let for_offense = (type === 'formation_offense');
607 if (offense === for_offense) {
608 formations_used_this_point.add(id);
609 } else if (for_offense) {
610 pending_offensive_formation = id;
612 pending_defensive_formation = id;
615 last_offensive_formation = id;
617 last_defensive_formation = id;
619 } else if (last_offense !== offense) {
620 if (offense === true && pending_offensive_formation !== null) {
621 formations_used_this_point.add(pending_offensive_formation);
622 pending_offensive_formation = null;
623 } else if (offense === false && pending_defensive_formation !== null) {
624 formations_used_this_point.add(pending_defensive_formation);
625 pending_defensive_formation = null;
626 } else if (offense === true && last_defensive_formation !== null) {
627 if (should_reuse_last_formation(match['events'], t)) {
628 formations_used_this_point.add(last_defensive_formation);
630 } else if (offense === false && last_offensive_formation !== null) {
631 if (should_reuse_last_formation(match['events'], t)) {
632 formations_used_this_point.add(last_offensive_formation);
637 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
638 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
640 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
641 // The handler subbed out and was replaced with another handler,
642 // so this wasn't a pass.
647 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
648 // Self-pass to goal after an interception; this is not a real pass,
649 // just how we represent a Callahan right now -- so don't
650 // count the throw, any assists or similar.
652 // It's an open question how we should handle a self-pass that is
653 // _not_ after an interception, or a self-pass that's not a goal.
654 // (It must mean we tipped off someone.) We'll count it as a regular one
655 // for the time being, although it will make hockey assists weird.
660 handler = prev_handler = null;
661 } else if (type === 'catch' || type === 'goal') {
662 if (handler !== null) {
664 ++players[handler].num_throws;
669 if (keep) ++p.touches;
670 ++touches_this_possession;
671 if (type === 'goal') {
673 if (prev_handler !== null) {
674 ++players[prev_handler].hockey_assists;
676 if (handler !== null) {
677 ++players[handler].assists;
681 handler = prev_handler = null;
683 // Update hold history.
684 prev_handler = handler;
685 handler = e['player'];
686 handler_got_by_interception = false;
688 } else if (type === 'throwaway') {
693 handler = prev_handler = null;
694 } else if (type === 'drop') {
696 handler = prev_handler = null;
697 } else if (type === 'stallout') {
698 if (keep) ++p.stallouts;
699 handler = prev_handler = null;
700 } else if (type === 'was_d') {
701 if (keep) ++p.was_ds;
702 handler = prev_handler = null;
703 } else if (type === 'defense') {
704 if (keep) ++p.defenses;
705 } else if (type === 'interception') {
710 ++touches_this_possession;
713 handler = e['player'];
714 handler_got_by_interception = true;
715 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
717 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
718 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
719 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
720 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
721 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
722 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
723 type !== 'formation_offense' && type !== 'formation_defense') {
724 console.log(format_time(t) + ": Unknown event “" + e + "”");
727 if (type === 'goal' || type === 'their_goal') {
728 formations_used_this_point.clear();
732 // Add field time for all players still left at match end.
733 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
735 for (const [q,p] of Object.entries(players)) {
736 if (p.on_field_since !== null && last_goal !== null) {
737 p.field_time_ms += last_goal - p.on_field_since;
740 if (game_started !== null && last_goal !== null) {
741 globals.field_time_ms += last_goal - game_started;
743 if (live_since !== null && last_goal !== null) {
744 globals.playing_time_ms += last_goal - live_since;
745 if (offense === true) {
746 globals.offensive_playing_time_ms += last_goal - live_since;
747 } else if (offense === false) {
748 globals.defensive_playing_time_ms += last_goal - live_since;
756 function recursively_expand_filterset(filterset, base, result)
758 if (result.length >= 100) {
761 if (base.length == filterset.length) {
765 let filter = filterset[base.length];
767 let elements = filter.elements;
768 if (elements.size === 0) {
769 elements = filter.choices;
771 for (const element of elements) {
774 'elements': new Set([ element ]),
775 'split': false, // Not used.
777 recursively_expand_filterset(filterset, [...base, split_filter], result);
780 recursively_expand_filterset(filterset, [...base, filter], result);
784 function expand_filtersets(filtersets) {
785 if (filtersets.length === 0) {
790 for (const filterset of filtersets) {
791 recursively_expand_filterset(filterset, [], expanded);
796 function process_matches(json, unexpanded_filtersets) {
797 let chosen_category = get_chosen_category();
798 write_main_menu(chosen_category);
800 let filtersets = expand_filtersets(Object.values(unexpanded_filtersets));
803 for (const filter of filtersets) {
804 let players = calc_stats(json, filter);
806 if (chosen_category === 'general') {
807 rows = make_table_general(players);
808 } else if (chosen_category === 'offense') {
809 rows = make_table_offense(players);
810 } else if (chosen_category === 'defense') {
811 rows = make_table_defense(players);
812 } else if (chosen_category === 'playing_time') {
813 rows = make_table_playing_time(players);
814 } else if (chosen_category === 'per_point') {
815 rows = make_table_per_point(players);
816 } else if (chosen_category === 'team_wide') {
817 rows = make_table_team_wide(players);
822 let merged_rows = [];
823 if (filtersets.length > 1) {
824 for (let i = 0; i < rowsets.length; ++i) {
825 let marker = make_filter_marker(filtersets[i]);
827 // Make filter header.
828 let tr = rowsets[i][0];
829 let th = document.createElement('th');
831 tr.insertBefore(th, tr.firstChild);
833 for (let j = 1; j < rowsets[i].length; ++j) {
834 let tr = rowsets[i][j];
836 // Remove the name for cleanness.
838 tr.firstChild.nextSibling.textContent = '';
842 tr.style.borderTop = '0px';
844 if (i != rowsets.length - 1) {
845 tr.style.borderBottom = '0px';
848 // Make filter marker.
849 let td = document.createElement('td');
850 td.textContent = marker;
851 td.classList.add('filtermarker');
852 tr.insertBefore(td, tr.firstChild);
856 for (let i = 0; i < rowsets[0].length; ++i) {
857 for (let j = 0; j < rowsets.length; ++j) {
858 merged_rows.push(rowsets[j][i]);
859 if (i === 0) break; // Don't merge the headings.
863 merged_rows = rowsets[0];
865 document.getElementById('stats').replaceChildren(...merged_rows);
868 function get_chosen_category() {
869 if (window.location.hash === '#offense') {
871 } else if (window.location.hash === '#defense') {
873 } else if (window.location.hash === '#playing_time') {
874 return 'playing_time';
875 } else if (window.location.hash === '#per_point') {
877 } else if (window.location.hash === '#team_wide') {
884 function write_main_menu(chosen_category) {
887 ['general', 'General'],
888 ['offense', 'Offense'],
889 ['defense', 'Defense'],
890 ['playing_time', 'Playing time'],
891 ['per_point', 'Per point'],
892 ['team_wide', 'Team-wide'],
894 for (const [id, title] of categories) {
895 if (chosen_category === id) {
896 let span = document.createElement('span');
897 span.innerText = title;
900 let a = document.createElement('a');
901 a.appendChild(document.createTextNode(title));
902 a.setAttribute('href', '#' + id);
907 document.getElementById('mainmenu').replaceChildren(...elems);
910 // https://en.wikipedia.org/wiki/1.96#History
913 const ci_width = 100;
914 const ci_height = 20;
916 function make_binomial_ci(val, num, z) {
919 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
920 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
921 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
923 // Fix the signs so that we don't get -0.00.
924 low = Math.max(low, 0.0);
934 // These can only happen once per point, but you get -1 and +1
935 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
936 // and then we can rewrite back.
937 function make_efficiency_ci(points_won, points_completed, z)
939 let ci = make_binomial_ci(points_won, points_completed, z);
940 ci.val = 2.0 * ci.val - 1.0;
941 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
942 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
945 ci.desired = 0.0; // Desired = positive efficiency.
949 // Ds, throwaways and drops can happen multiple times per point,
950 // so they are Poisson distributed.
952 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
953 // since our rates are definitely below 2 per point).
955 // FIXME: z is ignored.
956 function make_poisson_ci(val, num, z, inverted)
958 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
959 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
961 // Fix the signs so that we don't get -0.00.
962 low = Math.max(low, 0.0);
964 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
973 'inverted': inverted,
977 // Wilson and Hilferty, again recommended for general use in the PDF above
978 // (anything from their group “G1” works).
979 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
980 function make_poisson_ci_large(val, num, z)
982 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
983 let high = (val + 1.0) * Math.pow(1.0 - 1.0 / (9.0 * (val + 1.0)) + z / (3.0 * Math.sqrt(val + 1.0)), 3.0) / num;
985 // Fix the signs so that we don't get -0.00.
986 low = Math.max(low, 0.0);
988 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
989 // (this is used for number of touches).
1002 // We don't really know what to expect for possessions; it appears roughly
1003 // lognormal, but my head doesn't work well enough to extract the CI for
1004 // the estimated sample mean, and now my head spins around whether we do
1005 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
1006 // here, which should give us what we want.
1008 // FIXME: z is ignored.
1009 function make_ci_duration(vals, z)
1012 let sample_means = [];
1013 for (let i = 0; i < 300; ++i) {
1015 for (let j = 0; j < vals.length; ++j) {
1016 sum += vals[Math.floor(Math.random() * vals.length)];
1018 sample_means.push(sum / vals.length);
1020 sample_means.sort();
1022 // Interpolating here would probably be better, but OK.
1023 let low = sample_means[Math.floor(0.025 * sample_means.length)];
1024 let high = sample_means[Math.floor(0.975 * sample_means.length)];
1026 // Find the point estimate of the mean.
1028 for (const v of vals) {
1031 let avg = sum / vals.length;
1034 'val': avg / 1000.0,
1035 'lower_ci': low / 1000.0,
1036 'upper_ci': high / 1000.0,
1046 function make_table_general(players) {
1049 let header = document.createElement('tr');
1050 add_th(header, 'Player');
1051 add_th(header, '+/-');
1052 add_th(header, 'Soft +/-');
1053 add_th(header, 'O efficiency');
1054 add_th(header, 'D efficiency');
1055 add_th(header, 'Points played');
1059 for (const [q,p] of get_sorted_players(players)) {
1060 if (q === 'globals') continue;
1061 let row = document.createElement('tr');
1062 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1063 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1064 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1065 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1066 let name = add_3cell(row, p.name, 'name'); // TODO: number?
1067 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1068 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1069 add_3cell_ci(row, o_efficiency);
1070 add_3cell_ci(row, d_efficiency);
1071 add_3cell(row, p.points_played);
1072 row.dataset.player = q;
1077 let globals = players['globals'];
1078 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1079 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1080 let row = document.createElement('tr');
1084 add_3cell_ci(row, o_efficiency);
1085 add_3cell_ci(row, d_efficiency);
1086 add_3cell(row, globals.points_played);
1092 function make_table_team_wide(players) {
1093 let globals = players['globals'];
1097 let header = document.createElement('tr');
1099 add_th(header, 'Our team', 6);
1100 add_th(header, 'Opponents', 6);
1106 let row = document.createElement('tr');
1107 let name = add_3cell(row, 'Turnovers generated', 'name');
1108 add_3cell(row, globals.turnovers_won);
1110 add_3cell(row, globals.turnovers_lost);
1117 let row = document.createElement('tr');
1118 let name = add_3cell(row, 'Clean holds', 'name');
1119 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1120 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1121 our_clean_holds.desired = 0.3; // Arbitrary.
1122 our_clean_holds.format = 'percentage';
1123 their_clean_holds.desired = 0.3;
1124 their_clean_holds.format = 'percentage';
1125 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1126 add_3cell_ci(row, our_clean_holds);
1127 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1128 add_3cell_ci(row, their_clean_holds);
1134 let row = document.createElement('tr');
1135 let name = add_3cell(row, 'Clean breaks', 'name');
1136 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1137 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1138 our_clean_breaks.desired = 0.3; // Arbitrary.
1139 our_clean_breaks.format = 'percentage';
1140 their_clean_breaks.desired = 0.3;
1141 their_clean_breaks.format = 'percentage';
1142 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1143 add_3cell_ci(row, our_clean_breaks);
1144 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1145 add_3cell_ci(row, their_clean_breaks);
1149 // Touches. We only have information for our team here.
1152 for (const [q,p] of get_sorted_players(players)) {
1153 if (q === 'globals') continue;
1156 let row = document.createElement('tr');
1157 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1158 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1159 let possessions = goals + globals.turnovers_lost;
1161 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1166 row = document.createElement('tr');
1167 add_3cell(row, 'Touches per possession (goals)', 'name');
1169 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1174 row = document.createElement('tr');
1175 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1177 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1183 // Time. Here we have (roughly) for both.
1185 let row = document.createElement('tr');
1186 let name = add_3cell(row, 'Time per possession (all)', 'name');
1187 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1188 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1190 add_3cell_ci(row, make_ci_duration(time, z));
1192 add_3cell_ci(row, make_ci_duration(their_time, z));
1195 row = document.createElement('tr');
1196 add_3cell(row, 'Time per possession (goals)', 'name');
1198 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1200 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1203 row = document.createElement('tr');
1204 add_3cell(row, 'Time per possession (turnovers)', 'name');
1206 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1208 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1215 function make_table_offense(players) {
1218 let header = document.createElement('tr');
1219 add_th(header, 'Player');
1220 add_th(header, 'Goals');
1221 add_th(header, 'Assists');
1222 add_th(header, 'Hockey assists');
1223 add_th(header, 'Throws');
1224 add_th(header, 'Throwaways');
1225 add_th(header, '%OK');
1226 add_th(header, 'Catches');
1227 add_th(header, 'Drops');
1228 add_th(header, 'D-ed');
1229 add_th(header, '%OK');
1230 add_th(header, 'Stalls');
1231 add_th(header, 'Soft +/-', 6);
1242 for (const [q,p] of get_sorted_players(players)) {
1243 if (q === 'globals') continue;
1244 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1245 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1247 throw_ok.format = 'percentage';
1248 catch_ok.format = 'percentage';
1250 // Desire at least 90% percentage. Fairly arbitrary.
1251 throw_ok.desired = 0.9;
1252 catch_ok.desired = 0.9;
1254 let row = document.createElement('tr');
1255 add_3cell(row, p.name, 'name'); // TODO: number?
1256 add_3cell(row, p.goals);
1257 add_3cell(row, p.assists);
1258 add_3cell(row, p.hockey_assists);
1259 add_3cell(row, p.num_throws);
1260 add_3cell(row, p.throwaways);
1261 add_3cell_ci(row, throw_ok);
1262 add_3cell(row, p.catches);
1263 add_3cell(row, p.drops);
1264 add_3cell(row, p.was_ds);
1265 add_3cell_ci(row, catch_ok);
1266 add_3cell(row, p.stallouts);
1267 add_3cell(row, '+' + p.offensive_soft_plus);
1268 add_3cell(row, '-' + p.offensive_soft_minus);
1269 row.dataset.player = q;
1273 num_throws += p.num_throws;
1274 throwaways += p.throwaways;
1275 catches += p.catches;
1278 stallouts += p.stallouts;
1282 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1283 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1284 throw_ok.format = 'percentage';
1285 catch_ok.format = 'percentage';
1286 throw_ok.desired = 0.9;
1287 catch_ok.desired = 0.9;
1289 let row = document.createElement('tr');
1291 add_3cell(row, goals);
1294 add_3cell(row, num_throws);
1295 add_3cell(row, throwaways);
1296 add_3cell_ci(row, throw_ok);
1297 add_3cell(row, catches);
1298 add_3cell(row, drops);
1299 add_3cell(row, was_ds);
1300 add_3cell_ci(row, catch_ok);
1301 add_3cell(row, stallouts);
1309 function make_table_defense(players) {
1312 let header = document.createElement('tr');
1313 add_th(header, 'Player');
1314 add_th(header, 'Ds');
1315 add_th(header, 'Pulls');
1316 add_th(header, 'OOB pulls');
1317 add_th(header, 'OOB%');
1318 add_th(header, 'Avg. hang time (IB)');
1319 add_th(header, 'Callahans');
1320 add_th(header, 'Soft +/-', 6);
1327 let sum_sum_time = 0;
1330 for (const [q,p] of get_sorted_players(players)) {
1331 if (q === 'globals') continue;
1333 for (const t of p.pull_times) {
1336 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1337 let oob_pct = 100 * p.oob_pulls / p.pulls;
1339 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1340 ci_oob.format = 'percentage';
1341 ci_oob.desired = 0.2; // Arbitrary.
1342 ci_oob.inverted = true;
1344 let row = document.createElement('tr');
1345 add_3cell(row, p.name, 'name'); // TODO: number?
1346 add_3cell(row, p.defenses);
1347 add_3cell(row, p.pulls);
1348 add_3cell(row, p.oob_pulls);
1349 add_3cell_ci(row, ci_oob);
1350 if (p.pulls > p.oob_pulls) {
1351 add_3cell(row, avg_time.toFixed(1) + ' sec');
1353 add_3cell(row, 'N/A');
1355 add_3cell(row, p.callahans);
1356 add_3cell(row, '+' + p.defensive_soft_plus);
1357 add_3cell(row, '-' + p.defensive_soft_minus);
1358 row.dataset.player = q;
1361 defenses += p.defenses;
1363 oob_pulls += p.oob_pulls;
1364 sum_sum_time += sum_time;
1365 callahans += p.callahans;
1369 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1370 ci_oob.format = 'percentage';
1371 ci_oob.desired = 0.2; // Arbitrary.
1372 ci_oob.inverted = true;
1374 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1375 let oob_pct = 100 * oob_pulls / pulls;
1377 let row = document.createElement('tr');
1379 add_3cell(row, defenses);
1380 add_3cell(row, pulls);
1381 add_3cell(row, oob_pulls);
1382 add_3cell_ci(row, ci_oob);
1383 if (pulls > oob_pulls) {
1384 add_3cell(row, avg_time.toFixed(1) + ' sec');
1386 add_3cell(row, 'N/A');
1388 add_3cell(row, callahans);
1396 function make_table_playing_time(players) {
1399 let header = document.createElement('tr');
1400 add_th(header, 'Player');
1401 add_th(header, 'Points played');
1402 add_th(header, 'Time played');
1403 add_th(header, 'O time');
1404 add_th(header, 'D time');
1405 add_th(header, 'Time on field');
1406 add_th(header, 'O points');
1407 add_th(header, 'D points');
1411 for (const [q,p] of get_sorted_players(players)) {
1412 if (q === 'globals') continue;
1413 let row = document.createElement('tr');
1414 add_3cell(row, p.name, 'name'); // TODO: number?
1415 add_3cell(row, p.points_played);
1416 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1417 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1418 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1419 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1420 add_3cell(row, p.offensive_points_completed);
1421 add_3cell(row, p.defensive_points_completed);
1422 row.dataset.player = q;
1427 let globals = players['globals'];
1428 let row = document.createElement('tr');
1430 add_3cell(row, globals.points_played);
1431 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1432 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1433 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1434 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1435 add_3cell(row, globals.offensive_points_completed);
1436 add_3cell(row, globals.defensive_points_completed);
1442 function make_table_per_point(players) {
1445 let header = document.createElement('tr');
1446 add_th(header, 'Player');
1447 add_th(header, 'Goals');
1448 add_th(header, 'Assists');
1449 add_th(header, 'Hockey assists');
1450 add_th(header, 'Ds');
1451 add_th(header, 'Throwaways');
1452 add_th(header, 'Recv. errors');
1453 add_th(header, 'Touches');
1459 let hockey_assists = 0;
1462 let receiver_errors = 0;
1464 for (const [q,p] of get_sorted_players(players)) {
1465 if (q === 'globals') continue;
1467 // Can only happen once per point, so these are binomials.
1468 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1469 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1470 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1471 // Arbitrarily desire at least 10% (not everybody can score or assist).
1472 ci_goals.desired = 0.1;
1473 ci_assists.desired = 0.1;
1474 ci_hockey_assists.desired = 0.1;
1476 let row = document.createElement('tr');
1477 add_3cell(row, p.name, 'name'); // TODO: number?
1478 add_3cell_ci(row, ci_goals);
1479 add_3cell_ci(row, ci_assists);
1480 add_3cell_ci(row, ci_hockey_assists);
1481 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1482 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1483 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1484 if (p.points_played > 0) {
1485 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1487 add_3cell(row, 'N/A');
1489 row.dataset.player = q;
1493 assists += p.assists;
1494 hockey_assists += p.hockey_assists;
1495 defenses += p.defenses;
1496 throwaways += p.throwaways;
1497 receiver_errors += p.drops + p.was_ds;
1498 touches += p.touches;
1502 let globals = players['globals'];
1503 let row = document.createElement('tr');
1505 if (globals.points_played > 0) {
1506 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1507 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1508 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1509 ci_goals.desired = 0.5;
1510 ci_assists.desired = 0.5;
1511 ci_hockey_assists.desired = 0.5;
1513 add_3cell_ci(row, ci_goals);
1514 add_3cell_ci(row, ci_assists);
1515 add_3cell_ci(row, ci_hockey_assists);
1517 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1518 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1519 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1521 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1523 add_3cell_with_filler_ci(row, 'N/A');
1524 add_3cell_with_filler_ci(row, 'N/A');
1525 add_3cell_with_filler_ci(row, 'N/A');
1526 add_3cell_with_filler_ci(row, 'N/A');
1527 add_3cell_with_filler_ci(row, 'N/A');
1528 add_3cell_with_filler_ci(row, 'N/A');
1529 add_3cell(row, 'N/A');
1536 function open_filter_menu(click_to_add_div) {
1537 document.getElementById('filter-submenu').style.display = 'none';
1538 let filter_div = click_to_add_div.parentElement;
1539 let filter_id = filter_div.dataset.filterId;
1541 let menu = document.getElementById('filter-add-menu');
1542 menu.parentElement.removeChild(menu);
1543 filter_div.appendChild(menu);
1544 menu.style.display = 'block';
1545 menu.replaceChildren();
1547 // Place the menu directly under the “click to add” label;
1548 // we don't anchor it since that label will move around
1549 // and the menu shouldn't.
1550 let rect = click_to_add_div.getBoundingClientRect();
1551 menu.style.left = rect.left + 'px';
1552 menu.style.top = (rect.bottom + 10) + 'px';
1554 let filterset = global_filters[filter_id];
1555 if (filterset === undefined) {
1556 global_filters[filter_id] = filterset = [];
1559 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1560 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1561 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1562 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1563 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1564 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1565 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1568 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1569 let item = document.createElement('div');
1570 item.classList.add('option');
1571 item.appendChild(document.createTextNode(title));
1573 let arrow = document.createElement('div');
1574 arrow.classList.add('arrow');
1575 arrow.textContent = '▸';
1576 item.appendChild(arrow);
1578 menu.appendChild(item);
1580 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1583 function find_all_ratios(json)
1587 for (const player of json['players']) {
1588 players[player['player_id']] = {
1589 'gender': player['gender'],
1590 'last_point_seen': null,
1593 for (const match of json['matches']) {
1594 for (const [q,p] of Object.entries(players)) {
1595 p.on_field_since = null;
1597 for (const e of match['events']) {
1598 let p = players[e['player']];
1599 let type = e['type'];
1600 if (type === 'in') {
1601 p.on_field_since = 1;
1602 } else if (type === 'out') {
1603 p.on_field_since = null;
1604 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1605 let code = find_gender_ratio_code(players);
1606 if (ratios[code] === undefined) {
1607 ratios[code] = code;
1608 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1609 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1610 match['description'] + ', ' + format_time(e['t']));
1619 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1620 let submenu = document.getElementById('filter-submenu');
1622 // Move to the same place as the top-level menu.
1623 submenu.parentElement.removeChild(submenu);
1624 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1627 const filter = find_filter(filterset, filter_type);
1630 if (filter_type === 'match') {
1631 for (const match of global_json['matches']) {
1633 'title': match['description'],
1634 'id': match['match_id']
1637 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1638 for (const player of global_json['players']) {
1640 'title': player['name'],
1641 'id': player['player_id']
1644 } else if (filter_type === 'formation_offense') {
1646 'title': '(None/unknown)',
1649 for (const formation of global_json['formations']) {
1650 if (formation['offense']) {
1652 'title': formation['name'],
1653 'id': formation['formation_id']
1657 } else if (filter_type === 'formation_defense') {
1659 'title': '(None/unknown)',
1662 for (const formation of global_json['formations']) {
1663 if (!formation['offense']) {
1665 'title': formation['name'],
1666 'id': formation['formation_id']
1670 } else if (filter_type === 'starting_on') {
1673 'id': false, // last_pull_was_ours
1677 'id': true, // last_pull_was_ours
1679 } else if (filter_type === 'gender_ratio') {
1680 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1688 let choice_set = new Set();
1689 for (const choice of choices) {
1690 choice_set.add(choice.id);
1693 for (const choice of choices) {
1694 let label = document.createElement('label');
1696 let subitem = document.createElement('div');
1697 subitem.classList.add('option');
1699 let check = document.createElement('input');
1700 check.setAttribute('type', 'checkbox');
1701 check.setAttribute('id', 'choice' + choice.id);
1702 if (filter !== null && filter.elements.has(choice.id)) {
1703 check.setAttribute('checked', 'checked');
1705 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id, choice_set); });
1707 subitem.appendChild(check);
1708 subitem.appendChild(document.createTextNode(choice.title));
1710 label.appendChild(subitem);
1711 subitems.push(label);
1714 // If meaningful (it's not for player_all, since all data for that would be
1715 // the same anyway), show the split checkbox.
1716 if (choices.length > 1 && filter_type !== 'player_all') {
1717 let label = document.createElement('label');
1719 let subitem = document.createElement('div');
1720 subitem.classList.add('option');
1722 let check = document.createElement('input');
1723 check.setAttribute('type', 'checkbox');
1724 check.setAttribute('id', 'choice_split');
1725 if (filter !== null && filter.split) {
1726 check.setAttribute('checked', 'checked');
1728 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, 'split', choice_set); });
1730 subitem.appendChild(check);
1731 let text_span = document.createElement('span'); // So that we can style its disabling later.
1732 text_span.appendChild(document.createTextNode('Split'));
1733 subitem.appendChild(text_span);
1734 subitem.style.borderTop = '1px solid #ddd';
1736 label.appendChild(subitem);
1737 subitems.push(label);
1740 submenu.replaceChildren(...subitems);
1741 submenu.style.display = 'block';
1743 if (pill !== null) {
1744 let rect = pill.getBoundingClientRect();
1745 submenu.style.top = (rect.bottom + 10) + 'px';
1746 submenu.style.left = rect.left + 'px';
1748 // Position just outside the selected menu.
1749 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1750 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1751 submenu.style.left = (rect.right - 1) + 'px';
1755 // Find the right filter, if it exists.
1756 function find_filter(filterset, filter_type) {
1757 for (let f of filterset) {
1758 if (f.type === filter_type) {
1765 // Equivalent to Array.prototype.filter, but in-place.
1766 function inplace_filter(arr, cond) {
1768 for (let i = 0; i < arr.length; ++i) {
1776 function add_new_filterset() {
1777 let template = document.querySelector('.filter'); // First one is fine.
1778 let div = template.cloneNode(true);
1779 let add_menu = div.querySelector('#filter-add-menu');
1780 if (add_menu !== null) {
1781 div.removeChild(add_menu);
1783 let submenu = div.querySelector('#filter-submenu');
1784 if (submenu !== null) {
1785 div.removeChild(submenu);
1787 div.querySelector('.filters').replaceChildren();
1788 div.dataset.filterId = next_filterset_id++;
1789 template.parentElement.appendChild(div);
1792 function try_gc_filter_menus(cheap) {
1795 for (const filter_div of document.querySelectorAll('.filter')) {
1796 let id = filter_div.dataset.filterId;
1797 divs.push(filter_div);
1798 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1800 let last_div = divs[empties.length - 1];
1802 // See if we have two empty filter lists at the bottom of the list;
1803 // if so, we can remove one without it looking funny in the UI.
1804 // If not, we'll have to wait until closing the menu.
1805 // (The menu is positioned at the second-last one, so we can
1806 // remove the last one without issue.)
1807 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1808 delete global_filters[last_div.dataset.filterId];
1809 last_div.parentElement.removeChild(last_div);
1812 // This is a different situation from try_cheap_gc(), where we should
1813 // remove the one _not_ last. We might need to move the menu to the last one,
1814 // though, so it doesn't get lost.
1815 for (let i = 0; i < empties.length - 1; ++i) {
1820 delete global_filters[div.dataset.filterId];
1821 let add_menu = div.querySelector('#filter-add-menu');
1822 if (add_menu !== null) {
1823 div.removeChild(add_menu);
1824 last_div.appendChild(add_menu);
1826 let submenu = div.querySelector('#filter-submenu');
1827 if (submenu !== null) {
1828 div.removeChild(submenu);
1829 last_div.appendChild(submenu);
1831 div.parentElement.removeChild(div);
1836 function checkbox_changed(filter_div, filterset, e, filter_type, id, choices) {
1837 let filter = find_filter(filterset, filter_type);
1838 let pills_div = filter_div.querySelector('.filters');
1839 if (e.target.checked) {
1840 // See if we must create a new empty filterset (since this went from
1841 // empty to non-empty).
1842 if (filterset.length === 0) {
1843 add_new_filterset();
1846 // See if we must add a new filter to the list.
1847 if (filter === null) {
1849 'type': filter_type,
1850 'elements': new Set(),
1854 if (id === 'split') {
1855 filter.split = true;
1857 filter.elements.add(id);
1859 filter.pill = make_filter_pill(filter_div, filterset, filter);
1860 filterset.push(filter);
1861 pills_div.appendChild(filter.pill);
1863 if (id === 'split') {
1864 filter.split = true;
1866 filter.elements.add(id);
1868 let new_pill = make_filter_pill(filter_div, filterset, filter);
1869 pills_div.replaceChild(new_pill, filter.pill);
1870 filter.pill = new_pill;
1873 if (id === 'split') {
1874 filter.split = false;
1876 filter.elements.delete(id);
1878 if (filter.elements.size === 0) {
1879 pills_div.removeChild(filter.pill);
1880 inplace_filter(filterset, f => f !== filter);
1882 if (filterset.length == 0) {
1883 try_gc_filter_menus(true);
1886 let new_pill = make_filter_pill(filter_div, filterset, filter);
1887 pills_div.replaceChild(new_pill, filter.pill);
1888 filter.pill = new_pill;
1891 let choice_split = document.getElementById('choice_split');
1892 if (filter.elements.size === 1) {
1893 choice_split.nextSibling.style.opacity = 0.2;
1894 choice_split.setAttribute('disabled', 'disabled');
1896 choice_split.nextSibling.style.opacity = 1.0;
1897 choice_split.removeAttribute('disabled');
1900 process_matches(global_json, global_filters);
1903 function make_filter_pill(filter_div, filterset, filter) {
1904 let pill = document.createElement('div');
1905 pill.classList.add('filter-pill');
1907 if (filter.type === 'match') {
1911 for (const match_id of filter.elements) {
1912 all_names.push(find_match(match_id)['description']);
1914 let common_prefix = find_common_prefix_of_all(all_names);
1915 if (common_prefix !== null) {
1916 text += common_prefix + '(';
1920 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1921 for (const match_id of sorted_match_id) {
1925 let desc = find_match(match_id)['description'];
1926 if (common_prefix === null) {
1929 text += desc.substr(common_prefix.length);
1934 if (common_prefix !== null) {
1937 } else if (filter.type === 'player_any') {
1938 text = 'Player (any): ';
1939 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1941 for (const player_id of sorted_players) {
1945 text += find_player(player_id)['name'];
1948 } else if (filter.type === 'player_all') {
1950 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1952 for (const player_id of sorted_players) {
1956 text += find_player(player_id)['name'];
1959 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1960 const offense = (filter.type === 'formation_offense');
1968 for (const formation_id of filter.elements) {
1969 all_names.push(find_formation(formation_id)['name']);
1971 let common_prefix = find_common_prefix_of_all(all_names);
1972 if (common_prefix !== null) {
1973 text += common_prefix + '(';
1977 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1978 for (const formation_id of sorted_formation_id) {
1982 let desc = find_formation(formation_id)['name'];
1983 if (common_prefix === null) {
1986 text += desc.substr(common_prefix.length);
1991 if (common_prefix !== null) {
1994 } else if (filter.type === 'starting_on') {
1995 text = 'Starting on: ';
1997 if (filter.elements.has(false) && filter.elements.has(true)) {
1999 } else if (filter.elements.has(false)) {
2004 } else if (filter.type === 'gender_ratio') {
2008 for (const name of Array.from(filter.elements).sort()) {
2012 text += name; // FIXME
2016 if (filter.split && filter.elements.size !== 1) {
2020 let text_node = document.createElement('span');
2021 text_node.innerText = text;
2022 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
2023 pill.appendChild(text_node);
2025 pill.appendChild(document.createTextNode(' '));
2027 let delete_node = document.createElement('span');
2028 delete_node.innerText = '✖';
2029 delete_node.addEventListener('click', (e) => {
2030 // Delete this filter entirely.
2031 pill.parentElement.removeChild(pill);
2032 inplace_filter(filterset, f => f !== filter);
2033 if (filterset.length == 0) {
2034 try_gc_filter_menus(false);
2036 process_matches(global_json, global_filters);
2038 let add_menu = document.getElementById('filter-add-menu');
2039 let add_submenu = document.getElementById('filter-submenu');
2040 add_menu.style.display = 'none';
2041 add_submenu.style.display = 'none';
2043 pill.appendChild(delete_node);
2044 pill.style.cursor = 'pointer';
2049 function make_filter_marker(filterset) {
2051 for (const filter of filterset) {
2055 if (filter.type === 'match') {
2057 for (const match of global_json['matches']) {
2058 all_names.push(match['description']);
2060 let common_prefix = find_common_prefix_of_all(all_names);
2062 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
2063 for (const match_id of sorted_match_id) {
2064 let desc = find_match(match_id)['description'];
2065 if (common_prefix === null) {
2066 text += desc.substr(0, 3);
2068 text += desc.substr(common_prefix.length, 3);
2071 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
2072 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
2073 for (const player_id of sorted_players) {
2074 text += find_player(player_id)['name'].substr(0, 3);
2076 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2077 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
2078 for (const formation_id of sorted_formation_id) {
2079 text += find_formation(formation_id)['name'].substr(0, 3);
2081 } else if (filter.type === 'starting_on') {
2082 if (filter.elements.has(false) && filter.elements.has(true)) {
2084 } else if (filter.elements.has(false)) {
2089 } else if (filter.type === 'gender_ratio') {
2091 for (const name of Array.from(filter.elements).sort()) {
2095 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
2103 function find_common_prefix(a, b) {
2105 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2106 if (a[i] === b[i]) {
2115 function find_common_prefix_of_all(values) {
2116 if (values.length < 2) {
2119 let common_prefix = null;
2120 for (const desc of values) {
2121 if (common_prefix === null) {
2122 common_prefix = desc;
2124 common_prefix = find_common_prefix(common_prefix, desc);
2127 if (common_prefix.length >= 3) {
2128 return common_prefix;
2134 function find_match(match_id) {
2135 for (const match of global_json['matches']) {
2136 if (match['match_id'] === match_id) {
2143 function find_formation(formation_id) {
2144 for (const formation of global_json['formations']) {
2145 if (formation['formation_id'] === formation_id) {
2152 function find_player(player_id) {
2153 for (const player of global_json['players']) {
2154 if (player['player_id'] === player_id) {
2161 function player_pos(player_id) {
2163 for (const player of global_json['players']) {
2164 if (player['player_id'] === player_id) {
2172 function keep_match(match_id, filters) {
2173 for (const filter of filters) {
2174 if (filter.type === 'match') {
2175 return filter.elements.has(match_id);
2181 // Returns a map of e.g. F => 4, M => 3.
2182 function find_gender_ratio(players) {
2184 for (const [q,p] of Object.entries(players)) {
2185 if (p.on_field_since === null) {
2188 let gender = p.gender;
2189 if (gender === '' || gender === undefined || gender === null) {
2192 if (map[gender] === undefined) {
2201 function find_gender_ratio_code(players) {
2202 let map = find_gender_ratio(players);
2203 let all_genders = Array.from(Object.keys(map)).sort(
2205 if (map[a] !== map[b]) {
2206 return map[b] - map[a]; // Reverse numeric.
2216 for (const g of all_genders) {
2227 // null if none (e.g., if playing 3–3).
2228 function find_predominant_gender(players) {
2230 let predominant_gender = null;
2231 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2234 predominant_gender = gender;
2235 } else if (num == max) {
2236 predominant_gender = null; // At least two have the same.
2239 return predominant_gender;
2242 function find_num_players_on_field(players) {
2244 for (const [q,p] of Object.entries(players)) {
2245 if (p.on_field_since !== null) {
2252 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2253 if (filter.type === 'player_any') {
2254 for (const p of Array.from(filter.elements)) {
2255 if (players[p].on_field_since !== null) {
2260 } else if (filter.type === 'player_all') {
2261 for (const p of Array.from(filter.elements)) {
2262 if (players[p].on_field_since === null) {
2267 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2268 for (const f of Array.from(filter.elements)) {
2269 if (formations_used_this_point.has(f)) {
2274 } else if (filter.type === 'starting_on') {
2275 return filter.elements.has(last_pull_was_ours);
2276 } else if (filter.type === 'gender_ratio') {
2277 return filter.elements.has(find_gender_ratio_code(players));
2282 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2283 for (const filter of filters) {
2284 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2291 // Heuristic: If we go at least ten seconds without the possession changing
2292 // or the operator specifying some other formation, we probably play the
2293 // same formation as the last point.
2294 function should_reuse_last_formation(events, t) {
2295 for (const e of events) {
2299 if (e.t > t + 10000) {
2302 const type = e.type;
2303 if (type === 'their_goal' || type === 'goal' ||
2304 type === 'set_defense' || type === 'set_offense' ||
2305 type === 'throwaway' || type === 'their_throwaway' ||
2306 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2307 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2308 type === 'formation_offense' || type === 'formation_defense') {
2315 function possibly_close_menu(e) {
2316 if (e.target.closest('.filter-click-to-add') === null &&
2317 e.target.closest('#filter-add-menu') === null &&
2318 e.target.closest('#filter-submenu') === null &&
2319 e.target.closest('.filter-pill') === null) {
2320 let add_menu = document.getElementById('filter-add-menu');
2321 let add_submenu = document.getElementById('filter-submenu');
2322 add_menu.style.display = 'none';
2323 add_submenu.style.display = 'none';
2324 try_gc_filter_menus(false);
2328 let global_sort = {};
2330 function sort_by(th) {
2331 let tr = th.parentElement;
2333 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2334 let element = tr.children[column_idx];
2335 if (element === th) {
2336 ++child_idx; // Pad.
2339 if (element.hasAttribute('colspan')) {
2340 child_idx += parseInt(element.getAttribute('colspan'));
2347 let table = tr.parentElement;
2348 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2349 let row = table.children[row_idx];
2350 let player = parseInt(row.dataset.player);
2351 let value = row.children[child_idx].textContent;
2352 global_sort[player] = value;
2356 function get_sorted_players(players)
2358 let p = Object.entries(players);
2359 if (global_sort.length !== 0) {
2361 let ai = parseFloat(global_sort[a[0]]);
2362 let bi = parseFloat(global_sort[b[0]]);
2363 if (ai == ai && bi == bi) {
2364 return bi - ai; // Reverse numeric.
2365 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2367 } else if (global_sort[a[0]] > global_sort[b[0]]) {