All files / src/utils tournamentStages.js

100% Statements 376/376
89.88% Branches 151/168
100% Functions 21/21
100% Lines 376/376

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 4071x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 3035x 3035x 3035x 3035x 3035x 3035x   1x 1140x 1140x 1140x 1140x 1140x 898x 1140x 1140x 1140x 1140x   1x 1x   1x 638x 624x 638x 638x   1x 96x 96x 96x   1x 397x 397x 397x 397x 397x 397x 397x 397x 397x   1x 1x 109x 109x 107x 109x 105x 109x 5x 5x 5x 5x 5x 107x 107x   1x 1039x 1039x 1039x 1039x 1554x 1039x 1x   1x 1x 1170x 1170x 1143x 1039x 1039x 1039x 1039x 1143x 1170x 1140x 1140x 1148x 492x 19x 19x 18x 18x 18x 18x 18x 18x 18x 18x 19x 474x 474x 648x 648x 648x 1122x 550x 549x 550x 13x 550x 540x 540x 9x 9x 1122x 98x 98x 87x 87x 87x 96x 96x 96x 96x 96x 1110x 86x 1107x 86x 86x   1x 1x 1x 1x 1x 1172x 2x 2x 2x 2x 2x 2x 2x 1170x 1172x 27x 27x 27x 27x 27x 1172x 1172x   1x 867x 867x 867x 1x 1x 1x 1x   1x 1x 1x 1x 1x 70x 70x 70x 70x 70x 70x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 168x 1091x 1091x 1033x 1033x 1033x 925x 30x 30x 30x 30x 30x 30x 30x 58x 1091x 58x 58x 58x 58x 168x 168x 168x 168x 168x 30x 30x 58x 58x 58x 58x 30x 30x 30x 30x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 30x 30x 32x 32x 32x 32x 40x 40x 40x 40x 32x 3x 32x 32x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 35x 32x 24x 168x 168x   1x 1x 1x 1x 1x 1x 1x   1x   1x 1x 1x 1x 1x 1x 1x 52x 52x 52x 29x 29x   1x 1x 1x 1x 1x 1x 491x 491x 3088x 3088x 3088x 544x 544x 491x 491x 7x 6x 491x 491x 47x 47x 47x 491x 491x  
// Stage sections of the tournament match list (SB-1749).
//
// MLS NEXT Fest has rounds that are neither a group stage nor an elimination
// tree: showcase, placement finals and consolation. Each renders as its own
// section rather than falling into the catch-all "Matches" bucket.
//
// For these rounds `tournament_group` carries a stage label rather than a
// group ("HD · Showcase", "HD · Group Play", "GA Cup Qualifier"), and one
// round can hold several of them, so a section is one (round, stage label)
// pair and is titled with the label.
//
// SB-1873, SB-1875: a match is in the stage its group's competition names
// ("GA Cup Qualifier · Group A" on the group stage and "GA Cup Qualifier
// Bracket A" on the round of 16 are both `ga_cup_qualifier`), else in its
// round's stage — the stage the Stage chips filter on. The API sends
// it on every match (`stage_key`, `stage_label`, `stage_group`,
// `stage_competition`); `matchStage` reads those and, for a row without them,
// works them out with `match_stage_of` in backend/dao/tournament_filters.py —
// change one and change the other.
 
import {
  GROUP_SEPARATOR,
  GROUP_WHITESPACE,
  splitGroup,
} from './tournamentGroups';
import {
  KNOCKOUT_ROUNDS,
  ROUND_LABELS_LONG,
  ROUND_LABELS_SHORT,
} from './tournamentRounds';
 
export const GROUP_STAGE_ROUND = 'group_stage';
 
// Every round key in playing order, as ROUND_SEQUENCE in tournament_filters.py.
export const ROUND_SEQUENCE = [
  'group_stage',
  'crossover',
  'round_of_32',
  'round_of_16',
  'quarterfinal',
  'semifinal',
  'final',
  'third_place',
  'wildcard',
  'silver_semifinal',
  'bronze_semifinal',
  'silver_final',
  'bronze_final',
  'showcase',
  'consolation',
  'placement_final',
];
const ROUND_KEYS = new Set(ROUND_SEQUENCE);
const DIVISION_TOKENS = new Set(['HD', 'AD']);
const COMPETITION_MERGES = new Set(['showcase']);
const COMPETITION_SUFFIX = '_groups';
const STAGE_KEY_PATTERN = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
const STAGE_KEY_MAX_LENGTH = 40;
const LOWER_WORDS = new Set(['of']);
// The same patterns and words as tournament_filters.py.
const SUB_TOKEN =
  /^(?:(.*[^ ]) +)?((?:Group|Bracket) +(?:[A-Za-z]|[0-9]{1,3}))$/;
const POOL_LABEL = /^(?:[A-Z]|[0-9]{1,3}|[A-Z][0-9]{1,2})$/;
const EVENT_SEPARATOR = ' - ';
// After "HD · " / "AD · " off the group stage, a remainder starting with one
// of these is a legacy side label or a side's bracket (SB-1749), in the
// round's own stage; any other first word is a competition of that side.
export const LEGACY_SIDE_WORDS = new Set(['Showcase', 'Group', 'Bracket']);
 
const isSpace = ch => GROUP_WHITESPACE.includes(ch);
const trimSpace = text => {
  let start = 0;
  let end = text.length;
  while (start < end && isSpace(text[start])) start += 1;
  while (end > start && isSpace(text[end - 1])) end -= 1;
  return text.slice(start, end);
};
 
/** `{ head, rest }` around the first separator, or null (`_namespace`). */
function namespaceOf(group) {
  let lead = 0;
  while (lead < group.length && isSpace(group[lead])) lead += 1;
  const at = group.indexOf(GROUP_SEPARATOR, lead);
  if (at < 0) return null;
  return {
    head: trimSpace(group.slice(lead, at)) || null,
    rest: trimSpace(group.slice(at + GROUP_SEPARATOR.length)) || null,
  };
}
 
const isDivision = head =>
  head != null && DIVISION_TOKENS.has(head.toUpperCase());
 
const bracketOnly = text => {
  if (POOL_LABEL.test(text)) return true;
  const token = SUB_TOKEN.exec(text);
  return token != null && !token[1];
};
 
const stripSub = text => {
  const token = SUB_TOKEN.exec(text);
  return token && token[1] ? [token[1], token[2]] : [text, null];
};
 
const slugOf = name => {
  if (!name) return null;
  const slug = name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '_')
    .replace(/^_+|_+$/g, '')
    .slice(0, STAGE_KEY_MAX_LENGTH)
    .replace(/_+$/, '');
  return STAGE_KEY_PATTERN.test(slug) ? slug : null;
};
 
/** A competition name as a stage key, or null (`competition_stage_key`). */
export function competitionStageKey(name) {
  let slug = slugOf(name);
  if (slug == null) return null;
  if (
    slug === 'none' ||
    (ROUND_KEYS.has(slug) && !COMPETITION_MERGES.has(slug))
  ) {
    slug =
      slug
        .slice(0, STAGE_KEY_MAX_LENGTH - COMPETITION_SUFFIX.length)
        .replace(/_+$/, '') + COMPETITION_SUFFIX;
  }
  return slug;
}
 
const humanize = key =>
  key
    .split('_')
    .filter(Boolean)
    .map((w, i) =>
      i && LOWER_WORDS.has(w) ? w : w.slice(0, 1).toUpperCase() + w.slice(1)
    )
    .join(' ');
 
/** `match_stage_of`: `{ key, label, group, competition }`, or null with no round. */
export function stageOf(round, group) {
  // A blank round (empty or whitespace only) is no round, as `_blank`.
  if (round == null || !String(round).trim()) return null;
  const own = (sub = null) => ({
    key: round,
    label: humanize(round),
    group: sub,
    competition: false,
  });
  if (group == null || !trimSpace(String(group))) return own();
  const text = String(group);
  const ns = namespaceOf(text);
  if (round === GROUP_STAGE_ROUND) {
    if (ns && ns.head && !isDivision(ns.head)) {
      const key = competitionStageKey(ns.head);
      if (key != null) {
        // A blank label ("Showcase · ") is still offered, by its key.
        return {
          key,
          label: ns.head,
          group: ns.rest ?? text,
          competition: true,
        };
      }
    }
    return own(splitGroup(text).label);
  }
  let name;
  let base;
  let sub;
  if (ns) {
    if (!isDivision(ns.head) || !ns.rest) return own(ns.rest ? text : null);
    if (
      LEGACY_SIDE_WORDS.has(ns.rest.split(' ')[0]) ||
      POOL_LABEL.test(ns.rest)
    ) {
      return own(bracketOnly(ns.rest) ? text : null);
    }
    [base, sub] = stripSub(ns.rest);
    name = `${ns.head} ${base}`;
  } else {
    const trimmed = trimSpace(text);
    if (bracketOnly(trimmed)) return own(trimmed);
    [base, sub] = stripSub(trimmed);
    name = base;
  }
  const ownSlugs = [
    slugOf(name),
    slugOf(base),
    slugOf(name.split(EVENT_SEPARATOR).pop()),
  ];
  if (ownSlugs.includes(round)) return own(sub);
  const key = competitionStageKey(name);
  if (key == null) return own(sub);
  return { key, label: name, group: sub, competition: true };
}
 
/**
 * `{ key, label, group, competition }` of the stage a match is in, as the
 * Stage chips name it; all null for a match with no round.
 */
export function matchStage(match) {
  if (match?.stage_key !== undefined) {
    return {
      key: match.stage_key ?? null,
      label: match.stage_label ?? null,
      group: match.stage_group ?? null,
      competition: match.stage_competition ?? false,
    };
  }
  return (
    stageOf(match?.tournament_round, match?.tournament_group) ?? {
      key: null,
      label: null,
      group: null,
      competition: null,
    }
  );
}
 
export const roundRank = round => {
  const i = ROUND_SEQUENCE.indexOf(round);
  return i === -1 ? ROUND_SEQUENCE.length : i;
};
const roundName = round => ROUND_LABELS_LONG[round] ?? humanize(round ?? '');
const roundShort = round => ROUND_LABELS_SHORT[round] ?? roundName(round);
const natural = (a, b) =>
  String(a).localeCompare(String(b), undefined, { numeric: true });
 
/**
 * "GA Cup Qualifier — Round of 16 · Bracket A"; the stage alone when the
 * round is its name or is not worth saying (`roundLabel` null).
 */
export function competitionSectionTitle(stageLabel, roundLabel, sub = null) {
  const head =
    !roundLabel || stageLabel.toLowerCase() === roundLabel.toLowerCase()
      ? stageLabel
      : `${stageLabel} — ${roundLabel}`;
  return sub ? `${head} · ${sub}` : head;
}
 
/**
 * The list's sections for competition stages (SB-1875), and the matches left
 * for the round sections: a match named by its group (`competition`) is in
 * its stage's sections, any other is left to the round sections. The
 * Showcase, merged with its round (SB-1873), is one section with group chips
 * beside its legacy rows' own sections. Any other stage's sections are by
 * round in playing order — the group
 * stage as one section with group chips, any other round one section per
 * bracket ("GA Cup Qualifier — Round of 16 · Bracket A"). A stage that
 * plays one round, not a knockout, does not name it: "Pro Player Pathway",
 * "GA Cup Showcase · Bracket A", "Showcase". Stages are in the
 * order of the earliest round they play (`rank`, a ROUND_SEQUENCE index),
 * then by label. `shortTitle` is the phone heading, with the short round
 * label, when it differs.
 */
export function competitionSections(matches) {
  const all = (matches || []).map(m => ({ m, st: matchStage(m) }));
  const stages = new Map();
  // The Showcase, merged with its round: once any of its matches is a
  // re-sent group, its legacy round rows ("Fest - Showcase", "HD · Showcase")
  // join that one section, as before SB-1875; until then they keep their own
  // per-label sections.
  const merged = new Set(
    all
      .filter(({ st }) => st.competition && COMPETITION_MERGES.has(st.key))
      .map(({ st }) => st.key)
  );
  const rest = [];
  for (const { m, st } of all) {
    // A match in its round's own stage is left to the round sections.
    if (!st.key || !(st.competition || merged.has(st.key))) {
      rest.push(m);
      continue;
    }
    if (!stages.has(st.key)) {
      stages.set(st.key, {
        key: st.key,
        label: null,
        rows: [],
        first: Infinity,
      });
    }
    const stage = stages.get(st.key);
    if (st.competition && stage.label == null) stage.label = st.label;
    stage.rows.push(m);
    // The earliest round it plays, worked out once.
    stage.first = Math.min(stage.first, roundRank(m.tournament_round));
  }
  const first = s => s.first;
  const sections = [];
  for (const stage of [...stages.values()].sort(
    (a, b) => first(a) - first(b) || natural(a.label, b.label)
  )) {
    const byRound = new Map();
    for (const m of stage.rows) {
      const round = m.tournament_round;
      if (!byRound.has(round)) byRound.set(round, []);
      byRound.get(round).push(m);
    }
    const rounds = [...byRound.keys()].sort(
      (a, b) => roundRank(a) - roundRank(b) || natural(a, b)
    );
    if (COMPETITION_MERGES.has(stage.key)) {
      // One section with group chips, legacy rows and re-sent groups alike,
      // so the list reads as one Showcase block during and after a re-send.
      sections.push({
        key: `stage:${stage.key}`,
        stage: stage.key,
        rank: first(stage),
        title: stage.label,
        shortTitle: null,
        matches: stage.rows,
        showRoundChip: false,
        showGroupChip: true,
      });
      continue;
    }
    const oneRound = rounds.length === 1 && !KNOCKOUT_ROUNDS.has(rounds[0]);
    for (const round of rounds) {
      const rows = byRound.get(round);
      const groupStage = round === GROUP_STAGE_ROUND;
      const bySub = new Map();
      for (const m of rows) {
        const sub = groupStage ? null : matchStage(m).group;
        if (!bySub.has(sub)) bySub.set(sub, []);
        bySub.get(sub).push(m);
      }
      const subs = [...bySub.keys()].sort((a, b) =>
        a == null ? -1 : b == null ? 1 : natural(a, b)
      );
      for (const sub of subs) {
        const title = competitionSectionTitle(
          stage.label,
          oneRound ? null : roundName(round),
          sub
        );
        const short = competitionSectionTitle(
          stage.label,
          oneRound ? null : roundShort(round),
          sub
        );
        sections.push({
          key: `stage:${stage.key}:${round}:${sub ?? ''}`,
          stage: stage.key,
          rank: first(stage),
          title,
          shortTitle: short !== title ? short : null,
          matches: bySub.get(sub),
          showRoundChip: false,
          showGroupChip: groupStage,
        });
      }
    }
  }
  return { sections, rest };
}
 
// In playing order within a list. `title` is the section heading when the
// matches carry no stage label.
export const STAGE_ROUND_SECTIONS = [
  { round: 'showcase', title: 'Showcase' },
  { round: 'placement_final', title: 'Placement Finals' },
  { round: 'consolation', title: 'Consolation' },
];
 
export const STAGE_ROUNDS = new Set(STAGE_ROUND_SECTIONS.map(s => s.round));
 
/**
 * Heading for one stage section. A label that already names the round stands
 * alone ("HD · Showcase"); otherwise the round leads so two rounds sharing a
 * label stay distinguishable ("Placement Finals — HD · Group Play" vs
 * "Consolation — HD · Group Play").
 */
export function stageSectionTitle(roundTitle, stageLabel) {
  const label = (stageLabel ?? '').trim();
  if (!label) return roundTitle;
  if (label.toLowerCase().includes(roundTitle.toLowerCase())) return label;
  return `${roundTitle} — ${label}`;
}
 
/**
 * Split matches of one stage round into sections, one per stage label, in
 * label order with unlabelled matches last. Returns [] when the round has no
 * matches. Match order within a section is the order given.
 */
export function buildStageSections(matches, { round, title }) {
  const byLabel = new Map();
  for (const m of matches || []) {
    if (m.tournament_round !== round) continue;
    const label = (m.tournament_group ?? '').trim();
    if (!byLabel.has(label)) byLabel.set(label, []);
    byLabel.get(label).push(m);
  }
  return [...byLabel.keys()]
    .sort((a, b) => {
      if (!a || !b) return a ? -1 : b ? 1 : 0;
      return a.localeCompare(b);
    })
    .map(label => ({
      key: `${round}:${label}`,
      title: stageSectionTitle(title, label),
      matches: byLabel.get(label),
    }));
}