All files / src/utils festCard.js

98.57% Statements 208/211
93.54% Branches 116/124
100% Functions 15/15
98.57% Lines 208/211

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 2371x 1x 1x 1x 1x 1x 1x 1x       1x 1x 48x 48x   1x 1x 21x 21x 21x 21x 18x 21x 3x 21x 2x 21x 2x 21x 11x 21x 21x   1x   1x 1x 1x 1x 1x 1x 130x 130x 130x 130x 130x   130x 130x 130x 130x   130x 130x 130x 130x 130x 130x 130x   130x 130x 130x 130x 130x 130x 130x 130x 130x 130x   1x   1x 52x 52x 52x 52x 52x 52x 50x 10x 2x 50x 52x 52x   41x 41x 41x 41x 41x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 30x   30x 52x 52x 9x 9x 9x 9x 9x 9x 9x 9x 52x   24x 41x 41x 1x 1x 1x 1x 1x 41x   24x 38x 38x 3x 3x 3x 3x 3x 3x 3x 2x 3x 3x 3x 38x   17x 17x   1x 1x 46x 46x 46x 8x 8x 38x 38x   1x 1x 47x 47x 25x 25x   1x 1x 48x 48x 26x 48x 48x   1x 1x 1x 1x 1x 1x 1x 45x 45x 45x   45x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x 23x   45x 45x 21x 21x 21x 21x 21x 21x 21x 21x 21x 1x 1x   1x 1x 44x 44x 44x 44x   1x 1x 1x 1x 1x 116x 116x 68x        
/**
 * Pure helpers for the Fest Story share card (SB-1883).
 *
 * The card reads the matchup endpoint (`/api/matches/{id}/matchup`), whose
 * two sides each carry a dossier (conferences, form) and national badges.
 * Most teams have little of that, so every helper here returns null or []
 * for absent data — never 0, which would claim a measurement nobody made.
 */
 
import { venueTimeZone } from './tournamentDays';
 
/** True for an MLS NEXT Fest match — the only matches the card is offered for. */
export function isFestTournament(match) {
  return /mls next fest/i.test(String(match?.tournament_name ?? ''));
}
 
/** 1st 2nd 3rd 4th … 11th 12th 13th … 21st. */
export function ordinal(n) {
  const v = Number(n);
  if (!Number.isFinite(v)) return '';
  const mod100 = Math.abs(v) % 100;
  if (mod100 >= 11 && mod100 <= 13) return `${v}th`;
  switch (Math.abs(v) % 10) {
    case 1:
      return `${v}st`;
    case 2:
      return `${v}nd`;
    case 3:
      return `${v}rd`;
    default:
      return `${v}th`;
  }
}
 
const isNum = v => typeof v === 'number' && Number.isFinite(v);
 
/**
 * One side of the matchup reduced to what the card shows. The league
 * conference only: Flex tables are a different competition and would not
 * agree with the record printed beside them.
 */
export function sideStats(side) {
  const dossier = side && !side.error ? side.dossier : null;
  const usable = dossier && !dossier.error ? dossier : null;
  const conf =
    (usable?.conferences || []).find(c => c?.kind === 'league') || null;
  const hasResults = !!conf && !conf.no_results;
 
  const recordParts = hasResults
    ? [conf.wins, conf.draws, conf.losses]
    : [null, null, null];
  const record = recordParts.every(isNum) ? recordParts.join('-') : null;
 
  // Form arrives newest first; the card reads left to right, oldest to
  // newest, so the most recent result sits on the right.
  const last5 = (usable?.form || [])
    .map(f => f?.result)
    .filter(r => r === 'W' || r === 'D' || r === 'L')
    .slice(0, 5)
    .reverse();
 
  return {
    conference: conf?.division?.name || null,
    league: conf?.league || conf?.division?.league || null,
    position: hasResults && isNum(conf.position) ? conf.position : null,
    tableSize: hasResults && isNum(conf.table_size) ? conf.table_size : null,
    record,
    goals: hasResults && isNum(conf.gf) ? conf.gf : null,
    last5,
  };
}
 
const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
 
/** Length of the unbeaten run from the newest result backwards. */
function unbeatenRun(side) {
  const form =
    (side?.dossier && !side.dossier.error && side.dossier.form) || [];
  let wins = 0;
  let draws = 0;
  for (const f of form) {
    if (f?.result === 'W') wins += 1;
    else if (f?.result === 'D') draws += 1;
    else break;
  }
  return { length: wins + draws, wins, draws };
}
 
function bestBadge(side) {
  const badges = (side?.badges || []).filter(
    b => isNum(b?.rank) && b.rank <= 10 && b?.title
  );
  if (!badges.length) return null;
  return badges.reduce((a, b) => (b.rank < a.rank ? b : a));
}
 
/**
 * At most one banner for the whole card, by priority across both teams —
 * home wins a tie at the same level:
 *   1. unbeaten in the last 4+ results
 *   2. a top-10 national stat board
 *   3. top three of their conference table
 * Never the Power Rating. Null when nothing qualifies.
 *
 * @param names { home, away } team names for the eyebrow.
 */
export function headline(homeSide, awaySide, names = {}) {
  const sides = [
    { side: homeSide, name: names.home || '' },
    { side: awaySide, name: names.away || '' },
  ];
 
  for (const { side, name } of sides) {
    const run = unbeatenRun(side);
    if (run.length >= 4) {
      const parts = [];
      if (run.wins) parts.push(plural(run.wins, 'win', 'wins'));
      if (run.draws) parts.push(plural(run.draws, 'draw', 'draws'));
      return {
        eyebrow: `${name} · On form`,
        text: `Unbeaten in last ${run.length} — ${parts.join(', ')}`,
      };
    }
  }
 
  for (const { side, name } of sides) {
    const badge = bestBadge(side);
    if (badge) {
      return {
        eyebrow: `${name} · #${badge.rank} nationally`,
        text: badge.title,
      };
    }
  }
 
  for (const { side, name } of sides) {
    const s = sideStats(side);
    if (s.position && s.position <= 3 && s.conference) {
      const ord = ordinal(s.position);
      return {
        eyebrow: `${name} · ${ord} in ${s.conference}`,
        text:
          s.position === 1
            ? `Top of the ${s.conference} table`
            : s.tableSize
              ? `${ord} of ${s.tableSize} in ${s.conference}`
              : `${ord} in ${s.conference}`,
      };
    }
  }
 
  return null;
}
 
/** "MLS NEXT Homegrown Matchup" when both teams share a league, else Fest. */
export function matchupLabel(homeStats, awayStats) {
  const a = homeStats?.league;
  const b = awayStats?.league;
  if (a && a === b && (a === 'Homegrown' || a === 'Academy')) {
    return `MLS NEXT ${a} Matchup`;
  }
  return 'MLS NEXT Fest Matchup';
}
 
/** "Arizona Athletic Grounds - Field 20" → "Arizona Athletic Grounds · Field 20". */
export function fieldLabel(location) {
  const s = String(location ?? '').trim();
  if (!s) return null;
  return s.replace(/\s+-\s+/g, ' · ');
}
 
/** "Showcase · Group 17" → "Showcase G17"; anything else as given. */
export function groupLabel(tournamentGroup) {
  const s = String(tournamentGroup ?? '').trim();
  if (!s) return null;
  const m = s.match(/^(.+?)\s*·\s*Group\s+(\S+)$/i);
  return m ? `${m[1]} G${m[2]}` : s;
}
 
/**
 * Kickoff in the venue's own time zone: { day: 'THU', date: 'DEC 10',
 * time: '8:00PM' }. A Fest match in Mesa is at 8pm in Mesa, whoever is
 * looking — falls back to viewer local only when the venue is unknown.
 * Without a kickoff, the day and date come from match_date and time is null.
 */
export function festKickoff(match) {
  const zone = venueTimeZone({ location: match?.tournament_location });
  const iso = match?.scheduled_kickoff;
  const d = iso ? new Date(iso) : null;
 
  if (d && !Number.isNaN(d.getTime())) {
    const opts = zone ? { timeZone: zone } : {};
    const part = o =>
      d.toLocaleString('en-US', { ...o, ...opts }).toUpperCase();
    return {
      day: part({ weekday: 'short' }),
      date: part({ month: 'short', day: 'numeric' }),
      time: part({ hour: 'numeric', minute: '2-digit', hour12: true }).replace(
        /\s+/g,
        ''
      ),
    };
  }
 
  const key = match?.match_date;
  if (key && /^\d{4}-\d{2}-\d{2}/.test(key)) {
    const local = new Date(`${key.slice(0, 10)}T12:00:00`);
    return {
      day: local.toLocaleString('en-US', { weekday: 'short' }).toUpperCase(),
      date: local
        .toLocaleString('en-US', { month: 'short', day: 'numeric' })
        .toUpperCase(),
      time: null,
    };
  }
  return { day: null, date: null, time: null };
}
 
/** "Showcase G17 · Arizona Athletic Grounds · Field 20": group, then field. */
export function festVenueLine(match) {
  return [groupLabel(match?.tournament_group), fieldLabel(match?.location)]
    .filter(Boolean)
    .join(' · ');
}
 
/**
 * Team-name font size on a Fest card: long names shrink rather than
 * overflow (the card's CSS clamps them to two lines).
 */
export function festNameSize(name, base) {
  const len = String(name || '').length;
  if (len <= 10) return `${base}px`;
  if (len <= 16) return `${Math.round(base * 0.8)}px`;
  if (len <= 24) return `${Math.round(base * 0.66)}px`;
  return `${Math.round(base * 0.55)}px`;
}