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 for (const [q,p] of Object.entries(players)) {
395 if (p.on_field_since === null) {
398 if (type !== 'stoppage' && p.last_point_seen !== point_num) {
400 // In case the player did nothing this point,
401 // not even subbing in.
402 p.last_point_seen = point_num;
406 if (keep) attribute_player_time(p, t, live_since, offense);
408 if (type !== 'stoppage') {
410 if (last_pull_was_ours === true) { // D point.
411 ++p.defensive_points_completed;
412 if (type === 'goal') {
413 ++p.defensive_points_won;
415 } else if (last_pull_was_ours === false) { // O point.
416 ++p.offensive_points_completed;
417 if (type === 'goal') {
418 ++p.offensive_points_won;
426 if (type !== 'stoppage') {
428 ++globals.points_played;
429 if (last_pull_was_ours === true) { // D point.
430 ++globals.defensive_points_completed;
431 if (type === 'goal') {
432 ++globals.defensive_points_won;
434 } else if (last_pull_was_ours === false) { // O point.
435 ++globals.offensive_points_completed;
436 if (type === 'goal') {
437 ++globals.offensive_points_won;
441 if (live_since !== null) {
442 globals.playing_time_ms += t - live_since;
443 if (offense === true) {
444 globals.offensive_playing_time_ms += t - live_since;
445 } else if (offense === false) {
446 globals.defensive_playing_time_ms += t - live_since;
455 if (type === 'goal') {
457 } else if (type === 'their_goal') {
461 // Point count management
462 if (p !== undefined && type !== 'out' && p.last_point_seen !== point_num) {
464 p.last_point_seen = point_num;
468 if (type === 'goal' || type === 'their_goal') {
472 if (type !== 'out' && game_started === null) {
477 if (type === 'pull') {
478 puller = e['player'];
480 keep = keep_event(players, formations_used_this_point, /*last_pull_was_ours=*/true, filters); // Will change below. This is an ugly hack.
482 } else if (type === 'in' || type === 'out' || type === 'stoppage' || type === 'restart' || type === 'unknown' || type === 'set_defense' || type === 'set_offense') {
483 // No effect on pull.
484 } else if (type === 'pull_landed' && puller !== null) {
485 if (keep) players[puller].pull_times.push(t - pull_started);
486 } else if (type === 'pull_oob' && puller !== null) {
487 if (keep) ++players[puller].oob_pulls;
489 // Not pulling (if there was one, we never recorded its outcome, but still count it).
490 puller = pull_started = null;
493 // Stats for clean holds or not (must be done before resetting we_lost_disc etc. below).
495 if (type === 'goal' && !we_lost_disc) {
496 if (last_pull_was_ours === false) { // O point.
497 ++globals.clean_holds;
498 } else if (last_pull_was_ours === true) {
499 ++globals.clean_breaks;
501 } else if (type === 'their_goal' && !they_lost_disc) {
502 if (last_pull_was_ours === true) { // O point for them.
503 ++globals.their_clean_holds;
504 } else if (last_pull_was_ours === false) {
505 ++globals.their_clean_breaks;
510 // Offense/defense management
511 let last_offense = offense;
512 if (type === 'set_defense' || type === 'goal' || type === 'throwaway' || type === 'drop' || type === 'was_d' || type === 'stallout') {
515 if (keep && type !== 'goal' && !(type === 'set_defense' && last_pull_was_ours === null)) {
516 ++globals.turnovers_lost;
517 globals.touches_for_turnover += touches_this_possession;
518 if (possession_started != null) globals.time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
519 } else if (keep && type === 'goal') {
520 globals.touches_for_goal += touches_this_possession;
521 if (possession_started != null) globals.time_for_goal.push((t - possession_started) + extra_ms_this_possession);
523 touches_this_possession = 0;
524 possession_started = null;
525 extra_ms_this_possession = 0;
526 } else if (type === 'set_offense' || type === 'their_goal' || type === 'their_throwaway' || type === 'defense' || type === 'interception') {
528 they_lost_disc = true;
529 if (keep && type !== 'their_goal' && !(type === 'set_offense' && last_pull_was_ours === null)) {
530 ++globals.turnovers_won;
531 if (possession_started != null) globals.their_time_for_turnover.push((t - possession_started) + extra_ms_this_possession);
532 } else if (keep && type === 'their_goal') {
533 if (possession_started != null) globals.their_time_for_goal.push((t - possession_started) + extra_ms_this_possession);
535 touches_this_possession = 0;
536 possession_started = null;
537 extra_ms_this_possession = 0;
539 if (type === 'goal' || type === 'their_goal') {
540 between_points = true;
541 we_lost_disc = false;
542 they_lost_disc = false;
543 touches_this_possession = 0;
545 if (last_offense !== offense && live_since !== null) {
546 // Switched offense/defense status, so attribute this drive as needed,
547 // and update live_since to take that into account.
549 for (const [q,p] of Object.entries(players)) {
550 if (p.on_field_since === null) {
553 attribute_player_time(p, t, live_since, last_offense);
555 globals.playing_time_ms += t - live_since;
556 if (offense === true) {
557 globals.offensive_playing_time_ms += t - live_since;
558 } else if (offense === false) {
559 globals.defensive_playing_time_ms += t - live_since;
564 // The rules for possessions are slightly different; we want to start at pulls,
565 // not previous goals.
566 if ((last_offense !== offense && type !== 'goal' && type !== 'their_goal' && live_since !== null) ||
567 type === 'pull' || type === 'their_pull') {
568 possession_started = t;
569 } else if (type === 'stoppage') {
570 if (possession_started !== null) {
571 extra_ms_this_possession = t - possession_started;
572 possession_started = null;
574 } else if (type === 'restart' && live_since !== null && !between_points) {
575 possession_started = t;
578 // O/D-point management.
579 if (type === 'pull') {
580 last_pull_was_ours = true;
581 } else if (type === 'their_pull') {
582 last_pull_was_ours = false;
583 } else if (type === 'set_offense' && last_pull_was_ours === null) {
584 // set_offense could either be “changed to offense for some reason
585 // we could not express”, or “we started in the middle of a point,
586 // and we are offense”. We assume that if we already saw the pull,
587 // it's the former, and if not, it's the latter; thus, the === null
588 // test above. (It could also be “we set offense before the pull,
589 // so that we get the right button enabled”, in which case it will
590 // be overwritten by the next pull/their_pull event anyway.)
591 last_pull_was_ours = false;
592 } else if (type === 'set_defense' && last_pull_was_ours === null) {
594 last_pull_was_ours = true;
595 } else if (type === 'goal' || type === 'their_goal') {
596 last_pull_was_ours = null;
599 // Formation management
600 if (type === 'formation_offense' || type === 'formation_defense') {
601 let id = e.formation === null ? 0 : e.formation;
602 let for_offense = (type === 'formation_offense');
603 if (offense === for_offense) {
604 formations_used_this_point.add(id);
605 } else if (for_offense) {
606 pending_offensive_formation = id;
608 pending_defensive_formation = id;
611 last_offensive_formation = id;
613 last_defensive_formation = id;
615 } else if (last_offense !== offense) {
616 if (offense === true && pending_offensive_formation !== null) {
617 formations_used_this_point.add(pending_offensive_formation);
618 pending_offensive_formation = null;
619 } else if (offense === false && pending_defensive_formation !== null) {
620 formations_used_this_point.add(pending_defensive_formation);
621 pending_defensive_formation = null;
622 } else if (offense === true && last_defensive_formation !== null) {
623 if (should_reuse_last_formation(match['events'], t)) {
624 formations_used_this_point.add(last_defensive_formation);
626 } else if (offense === false && last_offensive_formation !== null) {
627 if (should_reuse_last_formation(match['events'], t)) {
628 formations_used_this_point.add(last_offensive_formation);
633 if (type !== 'out' && type !== 'in' && p !== undefined && p.on_field_since === null) {
634 console.log(match['description'] + ' ' + format_time(t) + ': Event “' + type + '” on subbed-out player ' + p.name);
636 if (type === 'catch' && handler !== null && players[handler].on_field_since === null) {
637 // The handler subbed out and was replaced with another handler,
638 // so this wasn't a pass.
643 if (type === 'goal' && handler === e['player'] && handler_got_by_interception) {
644 // Self-pass to goal after an interception; this is not a real pass,
645 // just how we represent a Callahan right now -- so don't
646 // count the throw, any assists or similar.
648 // It's an open question how we should handle a self-pass that is
649 // _not_ after an interception, or a self-pass that's not a goal.
650 // (It must mean we tipped off someone.) We'll count it as a regular one
651 // for the time being, although it will make hockey assists weird.
656 handler = prev_handler = null;
657 } else if (type === 'catch' || type === 'goal') {
658 if (handler !== null) {
660 ++players[handler].num_throws;
665 if (keep) ++p.touches;
666 ++touches_this_possession;
667 if (type === 'goal') {
669 if (prev_handler !== null) {
670 ++players[prev_handler].hockey_assists;
672 if (handler !== null) {
673 ++players[handler].assists;
677 handler = prev_handler = null;
679 // Update hold history.
680 prev_handler = handler;
681 handler = e['player'];
682 handler_got_by_interception = false;
684 } else if (type === 'throwaway') {
689 handler = prev_handler = null;
690 } else if (type === 'drop') {
692 handler = prev_handler = null;
693 } else if (type === 'stallout') {
694 if (keep) ++p.stallouts;
695 handler = prev_handler = null;
696 } else if (type === 'was_d') {
697 if (keep) ++p.was_ds;
698 handler = prev_handler = null;
699 } else if (type === 'defense') {
700 if (keep) ++p.defenses;
701 } else if (type === 'interception') {
706 ++touches_this_possession;
709 handler = e['player'];
710 handler_got_by_interception = true;
711 } else if (type === 'offensive_soft_plus' || type === 'offensive_soft_minus' || type === 'defensive_soft_plus' || type === 'defensive_soft_minus') {
713 } else if (type !== 'in' && type !== 'out' && type !== 'pull' &&
714 type !== 'their_goal' && type !== 'stoppage' && type !== 'restart' && type !== 'unknown' &&
715 type !== 'set_defense' && type !== 'goal' && type !== 'throwaway' &&
716 type !== 'drop' && type !== 'was_d' && type !== 'stallout' && type !== 'set_offense' && type !== 'their_goal' &&
717 type !== 'pull' && type !== 'pull_landed' && type !== 'pull_oob' && type !== 'their_pull' &&
718 type !== 'their_throwaway' && type !== 'defense' && type !== 'interception' &&
719 type !== 'formation_offense' && type !== 'formation_defense') {
720 console.log(format_time(t) + ": Unknown event “" + e + "”");
723 if (type === 'goal' || type === 'their_goal') {
724 formations_used_this_point.clear();
728 // Add field time for all players still left at match end.
729 const keep = keep_event(players, formations_used_this_point, last_pull_was_ours, filters);
731 for (const [q,p] of Object.entries(players)) {
732 if (p.on_field_since !== null && last_goal !== null) {
733 p.field_time_ms += last_goal - p.on_field_since;
736 if (game_started !== null && last_goal !== null) {
737 globals.field_time_ms += last_goal - game_started;
739 if (live_since !== null && last_goal !== null) {
740 globals.playing_time_ms += last_goal - live_since;
741 if (offense === true) {
742 globals.offensive_playing_time_ms += last_goal - live_since;
743 } else if (offense === false) {
744 globals.defensive_playing_time_ms += last_goal - live_since;
752 function recursively_expand_filterset(filterset, base, result)
754 if (result.length >= 100) {
757 if (base.length == filterset.length) {
761 let filter = filterset[base.length];
763 let elements = filter.elements;
764 if (elements.size === 0) {
765 elements = filter.choices;
767 for (const element of elements) {
770 'elements': new Set([ element ]),
771 'split': false, // Not used.
773 recursively_expand_filterset(filterset, [...base, split_filter], result);
776 recursively_expand_filterset(filterset, [...base, filter], result);
780 function expand_filtersets(filtersets) {
781 if (filtersets.length === 0) {
786 for (const filterset of filtersets) {
787 recursively_expand_filterset(filterset, [], expanded);
792 function process_matches(json, unexpanded_filtersets) {
793 let chosen_category = get_chosen_category();
794 write_main_menu(chosen_category);
796 let filtersets = expand_filtersets(Object.values(unexpanded_filtersets));
799 for (const filter of filtersets) {
800 let players = calc_stats(json, filter);
802 if (chosen_category === 'general') {
803 rows = make_table_general(players);
804 } else if (chosen_category === 'offense') {
805 rows = make_table_offense(players);
806 } else if (chosen_category === 'defense') {
807 rows = make_table_defense(players);
808 } else if (chosen_category === 'playing_time') {
809 rows = make_table_playing_time(players);
810 } else if (chosen_category === 'per_point') {
811 rows = make_table_per_point(players);
812 } else if (chosen_category === 'team_wide') {
813 rows = make_table_team_wide(players);
818 let merged_rows = [];
819 if (filtersets.length > 1) {
820 for (let i = 0; i < rowsets.length; ++i) {
821 let marker = make_filter_marker(filtersets[i]);
823 // Make filter header.
824 let tr = rowsets[i][0];
825 let th = document.createElement('th');
827 tr.insertBefore(th, tr.firstChild);
829 for (let j = 1; j < rowsets[i].length; ++j) {
830 let tr = rowsets[i][j];
832 // Remove the name for cleanness.
834 tr.firstChild.nextSibling.textContent = '';
838 tr.style.borderTop = '0px';
840 if (i != rowsets.length - 1) {
841 tr.style.borderBottom = '0px';
844 // Make filter marker.
845 let td = document.createElement('td');
846 td.textContent = marker;
847 td.classList.add('filtermarker');
848 tr.insertBefore(td, tr.firstChild);
852 for (let i = 0; i < rowsets[0].length; ++i) {
853 for (let j = 0; j < rowsets.length; ++j) {
854 merged_rows.push(rowsets[j][i]);
855 if (i === 0) break; // Don't merge the headings.
859 merged_rows = rowsets[0];
861 document.getElementById('stats').replaceChildren(...merged_rows);
864 function get_chosen_category() {
865 if (window.location.hash === '#offense') {
867 } else if (window.location.hash === '#defense') {
869 } else if (window.location.hash === '#playing_time') {
870 return 'playing_time';
871 } else if (window.location.hash === '#per_point') {
873 } else if (window.location.hash === '#team_wide') {
880 function write_main_menu(chosen_category) {
883 ['general', 'General'],
884 ['offense', 'Offense'],
885 ['defense', 'Defense'],
886 ['playing_time', 'Playing time'],
887 ['per_point', 'Per point'],
888 ['team_wide', 'Team-wide'],
890 for (const [id, title] of categories) {
891 if (chosen_category === id) {
892 let span = document.createElement('span');
893 span.innerText = title;
896 let a = document.createElement('a');
897 a.appendChild(document.createTextNode(title));
898 a.setAttribute('href', '#' + id);
903 document.getElementById('mainmenu').replaceChildren(...elems);
906 // https://en.wikipedia.org/wiki/1.96#History
909 const ci_width = 100;
910 const ci_height = 20;
912 function make_binomial_ci(val, num, z) {
915 // https://en.wikipedia.org/wiki/Binomial_proportion_confidence_interval#Wilson_score_interval
916 let low = (avg + z*z/(2*num) - z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
917 let high = (avg + z*z/(2*num) + z * Math.sqrt(avg * (1.0 - avg) / num + z*z/(4*num*num))) / (1 + z*z/num);
919 // Fix the signs so that we don't get -0.00.
920 low = Math.max(low, 0.0);
930 // These can only happen once per point, but you get -1 and +1
931 // instead of 0 and +1. After we rewrite to 0 and 1, it's a binomial,
932 // and then we can rewrite back.
933 function make_efficiency_ci(points_won, points_completed, z)
935 let ci = make_binomial_ci(points_won, points_completed, z);
936 ci.val = 2.0 * ci.val - 1.0;
937 ci.lower_ci = 2.0 * ci.lower_ci - 1.0;
938 ci.upper_ci = 2.0 * ci.upper_ci - 1.0;
941 ci.desired = 0.0; // Desired = positive efficiency.
945 // Ds, throwaways and drops can happen multiple times per point,
946 // so they are Poisson distributed.
948 // Modified Wald (recommended by http://www.ine.pt/revstat/pdf/rs120203.pdf
949 // since our rates are definitely below 2 per point).
951 // FIXME: z is ignored.
952 function make_poisson_ci(val, num, z, inverted)
954 let low = (val == 0) ? 0.0 : ((val - 0.5) - Math.sqrt(val - 0.5)) / num;
955 let high = (val == 0) ? -Math.log(0.025) / num : ((val + 0.5) + Math.sqrt(val + 0.5)) / num;
957 // Fix the signs so that we don't get -0.00.
958 low = Math.max(low, 0.0);
960 // The display range of 0 to 0.5 is fairly arbitrary. So is the desired 0.05 per point.
969 'inverted': inverted,
973 // Wilson and Hilferty, again recommended for general use in the PDF above
974 // (anything from their group “G1” works).
975 // https://en.wikipedia.org/wiki/Poisson_distribution#Confidence_interval
976 function make_poisson_ci_large(val, num, z)
978 let low = val * Math.pow(1.0 - 1.0 / (9.0 * val) - z / (3.0 * Math.sqrt(val)), 3.0) / num;
979 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;
981 // Fix the signs so that we don't get -0.00.
982 low = Math.max(low, 0.0);
984 // The display range of 0 to 25.0 is fairly arbitrary. We have no desire here
985 // (this is used for number of touches).
998 // We don't really know what to expect for possessions; it appears roughly
999 // lognormal, but my head doesn't work well enough to extract the CI for
1000 // the estimated sample mean, and now my head spins around whether we do
1001 // this correctly even for Poisson :-) But we do a simple (non-BCa) bootstrap
1002 // here, which should give us what we want.
1004 // FIXME: z is ignored.
1005 function make_ci_duration(vals, z)
1008 let sample_means = [];
1009 for (let i = 0; i < 300; ++i) {
1011 for (let j = 0; j < vals.length; ++j) {
1012 sum += vals[Math.floor(Math.random() * vals.length)];
1014 sample_means.push(sum / vals.length);
1016 sample_means.sort();
1018 // Interpolating here would probably be better, but OK.
1019 let low = sample_means[Math.floor(0.025 * sample_means.length)];
1020 let high = sample_means[Math.floor(0.975 * sample_means.length)];
1022 // Find the point estimate of the mean.
1024 for (const v of vals) {
1027 let avg = sum / vals.length;
1030 'val': avg / 1000.0,
1031 'lower_ci': low / 1000.0,
1032 'upper_ci': high / 1000.0,
1042 function make_table_general(players) {
1045 let header = document.createElement('tr');
1046 add_th(header, 'Player');
1047 add_th(header, '+/-');
1048 add_th(header, 'Soft +/-');
1049 add_th(header, 'O efficiency');
1050 add_th(header, 'D efficiency');
1051 add_th(header, 'Points played');
1055 for (const [q,p] of get_sorted_players(players)) {
1056 if (q === 'globals') continue;
1057 let row = document.createElement('tr');
1058 let pm = p.goals + p.assists + p.hockey_assists + p.defenses - p.throwaways - p.drops - p.was_ds - p.stallouts;
1059 let soft_pm = p.offensive_soft_plus + p.defensive_soft_plus - p.offensive_soft_minus - p.defensive_soft_minus;
1060 let o_efficiency = make_efficiency_ci(p.offensive_points_won, p.offensive_points_completed, z);
1061 let d_efficiency = make_efficiency_ci(p.defensive_points_won, p.defensive_points_completed, z);
1062 let name = add_3cell(row, p.name, 'name'); // TODO: number?
1063 add_3cell(row, pm > 0 ? ('+' + pm) : pm);
1064 add_3cell(row, soft_pm > 0 ? ('+' + soft_pm) : soft_pm);
1065 add_3cell_ci(row, o_efficiency);
1066 add_3cell_ci(row, d_efficiency);
1067 add_3cell(row, p.points_played);
1068 row.dataset.player = q;
1073 let globals = players['globals'];
1074 let o_efficiency = make_efficiency_ci(globals.offensive_points_won, globals.offensive_points_completed, z);
1075 let d_efficiency = make_efficiency_ci(globals.defensive_points_won, globals.defensive_points_completed, z);
1076 let row = document.createElement('tr');
1080 add_3cell_ci(row, o_efficiency);
1081 add_3cell_ci(row, d_efficiency);
1082 add_3cell(row, globals.points_played);
1088 function make_table_team_wide(players) {
1089 let globals = players['globals'];
1093 let header = document.createElement('tr');
1095 add_th(header, 'Our team', 6);
1096 add_th(header, 'Opponents', 6);
1102 let row = document.createElement('tr');
1103 let name = add_3cell(row, 'Turnovers generated', 'name');
1104 add_3cell(row, globals.turnovers_won);
1106 add_3cell(row, globals.turnovers_lost);
1113 let row = document.createElement('tr');
1114 let name = add_3cell(row, 'Clean holds', 'name');
1115 let our_clean_holds = make_binomial_ci(globals.clean_holds, globals.offensive_points_completed, z);
1116 let their_clean_holds = make_binomial_ci(globals.their_clean_holds, globals.defensive_points_completed, z);
1117 our_clean_holds.desired = 0.3; // Arbitrary.
1118 our_clean_holds.format = 'percentage';
1119 their_clean_holds.desired = 0.3;
1120 their_clean_holds.format = 'percentage';
1121 add_3cell(row, globals.clean_holds + ' / ' + globals.offensive_points_completed);
1122 add_3cell_ci(row, our_clean_holds);
1123 add_3cell(row, globals.their_clean_holds + ' / ' + globals.defensive_points_completed);
1124 add_3cell_ci(row, their_clean_holds);
1130 let row = document.createElement('tr');
1131 let name = add_3cell(row, 'Clean breaks', 'name');
1132 let our_clean_breaks = make_binomial_ci(globals.clean_breaks, globals.defensive_points_completed, z);
1133 let their_clean_breaks = make_binomial_ci(globals.their_clean_breaks, globals.offensive_points_completed, z);
1134 our_clean_breaks.desired = 0.3; // Arbitrary.
1135 our_clean_breaks.format = 'percentage';
1136 their_clean_breaks.desired = 0.3;
1137 their_clean_breaks.format = 'percentage';
1138 add_3cell(row, globals.clean_breaks + ' / ' + globals.defensive_points_completed);
1139 add_3cell_ci(row, our_clean_breaks);
1140 add_3cell(row, globals.their_clean_breaks + ' / ' + globals.offensive_points_completed);
1141 add_3cell_ci(row, their_clean_breaks);
1145 // Touches. We only have information for our team here.
1148 for (const [q,p] of get_sorted_players(players)) {
1149 if (q === 'globals') continue;
1152 let row = document.createElement('tr');
1153 let name = add_3cell(row, 'Touches per possession (all)', 'name');
1154 let touches = globals.touches_for_turnover + globals.touches_for_goal;
1155 let possessions = goals + globals.turnovers_lost;
1157 add_3cell_ci(row, make_poisson_ci_large(touches, possessions, z));
1162 row = document.createElement('tr');
1163 add_3cell(row, 'Touches per possession (goals)', 'name');
1165 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_goal, goals, z));
1170 row = document.createElement('tr');
1171 add_3cell(row, 'Touches per possession (turnovers)', 'name');
1173 add_3cell_ci(row, make_poisson_ci_large(globals.touches_for_turnover, globals.turnovers_lost, z));
1179 // Time. Here we have (roughly) for both.
1181 let row = document.createElement('tr');
1182 let name = add_3cell(row, 'Time per possession (all)', 'name');
1183 let time = globals.time_for_turnover.concat(globals.time_for_goal);
1184 let their_time = globals.their_time_for_turnover.concat(globals.their_time_for_goal);
1186 add_3cell_ci(row, make_ci_duration(time, z));
1188 add_3cell_ci(row, make_ci_duration(their_time, z));
1191 row = document.createElement('tr');
1192 add_3cell(row, 'Time per possession (goals)', 'name');
1194 add_3cell_ci(row, make_ci_duration(globals.time_for_goal, z));
1196 add_3cell_ci(row, make_ci_duration(globals.their_time_for_goal, z));
1199 row = document.createElement('tr');
1200 add_3cell(row, 'Time per possession (turnovers)', 'name');
1202 add_3cell_ci(row, make_ci_duration(globals.time_for_turnover, z));
1204 add_3cell_ci(row, make_ci_duration(globals.their_time_for_turnover, z));
1211 function make_table_offense(players) {
1214 let header = document.createElement('tr');
1215 add_th(header, 'Player');
1216 add_th(header, 'Goals');
1217 add_th(header, 'Assists');
1218 add_th(header, 'Hockey assists');
1219 add_th(header, 'Throws');
1220 add_th(header, 'Throwaways');
1221 add_th(header, '%OK');
1222 add_th(header, 'Catches');
1223 add_th(header, 'Drops');
1224 add_th(header, 'D-ed');
1225 add_th(header, '%OK');
1226 add_th(header, 'Stalls');
1227 add_th(header, 'Soft +/-', 6);
1238 for (const [q,p] of get_sorted_players(players)) {
1239 if (q === 'globals') continue;
1240 let throw_ok = make_binomial_ci(p.num_throws - p.throwaways, p.num_throws, z);
1241 let catch_ok = make_binomial_ci(p.catches, p.catches + p.drops + p.was_ds, z);
1243 throw_ok.format = 'percentage';
1244 catch_ok.format = 'percentage';
1246 // Desire at least 90% percentage. Fairly arbitrary.
1247 throw_ok.desired = 0.9;
1248 catch_ok.desired = 0.9;
1250 let row = document.createElement('tr');
1251 add_3cell(row, p.name, 'name'); // TODO: number?
1252 add_3cell(row, p.goals);
1253 add_3cell(row, p.assists);
1254 add_3cell(row, p.hockey_assists);
1255 add_3cell(row, p.num_throws);
1256 add_3cell(row, p.throwaways);
1257 add_3cell_ci(row, throw_ok);
1258 add_3cell(row, p.catches);
1259 add_3cell(row, p.drops);
1260 add_3cell(row, p.was_ds);
1261 add_3cell_ci(row, catch_ok);
1262 add_3cell(row, p.stallouts);
1263 add_3cell(row, '+' + p.offensive_soft_plus);
1264 add_3cell(row, '-' + p.offensive_soft_minus);
1265 row.dataset.player = q;
1269 num_throws += p.num_throws;
1270 throwaways += p.throwaways;
1271 catches += p.catches;
1274 stallouts += p.stallouts;
1278 let throw_ok = make_binomial_ci(num_throws - throwaways, num_throws, z);
1279 let catch_ok = make_binomial_ci(catches, catches + drops + was_ds, z);
1280 throw_ok.format = 'percentage';
1281 catch_ok.format = 'percentage';
1282 throw_ok.desired = 0.9;
1283 catch_ok.desired = 0.9;
1285 let row = document.createElement('tr');
1287 add_3cell(row, goals);
1290 add_3cell(row, num_throws);
1291 add_3cell(row, throwaways);
1292 add_3cell_ci(row, throw_ok);
1293 add_3cell(row, catches);
1294 add_3cell(row, drops);
1295 add_3cell(row, was_ds);
1296 add_3cell_ci(row, catch_ok);
1297 add_3cell(row, stallouts);
1305 function make_table_defense(players) {
1308 let header = document.createElement('tr');
1309 add_th(header, 'Player');
1310 add_th(header, 'Ds');
1311 add_th(header, 'Pulls');
1312 add_th(header, 'OOB pulls');
1313 add_th(header, 'OOB%');
1314 add_th(header, 'Avg. hang time (IB)');
1315 add_th(header, 'Callahans');
1316 add_th(header, 'Soft +/-', 6);
1323 let sum_sum_time = 0;
1326 for (const [q,p] of get_sorted_players(players)) {
1327 if (q === 'globals') continue;
1329 for (const t of p.pull_times) {
1332 let avg_time = 1e-3 * sum_time / (p.pulls - p.oob_pulls);
1333 let oob_pct = 100 * p.oob_pulls / p.pulls;
1335 let ci_oob = make_binomial_ci(p.oob_pulls, p.pulls, z);
1336 ci_oob.format = 'percentage';
1337 ci_oob.desired = 0.2; // Arbitrary.
1338 ci_oob.inverted = true;
1340 let row = document.createElement('tr');
1341 add_3cell(row, p.name, 'name'); // TODO: number?
1342 add_3cell(row, p.defenses);
1343 add_3cell(row, p.pulls);
1344 add_3cell(row, p.oob_pulls);
1345 add_3cell_ci(row, ci_oob);
1346 if (p.pulls > p.oob_pulls) {
1347 add_3cell(row, avg_time.toFixed(1) + ' sec');
1349 add_3cell(row, 'N/A');
1351 add_3cell(row, p.callahans);
1352 add_3cell(row, '+' + p.defensive_soft_plus);
1353 add_3cell(row, '-' + p.defensive_soft_minus);
1354 row.dataset.player = q;
1357 defenses += p.defenses;
1359 oob_pulls += p.oob_pulls;
1360 sum_sum_time += sum_time;
1361 callahans += p.callahans;
1365 let ci_oob = make_binomial_ci(oob_pulls, pulls, z);
1366 ci_oob.format = 'percentage';
1367 ci_oob.desired = 0.2; // Arbitrary.
1368 ci_oob.inverted = true;
1370 let avg_time = 1e-3 * sum_sum_time / (pulls - oob_pulls);
1371 let oob_pct = 100 * oob_pulls / pulls;
1373 let row = document.createElement('tr');
1375 add_3cell(row, defenses);
1376 add_3cell(row, pulls);
1377 add_3cell(row, oob_pulls);
1378 add_3cell_ci(row, ci_oob);
1379 if (pulls > oob_pulls) {
1380 add_3cell(row, avg_time.toFixed(1) + ' sec');
1382 add_3cell(row, 'N/A');
1384 add_3cell(row, callahans);
1392 function make_table_playing_time(players) {
1395 let header = document.createElement('tr');
1396 add_th(header, 'Player');
1397 add_th(header, 'Points played');
1398 add_th(header, 'Time played');
1399 add_th(header, 'O time');
1400 add_th(header, 'D time');
1401 add_th(header, 'Time on field');
1402 add_th(header, 'O points');
1403 add_th(header, 'D points');
1407 for (const [q,p] of get_sorted_players(players)) {
1408 if (q === 'globals') continue;
1409 let row = document.createElement('tr');
1410 add_3cell(row, p.name, 'name'); // TODO: number?
1411 add_3cell(row, p.points_played);
1412 add_3cell(row, Math.floor(p.playing_time_ms / 60000) + ' min');
1413 add_3cell(row, Math.floor(p.offensive_playing_time_ms / 60000) + ' min');
1414 add_3cell(row, Math.floor(p.defensive_playing_time_ms / 60000) + ' min');
1415 add_3cell(row, Math.floor(p.field_time_ms / 60000) + ' min');
1416 add_3cell(row, p.offensive_points_completed);
1417 add_3cell(row, p.defensive_points_completed);
1418 row.dataset.player = q;
1423 let globals = players['globals'];
1424 let row = document.createElement('tr');
1426 add_3cell(row, globals.points_played);
1427 add_3cell(row, Math.floor(globals.playing_time_ms / 60000) + ' min');
1428 add_3cell(row, Math.floor(globals.offensive_playing_time_ms / 60000) + ' min');
1429 add_3cell(row, Math.floor(globals.defensive_playing_time_ms / 60000) + ' min');
1430 add_3cell(row, Math.floor(globals.field_time_ms / 60000) + ' min');
1431 add_3cell(row, globals.offensive_points_completed);
1432 add_3cell(row, globals.defensive_points_completed);
1438 function make_table_per_point(players) {
1441 let header = document.createElement('tr');
1442 add_th(header, 'Player');
1443 add_th(header, 'Goals');
1444 add_th(header, 'Assists');
1445 add_th(header, 'Hockey assists');
1446 add_th(header, 'Ds');
1447 add_th(header, 'Throwaways');
1448 add_th(header, 'Recv. errors');
1449 add_th(header, 'Touches');
1455 let hockey_assists = 0;
1458 let receiver_errors = 0;
1460 for (const [q,p] of get_sorted_players(players)) {
1461 if (q === 'globals') continue;
1463 // Can only happen once per point, so these are binomials.
1464 let ci_goals = make_binomial_ci(p.goals, p.points_played, z);
1465 let ci_assists = make_binomial_ci(p.assists, p.points_played, z);
1466 let ci_hockey_assists = make_binomial_ci(p.hockey_assists, p.points_played, z);
1467 // Arbitrarily desire at least 10% (not everybody can score or assist).
1468 ci_goals.desired = 0.1;
1469 ci_assists.desired = 0.1;
1470 ci_hockey_assists.desired = 0.1;
1472 let row = document.createElement('tr');
1473 add_3cell(row, p.name, 'name'); // TODO: number?
1474 add_3cell_ci(row, ci_goals);
1475 add_3cell_ci(row, ci_assists);
1476 add_3cell_ci(row, ci_hockey_assists);
1477 add_3cell_ci(row, make_poisson_ci(p.defenses, p.points_played, z));
1478 add_3cell_ci(row, make_poisson_ci(p.throwaways, p.points_played, z, true));
1479 add_3cell_ci(row, make_poisson_ci(p.drops + p.was_ds, p.points_played, z, true));
1480 if (p.points_played > 0) {
1481 add_3cell(row, p.touches == 0 ? 0 : (p.touches / p.points_played).toFixed(2));
1483 add_3cell(row, 'N/A');
1485 row.dataset.player = q;
1489 assists += p.assists;
1490 hockey_assists += p.hockey_assists;
1491 defenses += p.defenses;
1492 throwaways += p.throwaways;
1493 receiver_errors += p.drops + p.was_ds;
1494 touches += p.touches;
1498 let globals = players['globals'];
1499 let row = document.createElement('tr');
1501 if (globals.points_played > 0) {
1502 let ci_goals = make_binomial_ci(goals, globals.points_played, z);
1503 let ci_assists = make_binomial_ci(assists, globals.points_played, z);
1504 let ci_hockey_assists = make_binomial_ci(hockey_assists, globals.points_played, z);
1505 ci_goals.desired = 0.5;
1506 ci_assists.desired = 0.5;
1507 ci_hockey_assists.desired = 0.5;
1509 add_3cell_ci(row, ci_goals);
1510 add_3cell_ci(row, ci_assists);
1511 add_3cell_ci(row, ci_hockey_assists);
1513 add_3cell_ci(row, make_poisson_ci(defenses, globals.points_played, z));
1514 add_3cell_ci(row, make_poisson_ci(throwaways, globals.points_played, z, true));
1515 add_3cell_ci(row, make_poisson_ci(receiver_errors, globals.points_played, z, true));
1517 add_3cell(row, touches == 0 ? 0 : (touches / globals.points_played).toFixed(2));
1519 add_3cell_with_filler_ci(row, 'N/A');
1520 add_3cell_with_filler_ci(row, 'N/A');
1521 add_3cell_with_filler_ci(row, 'N/A');
1522 add_3cell_with_filler_ci(row, 'N/A');
1523 add_3cell_with_filler_ci(row, 'N/A');
1524 add_3cell_with_filler_ci(row, 'N/A');
1525 add_3cell(row, 'N/A');
1532 function open_filter_menu(click_to_add_div) {
1533 document.getElementById('filter-submenu').style.display = 'none';
1534 let filter_div = click_to_add_div.parentElement;
1535 let filter_id = filter_div.dataset.filterId;
1537 let menu = document.getElementById('filter-add-menu');
1538 menu.parentElement.removeChild(menu);
1539 filter_div.appendChild(menu);
1540 menu.style.display = 'block';
1541 menu.replaceChildren();
1543 // Place the menu directly under the “click to add” label;
1544 // we don't anchor it since that label will move around
1545 // and the menu shouldn't.
1546 let rect = click_to_add_div.getBoundingClientRect();
1547 menu.style.left = rect.left + 'px';
1548 menu.style.top = (rect.bottom + 10) + 'px';
1550 let filterset = global_filters[filter_id];
1551 if (filterset === undefined) {
1552 global_filters[filter_id] = filterset = [];
1555 add_menu_item(filter_div, filterset, menu, 0, 'match', 'Match (any)');
1556 add_menu_item(filter_div, filterset, menu, 1, 'player_any', 'Player on field (any)');
1557 add_menu_item(filter_div, filterset, menu, 2, 'player_all', 'Player on field (all)');
1558 add_menu_item(filter_div, filterset, menu, 3, 'formation_offense', 'Offense played (any)');
1559 add_menu_item(filter_div, filterset, menu, 4, 'formation_defense', 'Defense played (any)');
1560 add_menu_item(filter_div, filterset, menu, 5, 'starting_on', 'Starting on');
1561 add_menu_item(filter_div, filterset, menu, 6, 'gender_ratio', 'Gender ratio');
1564 function add_menu_item(filter_div, filterset, menu, menu_idx, filter_type, title) {
1565 let item = document.createElement('div');
1566 item.classList.add('option');
1567 item.appendChild(document.createTextNode(title));
1569 let arrow = document.createElement('div');
1570 arrow.classList.add('arrow');
1571 arrow.textContent = '▸';
1572 item.appendChild(arrow);
1574 menu.appendChild(item);
1576 item.addEventListener('click', (e) => { show_submenu(filter_div, filterset, menu_idx, null, filter_type); });
1579 function find_all_ratios(json)
1583 for (const player of json['players']) {
1584 players[player['player_id']] = {
1585 'gender': player['gender'],
1586 'last_point_seen': null,
1589 for (const match of json['matches']) {
1590 for (const [q,p] of Object.entries(players)) {
1591 p.on_field_since = null;
1593 for (const e of match['events']) {
1594 let p = players[e['player']];
1595 let type = e['type'];
1596 if (type === 'in') {
1597 p.on_field_since = 1;
1598 } else if (type === 'out') {
1599 p.on_field_since = null;
1600 } else if (type === 'pull' || type == 'their_pull') { // We assume no cross-gender subs for now.
1601 let code = find_gender_ratio_code(players);
1602 if (ratios[code] === undefined) {
1603 ratios[code] = code;
1604 if (code !== '4 F, 3 M' && code !== '4 M, 3 F' && code !== '3 M, 2 F' && code !== '3 F, 2 M') {
1605 console.log('Unexpected gender ratio ' + code + ' first seen at: ' +
1606 match['description'] + ', ' + format_time(e['t']));
1615 function show_submenu(filter_div, filterset, menu_idx, pill, filter_type) {
1616 let submenu = document.getElementById('filter-submenu');
1618 // Move to the same place as the top-level menu.
1619 submenu.parentElement.removeChild(submenu);
1620 document.getElementById('filter-add-menu').parentElement.appendChild(submenu);
1623 const filter = find_filter(filterset, filter_type);
1626 if (filter_type === 'match') {
1627 for (const match of global_json['matches']) {
1629 'title': match['description'],
1630 'id': match['match_id']
1633 } else if (filter_type === 'player_any' || filter_type === 'player_all') {
1634 for (const player of global_json['players']) {
1636 'title': player['name'],
1637 'id': player['player_id']
1640 } else if (filter_type === 'formation_offense') {
1642 'title': '(None/unknown)',
1645 for (const formation of global_json['formations']) {
1646 if (formation['offense']) {
1648 'title': formation['name'],
1649 'id': formation['formation_id']
1653 } else if (filter_type === 'formation_defense') {
1655 'title': '(None/unknown)',
1658 for (const formation of global_json['formations']) {
1659 if (!formation['offense']) {
1661 'title': formation['name'],
1662 'id': formation['formation_id']
1666 } else if (filter_type === 'starting_on') {
1669 'id': false, // last_pull_was_ours
1673 'id': true, // last_pull_was_ours
1675 } else if (filter_type === 'gender_ratio') {
1676 for (const [title, id] of Object.entries(find_all_ratios(global_json)).sort()) {
1684 let choice_set = new Set();
1685 for (const choice of choices) {
1686 choice_set.add(choice.id);
1689 for (const choice of choices) {
1690 let label = document.createElement('label');
1692 let subitem = document.createElement('div');
1693 subitem.classList.add('option');
1695 let check = document.createElement('input');
1696 check.setAttribute('type', 'checkbox');
1697 check.setAttribute('id', 'choice' + choice.id);
1698 if (filter !== null && filter.elements.has(choice.id)) {
1699 check.setAttribute('checked', 'checked');
1701 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, choice.id, choice_set); });
1703 subitem.appendChild(check);
1704 subitem.appendChild(document.createTextNode(choice.title));
1706 label.appendChild(subitem);
1707 subitems.push(label);
1710 // If meaningful (it's not for player_all, since all data for that would be
1711 // the same anyway), show the split checkbox.
1712 if (choices.length > 1 && filter_type !== 'player_all') {
1713 let label = document.createElement('label');
1715 let subitem = document.createElement('div');
1716 subitem.classList.add('option');
1718 let check = document.createElement('input');
1719 check.setAttribute('type', 'checkbox');
1720 check.setAttribute('id', 'choice_split');
1721 if (filter !== null && filter.split) {
1722 check.setAttribute('checked', 'checked');
1724 check.addEventListener('change', (e) => { checkbox_changed(filter_div, filterset, e, filter_type, 'split', choice_set); });
1726 subitem.appendChild(check);
1727 let text_span = document.createElement('span'); // So that we can style its disabling later.
1728 text_span.appendChild(document.createTextNode('Split'));
1729 subitem.appendChild(text_span);
1730 subitem.style.borderTop = '1px solid #ddd';
1732 label.appendChild(subitem);
1733 subitems.push(label);
1736 submenu.replaceChildren(...subitems);
1737 submenu.style.display = 'block';
1739 if (pill !== null) {
1740 let rect = pill.getBoundingClientRect();
1741 submenu.style.top = (rect.bottom + 10) + 'px';
1742 submenu.style.left = rect.left + 'px';
1744 // Position just outside the selected menu.
1745 let rect = document.getElementById('filter-add-menu').getBoundingClientRect();
1746 submenu.style.top = (rect.top + menu_idx * 35) + 'px';
1747 submenu.style.left = (rect.right - 1) + 'px';
1751 // Find the right filter, if it exists.
1752 function find_filter(filterset, filter_type) {
1753 for (let f of filterset) {
1754 if (f.type === filter_type) {
1761 // Equivalent to Array.prototype.filter, but in-place.
1762 function inplace_filter(arr, cond) {
1764 for (let i = 0; i < arr.length; ++i) {
1772 function add_new_filterset() {
1773 let template = document.querySelector('.filter'); // First one is fine.
1774 let div = template.cloneNode(true);
1775 let add_menu = div.querySelector('#filter-add-menu');
1776 if (add_menu !== null) {
1777 div.removeChild(add_menu);
1779 let submenu = div.querySelector('#filter-submenu');
1780 if (submenu !== null) {
1781 div.removeChild(submenu);
1783 div.querySelector('.filters').replaceChildren();
1784 div.dataset.filterId = next_filterset_id++;
1785 template.parentElement.appendChild(div);
1788 function try_gc_filter_menus(cheap) {
1791 for (const filter_div of document.querySelectorAll('.filter')) {
1792 let id = filter_div.dataset.filterId;
1793 divs.push(filter_div);
1794 empties.push(global_filters[id] === undefined || global_filters[id].length === 0);
1796 let last_div = divs[empties.length - 1];
1798 // See if we have two empty filter lists at the bottom of the list;
1799 // if so, we can remove one without it looking funny in the UI.
1800 // If not, we'll have to wait until closing the menu.
1801 // (The menu is positioned at the second-last one, so we can
1802 // remove the last one without issue.)
1803 if (empties.length >= 2 && empties[empties.length - 2] && empties[empties.length - 1]) {
1804 delete global_filters[last_div.dataset.filterId];
1805 last_div.parentElement.removeChild(last_div);
1808 // This is a different situation from try_cheap_gc(), where we should
1809 // remove the one _not_ last. We might need to move the menu to the last one,
1810 // though, so it doesn't get lost.
1811 for (let i = 0; i < empties.length - 1; ++i) {
1816 delete global_filters[div.dataset.filterId];
1817 let add_menu = div.querySelector('#filter-add-menu');
1818 if (add_menu !== null) {
1819 div.removeChild(add_menu);
1820 last_div.appendChild(add_menu);
1822 let submenu = div.querySelector('#filter-submenu');
1823 if (submenu !== null) {
1824 div.removeChild(submenu);
1825 last_div.appendChild(submenu);
1827 div.parentElement.removeChild(div);
1832 function checkbox_changed(filter_div, filterset, e, filter_type, id, choices) {
1833 let filter = find_filter(filterset, filter_type);
1834 let pills_div = filter_div.querySelector('.filters');
1835 if (e.target.checked) {
1836 // See if we must create a new empty filterset (since this went from
1837 // empty to non-empty).
1838 if (filterset.length === 0) {
1839 add_new_filterset();
1842 // See if we must add a new filter to the list.
1843 if (filter === null) {
1845 'type': filter_type,
1846 'elements': new Set(),
1850 if (id === 'split') {
1851 filter.split = true;
1853 filter.elements.add(id);
1855 filter.pill = make_filter_pill(filter_div, filterset, filter);
1856 filterset.push(filter);
1857 pills_div.appendChild(filter.pill);
1859 if (id === 'split') {
1860 filter.split = true;
1862 filter.elements.add(id);
1864 let new_pill = make_filter_pill(filter_div, filterset, filter);
1865 pills_div.replaceChild(new_pill, filter.pill);
1866 filter.pill = new_pill;
1869 if (id === 'split') {
1870 filter.split = false;
1872 filter.elements.delete(id);
1874 if (filter.elements.size === 0) {
1875 pills_div.removeChild(filter.pill);
1876 inplace_filter(filterset, f => f !== filter);
1878 if (filterset.length == 0) {
1879 try_gc_filter_menus(true);
1882 let new_pill = make_filter_pill(filter_div, filterset, filter);
1883 pills_div.replaceChild(new_pill, filter.pill);
1884 filter.pill = new_pill;
1887 let choice_split = document.getElementById('choice_split');
1888 if (filter.elements.size === 1) {
1889 choice_split.nextSibling.style.opacity = 0.2;
1890 choice_split.setAttribute('disabled', 'disabled');
1892 choice_split.nextSibling.style.opacity = 1.0;
1893 choice_split.removeAttribute('disabled');
1896 process_matches(global_json, global_filters);
1899 function make_filter_pill(filter_div, filterset, filter) {
1900 let pill = document.createElement('div');
1901 pill.classList.add('filter-pill');
1903 if (filter.type === 'match') {
1907 for (const match_id of filter.elements) {
1908 all_names.push(find_match(match_id)['description']);
1910 let common_prefix = find_common_prefix_of_all(all_names);
1911 if (common_prefix !== null) {
1912 text += common_prefix + '(';
1916 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
1917 for (const match_id of sorted_match_id) {
1921 let desc = find_match(match_id)['description'];
1922 if (common_prefix === null) {
1925 text += desc.substr(common_prefix.length);
1930 if (common_prefix !== null) {
1933 } else if (filter.type === 'player_any') {
1934 text = 'Player (any): ';
1935 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1937 for (const player_id of sorted_players) {
1941 text += find_player(player_id)['name'];
1944 } else if (filter.type === 'player_all') {
1946 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
1948 for (const player_id of sorted_players) {
1952 text += find_player(player_id)['name'];
1955 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
1956 const offense = (filter.type === 'formation_offense');
1964 for (const formation_id of filter.elements) {
1965 all_names.push(find_formation(formation_id)['name']);
1967 let common_prefix = find_common_prefix_of_all(all_names);
1968 if (common_prefix !== null) {
1969 text += common_prefix + '(';
1973 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
1974 for (const formation_id of sorted_formation_id) {
1978 let desc = find_formation(formation_id)['name'];
1979 if (common_prefix === null) {
1982 text += desc.substr(common_prefix.length);
1987 if (common_prefix !== null) {
1990 } else if (filter.type === 'starting_on') {
1991 text = 'Starting on: ';
1993 if (filter.elements.has(false) && filter.elements.has(true)) {
1995 } else if (filter.elements.has(false)) {
2000 } else if (filter.type === 'gender_ratio') {
2004 for (const name of Array.from(filter.elements).sort()) {
2008 text += name; // FIXME
2012 if (filter.split && filter.elements.size !== 1) {
2016 let text_node = document.createElement('span');
2017 text_node.innerText = text;
2018 text_node.addEventListener('click', (e) => show_submenu(filter_div, filterset, null, pill, filter.type));
2019 pill.appendChild(text_node);
2021 pill.appendChild(document.createTextNode(' '));
2023 let delete_node = document.createElement('span');
2024 delete_node.innerText = '✖';
2025 delete_node.addEventListener('click', (e) => {
2026 // Delete this filter entirely.
2027 pill.parentElement.removeChild(pill);
2028 inplace_filter(filterset, f => f !== filter);
2029 if (filterset.length == 0) {
2030 try_gc_filter_menus(false);
2032 process_matches(global_json, global_filters);
2034 let add_menu = document.getElementById('filter-add-menu');
2035 let add_submenu = document.getElementById('filter-submenu');
2036 add_menu.style.display = 'none';
2037 add_submenu.style.display = 'none';
2039 pill.appendChild(delete_node);
2040 pill.style.cursor = 'pointer';
2045 function entire_gender(players) {
2047 for (const player_id of players) {
2048 if (gender === null) {
2049 gender = find_player(player_id).gender;
2050 } else if (gender !== find_player(player_id).gender) {
2051 return false; // Not all are of the same gender.
2054 for (const player of global_json['players']) {
2055 if (player.gender === gender && !players.has(player.player_id)) {
2056 return false; // Not all of this gender are in the group.
2062 function make_filter_marker(filterset) {
2064 for (const filter of filterset) {
2068 if (filter.type === 'match') {
2070 for (const match of global_json['matches']) {
2071 all_names.push(match['description']);
2073 let common_prefix = find_common_prefix_of_all(all_names);
2075 let sorted_match_id = Array.from(filter.elements).sort((a, b) => a - b);
2076 for (const match_id of sorted_match_id) {
2077 let desc = find_match(match_id)['description'];
2078 if (common_prefix === null) {
2079 text += desc.substr(0, 3);
2081 text += desc.substr(common_prefix.length, 3);
2084 } else if (filter.type === 'player_any' || filter.type === 'player_all') {
2085 let sorted_players = Array.from(filter.elements).sort((a, b) => player_pos(a) - player_pos(b));
2086 if (filter.elements.size >= 3 && entire_gender(filter.elements)) {
2087 text += find_player(sorted_players[0]).gender;
2089 for (const player_id of sorted_players) {
2090 text += find_player(player_id)['name'].substr(0, 3);
2093 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2094 let sorted_formation_id = Array.from(filter.elements).sort((a, b) => a - b);
2095 for (const formation_id of sorted_formation_id) {
2096 text += find_formation(formation_id)['name'].substr(0, 3);
2098 } else if (filter.type === 'starting_on') {
2099 if (filter.elements.has(false) && filter.elements.has(true)) {
2101 } else if (filter.elements.has(false)) {
2106 } else if (filter.type === 'gender_ratio') {
2108 for (const name of Array.from(filter.elements).sort()) {
2112 text += name.replaceAll(' ', '').substr(0, 2); // 4 F, 3M -> 4 F.
2120 function find_common_prefix(a, b) {
2122 for (let i = 0; i < Math.min(a.length, b.length); ++i) {
2123 if (a[i] === b[i]) {
2132 function find_common_prefix_of_all(values) {
2133 if (values.length < 2) {
2136 let common_prefix = null;
2137 for (const desc of values) {
2138 if (common_prefix === null) {
2139 common_prefix = desc;
2141 common_prefix = find_common_prefix(common_prefix, desc);
2144 if (common_prefix.length >= 3) {
2145 return common_prefix;
2151 function find_match(match_id) {
2152 for (const match of global_json['matches']) {
2153 if (match['match_id'] === match_id) {
2160 function find_formation(formation_id) {
2161 for (const formation of global_json['formations']) {
2162 if (formation['formation_id'] === formation_id) {
2169 function find_player(player_id) {
2170 for (const player of global_json['players']) {
2171 if (player['player_id'] === player_id) {
2178 function player_pos(player_id) {
2180 for (const player of global_json['players']) {
2181 if (player['player_id'] === player_id) {
2189 function keep_match(match_id, filters) {
2190 for (const filter of filters) {
2191 if (filter.type === 'match') {
2192 return filter.elements.has(match_id);
2198 // Returns a map of e.g. F => 4, M => 3.
2199 function find_gender_ratio(players) {
2201 for (const [q,p] of Object.entries(players)) {
2202 if (p.on_field_since === null) {
2205 let gender = p.gender;
2206 if (gender === '' || gender === undefined || gender === null) {
2209 if (map[gender] === undefined) {
2218 function find_gender_ratio_code(players) {
2219 let map = find_gender_ratio(players);
2220 let all_genders = Array.from(Object.keys(map)).sort(
2222 if (map[a] !== map[b]) {
2223 return map[b] - map[a]; // Reverse numeric.
2233 for (const g of all_genders) {
2244 // null if none (e.g., if playing 3–3).
2245 function find_predominant_gender(players) {
2247 let predominant_gender = null;
2248 for (const [gender, num] of Object.entries(find_gender_ratio(players))) {
2251 predominant_gender = gender;
2252 } else if (num == max) {
2253 predominant_gender = null; // At least two have the same.
2256 return predominant_gender;
2259 function find_num_players_on_field(players) {
2261 for (const [q,p] of Object.entries(players)) {
2262 if (p.on_field_since !== null) {
2269 function filter_passes(players, formations_used_this_point, last_pull_was_ours, filter) {
2270 if (filter.type === 'player_any') {
2271 for (const p of Array.from(filter.elements)) {
2272 if (players[p].on_field_since !== null) {
2277 } else if (filter.type === 'player_all') {
2278 for (const p of Array.from(filter.elements)) {
2279 if (players[p].on_field_since === null) {
2284 } else if (filter.type === 'formation_offense' || filter.type === 'formation_defense') {
2285 for (const f of Array.from(filter.elements)) {
2286 if (formations_used_this_point.has(f)) {
2291 } else if (filter.type === 'starting_on') {
2292 return filter.elements.has(last_pull_was_ours);
2293 } else if (filter.type === 'gender_ratio') {
2294 return filter.elements.has(find_gender_ratio_code(players));
2299 function keep_event(players, formations_used_this_point, last_pull_was_ours, filters) {
2300 for (const filter of filters) {
2301 if (!filter_passes(players, formations_used_this_point, last_pull_was_ours, filter)) {
2308 // Heuristic: If we go at least ten seconds without the possession changing
2309 // or the operator specifying some other formation, we probably play the
2310 // same formation as the last point.
2311 function should_reuse_last_formation(events, t) {
2312 for (const e of events) {
2316 if (e.t > t + 10000) {
2319 const type = e.type;
2320 if (type === 'their_goal' || type === 'goal' ||
2321 type === 'set_defense' || type === 'set_offense' ||
2322 type === 'throwaway' || type === 'their_throwaway' ||
2323 type === 'drop' || type === 'was_d' || type === 'stallout' || type === 'defense' || type === 'interception' ||
2324 type === 'pull' || type === 'pull_landed' || type === 'pull_oob' || type === 'their_pull' ||
2325 type === 'formation_offense' || type === 'formation_defense') {
2332 function possibly_close_menu(e) {
2333 if (e.target.closest('.filter-click-to-add') === null &&
2334 e.target.closest('#filter-add-menu') === null &&
2335 e.target.closest('#filter-submenu') === null &&
2336 e.target.closest('.filter-pill') === null) {
2337 let add_menu = document.getElementById('filter-add-menu');
2338 let add_submenu = document.getElementById('filter-submenu');
2339 add_menu.style.display = 'none';
2340 add_submenu.style.display = 'none';
2341 try_gc_filter_menus(false);
2345 let global_sort = {};
2347 function sort_by(th) {
2348 let tr = th.parentElement;
2350 for (let column_idx = 0; column_idx < tr.children.length; ++column_idx) {
2351 let element = tr.children[column_idx];
2352 if (element === th) {
2353 ++child_idx; // Pad.
2356 if (element.hasAttribute('colspan')) {
2357 child_idx += parseInt(element.getAttribute('colspan'));
2364 let table = tr.parentElement;
2365 for (let row_idx = 1; row_idx < table.children.length - 1; ++row_idx) { // Skip header and globals.
2366 let row = table.children[row_idx];
2367 let player = parseInt(row.dataset.player);
2368 let value = row.children[child_idx].textContent;
2369 global_sort[player] = value;
2373 function get_sorted_players(players)
2375 let p = Object.entries(players);
2376 if (global_sort.length !== 0) {
2378 let ai = parseFloat(global_sort[a[0]]);
2379 let bi = parseFloat(global_sort[b[0]]);
2380 if (ai == ai && bi == bi) {
2381 return bi - ai; // Reverse numeric.
2382 } else if (global_sort[a[0]] < global_sort[b[0]]) {
2384 } else if (global_sort[a[0]] > global_sort[b[0]]) {