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 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 | 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 355x 355x 1x 1x 1x 1x 1x 1x 112x 112x 112x 73x 112x 112x 1x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 44x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 130x 201x 201x 201x 201x 264x 264x 261x 261x 264x 16x 16x 264x 248x 57x 57x 57x 57x 57x 57x 57x 57x 248x 248x 13x 13x 248x 248x 248x 264x 264x 264x 201x 201x 201x 201x 286x 286x 286x 286x 286x 286x 286x 286x 23x 23x 23x 201x 201x 201x 201x 285x 285x 285x 285x 262x 285x 3x 3x 6x 6x 6x 6x 3x 3x 285x 28x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 285x 201x 201x 201x 201x 201x 201x 68x 68x 68x 68x 68x 68x 14x 201x 201x 201x 201x 201x 201x 15x 15x 15x 15x 15x 15x 15x 201x 201x 201x 14x 12x 12x 14x 14x 14x 14x 201x 201x 201x 201x 201x 15x 15x 22x 12x 12x 201x 201x 4x 4x 201x 201x 29x 201x 201x 201x 201x 201x 137x 137x 137x 1x 1x 1x 137x 137x 6x 137x 1x 1x 1x 137x 137x 6x 6x 6x 6x 137x 2x 2x 2x 137x 137x 5x 137x 1x 1x 1x 137x 1x 1x 1x 137x 201x 201x 235x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 203x 203x 203x 203x 203x 203x 203x 201x 201x 203x 203x 203x 203x 203x 203x 203x 81x 81x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 79x 122x 166x 122x 122x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 203x 3x 3x 3x 3x 3x 3x 3x 122x 122x 122x 122x 122x 166x 121x 121x 203x 203x 203x 203x 203x 203x 203x 203x 203x 201x 201x 201x 201x 4x 3x 3x 3x 3x 3x 3x 201x 201x 201x 226x 226x 226x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 201x 201x 201x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 104x 1x 1x 1x 104x 104x 104x 201x 201x 201x 201x 201x 201x 201x 201x 201x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 42x 201x 201x 201x 201x 201x 201x 7x 6x 6x 6x 1x 7x 201x 201x 201x 201x 15x 15x 15x 15x 201x 201x 9x 7x 7x 7x 7x 7x 201x 201x 201x 201x 39x 39x 39x 39x 38x 39x 1x 1x 38x 38x 38x 201x 201x 201x 201x 5x 5x 5x 201x 201x 7x 7x 7x 7x 7x 7x 201x 201x 201x 201x 10x 10x 10x 10x 10x 10x 201x 201x 201x 201x 201x 201x 201x 201x 11x 11x 11x 3x 3x 3x 3x 9x 3x 3x 3x 3x 3x 9x 3x 3x 3x 3x 3x 3x 3x 11x 201x 201x 12x 12x 12x 12x 12x 12x 12x 12x 201x 201x 201x 9x 9x 9x 9x 9x 9x 9x 201x 201x 201x 201x 11x 11x 7x 201x 201x 201x 201x 201x 201x 201x 201x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 201x 201x 201x 201x 201x 201x 1x 1x 1x 1x 1x 201x 201x 201x 2x 2x 1x 1x 2x 2x 2x 2x 201x 201x 201x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 201x 201x 201x 201x 201x 201x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 5x 5x 5x 7x 7x 7x 7x 7x 5x 201x 201x 13x 13x 11x 11x 11x 11x 11x 13x 8x 13x 13x 13x 13x 13x 13x 2x 1x 1x 13x 11x 11x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 30x 30x 27x 27x 27x 29x 29x 29x 27x 30x 5x 5x 5x 5x 22x 22x 22x 22x 28x 24x 24x 24x 24x 24x 24x 21x 21x 21x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x 201x | /**
* Tournament matches composable (SB-1749).
*
* Owns how the Tournaments page gets a tournament's matches, and the one
* decision behind it — the scale switch:
*
* - **Small** (up to LARGE_TOURNAMENT_MATCH_THRESHOLD matches): one call to
* `GET /api/tournaments/{id}`, every match in the response. Unchanged.
* - **Large** (more than that — MLS NEXT Fest is ~2,400): one response cannot
* hold it, so matches are paged and filtered server-side. An age group is
* always selected and a page is never more than TOURNAMENT_PAGE_SIZE rows.
*
* Backend endpoints (large mode):
* GET /api/tournaments/{id}/matches?age_group_id=&group=&round=&on_date=
* &conference_id=&league=&stage=&team_id=&limit=&offset=
* → { matches, total, limit, offset }
* GET /api/tournaments/{id}/filters?age_group_id=&on_date=
* → { facets_available, age_groups: [{ id, name, matches, matches_on_date }],
* groups: [{ key, division, label, stage, round, matches }] | null,
* days: [{ date, count }], conferences: [{ id, name, league,
* team_count }], unplaced: { count, total } | null, today,
* leagues: [{ league, match_count, team_count }],
* stages: [{ key, label, count }], unstaged_count }
*
* Day and conference (SB-1865): a large tournament is read one day at a time
* once the server lists its days, and can be narrowed to one conference. An
* API without `days` / `conferences` leaves both off — the list is then the
* whole age group, exactly as before.
*
* League, stage and team (SB-1870): a league (Homegrown / Academy) and a
* stage narrow the day's list like a conference does, and are offered only
* when the server lists them. A team, picked from the search, replaces the
* view with that team's whole schedule — every day, its age group — until it
* is cleared, which puts the view it replaced back.
*
* The filters are decoration on the list: when that request fails, or the
* server cannot count (`matches: null`, `groups: null`), the list still loads
* and the controls show no numbers — unknown is not zero.
*
* Not a singleton: each caller gets its own state.
*/
import { ref, computed } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
import { localDateKey } from '../utils/tournamentStatus';
import {
dateKeyInZone,
findGroupOption,
isDateKey,
offeredGroupsFor,
pickDefaultDay,
venueTimeZone,
} from '../utils/tournamentDays';
// The scale switch. A tournament with more matches than this is "large".
export const LARGE_TOURNAMENT_MATCH_THRESHOLD = 300;
// Rows per request in large mode. The API caps a page at 500. Must equal the
// API's default page size (DEFAULT_LIMIT in backend/dao/tournament_filters.py):
// only pages of that size, at a multiple of it, are cached by the server.
export const TOURNAMENT_PAGE_SIZE = 200;
// The API treats `group` and `round` as independent, so a Group filter is
// sent with the round its option counted. Since SB-1875 each option says its
// `round` (a bracket's is a knockout round; null when its matches span
// several, and then no round is sent). An option without `round` — an older
// API, which listed group-stage groups only — is sent with this one.
export const GROUP_FILTER_ROUND = 'group_stage';
/** True when the tournament's exact `match_count` puts it past the switch. */
export function isLargeTournament(tournament) {
return Number(tournament?.match_count) > LARGE_TOURNAMENT_MATCH_THRESHOLD;
}
/**
* The age group a large tournament opens on: the first one playing today,
* else the first with any matches, else the first listed. `matches: null`
* (not counted) is not "no matches", so it does not rule an age group out.
*/
export function pickDefaultAgeGroupId(ageGroups) {
const list = ageGroups || [];
const today = list.find(ag => ag.matches_on_date > 0);
if (today) return today.id;
const withMatches = list.find(ag => ag.matches == null || ag.matches > 0);
return (withMatches ?? list[0])?.id ?? null;
}
export function useTournamentMatches() {
const authStore = useAuthStore();
// The tournament with its loaded matches: the whole list in small mode, the
// pages loaded so far in large mode. Null until the first load.
const tournament = ref(null);
const isLarge = ref(false);
// ── large mode only ──
const ageGroups = ref([]);
// null = unknown (do not offer the control); [] = this age has no groups.
const groups = ref(null);
const selectedAgeGroupId = ref(null);
const selectedGroup = ref(null);
// The stage of the Group option picked (SB-1875): one stored group can be
// an option of two stages, each with its own round. Null when the group
// came from a link or a reconcile, and the selected stage decides.
const selectedGroupStage = ref(null);
// [{ date, count }] ascending; null = the API does not list days, so the
// list is not narrowed to one.
const days = ref(null);
// [{ id, name, league, team_count }]; null = unknown (no control).
const conferences = ref(null);
// { count, total } of teams with no known conference; null = not known,
// which is never shown as 0.
const unplaced = ref(null);
// The server's venue day (`today` on the filters response); null until it
// says. The server knows one venue, so a tournament whose own zone is known
// uses that zone's date instead — see `today` below.
const serverToday = ref(null);
// The open tournament's venue zone, read off its summary.
const zone = ref(null);
// Today where the tournament is played: its own zone's date, else the
// server's, else the browser's.
const today = () =>
dateKeyInZone(zone.value) ?? serverToday.value ?? localDateKey();
const venueToday = computed(() =>
zone.value || serverToday.value ? today() : null
);
const selectedDay = ref(null);
const selectedConferenceId = ref(null);
// [{ league, match_count, team_count }]; null = the API does not offer the
// league toggle.
const leagues = ref(null);
// [{ key, label, count }]; null = no stage control. `unstagedCount`: how
// many matches have no stage yet — null when not known, never shown as 0.
const stages = ref(null);
const unstagedCount = ref(null);
const selectedLeague = ref(null);
const selectedStage = ref(null);
// The team whose schedule is open (a row from /teams), or null. While set,
// the list is that team's and ignores the day and the other filters.
const selectedTeam = ref(null);
const teamMode = computed(() => selectedTeam.value != null);
// The view a team replaced, put back when the team is cleared; null when
// the page was opened on a team (there is nothing to go back to).
let viewBeforeTeam = null;
// Teams picked this visit, so back / forward to one still knows its name.
const knownTeams = new Map();
// Exact number of matches the current filters select; null until known.
const total = ref(null);
const pageLoading = ref(false);
const loadingMore = ref(false);
const pageError = ref(null);
// Bumped on every tournament load and every filter change, so an answer
// that arrives for something the visitor has already left is dropped.
let loadSeq = 0;
let pageSeq = 0;
// Filters answers have their own sequence: a page reload (a conference or
// group change) must not throw away facets that are still for the same
// age group and day.
let filtersSeq = 0;
// Loads that have not settled, and the tournament the latest one asked for.
// While either disagrees with what is on screen, `tournament` is not the
// tournament the visitor selected and must not be refreshed.
let loadsInFlight = 0;
let wantedId = null;
const get = url => authStore.apiRequest(url, { method: 'GET' });
const loadedCount = computed(() => tournament.value?.matches?.length ?? 0);
const hasMore = computed(
() =>
isLarge.value && total.value != null && loadedCount.value < total.value
);
// `allAges`: a team whose ages are not known yet is asked for in every age
// first, so its own ages can be read off its matches.
const fetchPage = (id, offset, { allAges = false } = {}) => {
const params = new URLSearchParams();
if (selectedAgeGroupId.value != null && !allAges) {
params.set('age_group_id', selectedAgeGroupId.value);
}
if (selectedTeam.value) {
// A team's whole tournament: no day, no other narrowing.
params.set('team_id', selectedTeam.value.team_id);
} else {
if (selectedGroup.value != null) {
// A group is offered only under its own stage; a stage it is not in
// clears it (setStage), so the two never contradict. It goes with
// its round (SB-1875: a bracket's is a knockout round), so the list
// is what the option counted.
params.set('group', selectedGroup.value);
const round = groupRound(selectedGroup.value);
if (round) params.set('round', round);
}
if (selectedDay.value) params.set('on_date', selectedDay.value);
if (selectedConferenceId.value != null) {
params.set('conference_id', selectedConferenceId.value);
}
if (selectedLeague.value) params.set('league', selectedLeague.value);
if (selectedStage.value) params.set('stage', selectedStage.value);
}
params.set('limit', TOURNAMENT_PAGE_SIZE);
params.set('offset', offset);
return get(`${getApiBaseUrl()}/api/tournaments/${id}/matches?${params}`);
};
// Never throws: a failed filters request resolves to null. `onDate` is the
// day the age groups' `matches_on_date` counts; today when none is open.
const fetchFilters = async (id, ageGroupId, onDate = null) => {
const params = new URLSearchParams();
if (ageGroupId != null) params.set('age_group_id', ageGroupId);
params.set('on_date', onDate || today());
try {
return await get(
`${getApiBaseUrl()}/api/tournaments/${id}/filters?${params}`
);
} catch (err) {
console.error('Error fetching tournament filters:', err);
return null;
}
};
// `keepGroups`: an answer without groups (failed, or not counted) leaves
// the groups already known in place instead of making them unknown.
const applyFilters = (
data,
{ fallbackAgeGroups = null, keepGroups = false } = {}
) => {
if (Array.isArray(data?.age_groups) && data.age_groups.length > 0) {
ageGroups.value = data.age_groups;
} else if (fallbackAgeGroups) {
// No counts: `matches` stays null, never 0.
ageGroups.value = fallbackAgeGroups.map(ag => ({
id: ag.id,
name: ag.name,
matches: null,
matches_on_date: null,
}));
}
if (Array.isArray(data?.groups)) groups.value = data.groups;
else if (!keepGroups) groups.value = null;
// A failed request (no answer) leaves the day and conference facets as
// they were; an answer without them means the API does not offer them.
if (data == null && keepGroups) return;
days.value = Array.isArray(data?.days)
? data.days.filter(d => isDateKey(d?.date))
: null;
conferences.value = Array.isArray(data?.conferences)
? data.conferences
: null;
unplaced.value =
data?.unplaced && typeof data.unplaced.count === 'number'
? data.unplaced
: null;
leagues.value = Array.isArray(data?.leagues)
? data.leagues.filter(l => typeof l?.league === 'string')
: null;
stages.value = Array.isArray(data?.stages)
? data.stages.filter(st => typeof st?.key === 'string' && st.key)
: null;
unstagedCount.value =
typeof data?.unstaged_count === 'number' ? data.unstaged_count : null;
if (isDateKey(data?.today)) serverToday.value = data.today;
};
// The round a selected group is sent with: its option's (null: none). An
// option that does not say (an older API), and a group whose options are
// not known yet (a link opened before the facets arrive), get the group
// stage's — and once they are known, a different round re-asks the page.
const groupRound = key => {
const option = findGroupOption(
groups.value,
key,
selectedGroupStage.value ?? selectedStage.value
);
if (!option || !('round' in option)) return GROUP_FILTER_ROUND;
return option.round;
};
const roundOfSelection = () =>
selectedGroup.value != null ? groupRound(selectedGroup.value) : null;
// The groups the Group control offers: a chosen conference or league
// narrows them to its side (SB-1753), a chosen stage to its own.
const offeredGroups = () =>
offeredGroupsFor({
groups: groups.value,
conference: (conferences.value || []).find(
c => c.id === selectedConferenceId.value
),
league: selectedLeague.value,
stage: (stages.value || []).find(st => st.key === selectedStage.value),
});
// A conference in the other league than the one chosen is not offered.
const conferenceFitsLeague = () => {
if (selectedConferenceId.value == null || !selectedLeague.value) {
return true;
}
const c = (conferences.value || []).find(
x => x.id === selectedConferenceId.value
);
return !c?.league || c.league === selectedLeague.value;
};
// Whether the selected group is still offered — as the option of the
// stage it was picked under, when one was (SB-1875: one stored group can
// be an option of two stages, each with its own round).
const groupOffered = () =>
(offeredGroups() || []).some(
g =>
g.key === selectedGroup.value &&
(selectedGroupStage.value == null ||
g.stage === selectedGroupStage.value)
);
const dropGroup = () => {
selectedGroup.value = null;
selectedGroupStage.value = null;
};
const dropUnofferedGroup = () => {
if (selectedGroup.value != null && !groupOffered()) dropGroup();
};
// After the facets change, drop any selection they no longer offer: a day
// this age does not play, a conference or group it does not have. Returns
// true when the page on screen no longer matches the selection.
const reconcile = () => {
let changed = false;
const day = pickDefaultDay(days.value, today(), selectedDay.value);
if (day !== selectedDay.value) {
selectedDay.value = day;
changed = true;
}
if (
selectedLeague.value &&
!(leagues.value || []).some(l => l.league === selectedLeague.value)
) {
selectedLeague.value = null;
changed = true;
}
if (
selectedConferenceId.value != null &&
(!(conferences.value || []).some(
c => c.id === selectedConferenceId.value
) ||
!conferenceFitsLeague())
) {
selectedConferenceId.value = null;
changed = true;
}
if (
selectedStage.value &&
!(stages.value || []).some(st => st.key === selectedStage.value)
) {
selectedStage.value = null;
changed = true;
}
if (selectedGroup.value != null && !groupOffered()) {
dropGroup();
changed = true;
}
return changed;
};
const setMatches = matches => {
tournament.value = { ...tournament.value, matches };
};
/**
* Load a tournament. `summary` is its row from `GET /api/tournaments` —
* `match_count` decides the mode, and in large mode it is also the header
* (name, dates, age groups), since the detail endpoint is never called.
* Throws when the matches cannot be loaded.
*
* `wanted`: { day, ageGroupId, conferenceId, group, league, stage, teamId }
* from a link. Each is honoured when the tournament offers it, and quietly
* dropped when not.
*/
const load = async (summary, wanted = {}) => {
wantedId = summary.id;
loadsInFlight += 1;
try {
await loadTournament(summary, wanted || {});
} finally {
loadsInFlight -= 1;
}
};
const loadTournament = async (summary, wanted) => {
const seq = ++loadSeq;
pageSeq += 1;
filtersSeq += 1;
const id = summary.id;
zone.value = venueTimeZone(summary);
const large = isLargeTournament(summary);
if (!large) {
const data = await get(`${getApiBaseUrl()}/api/tournaments/${id}`);
if (seq !== loadSeq) return;
isLarge.value = false;
ageGroups.value = [];
groups.value = null;
selectedAgeGroupId.value = null;
selectedGroup.value = null;
days.value = null;
conferences.value = null;
unplaced.value = null;
leagues.value = null;
stages.value = null;
unstagedCount.value = null;
selectedDay.value = null;
selectedConferenceId.value = null;
selectedLeague.value = null;
selectedStage.value = null;
selectedTeam.value = null;
viewBeforeTeam = null;
total.value = null;
pageError.value = null;
pageLoading.value = false;
tournament.value = data;
return;
}
const all = await fetchFilters(id, null);
if (seq !== loadSeq) return;
// Filters failed or came back empty: the tournament's own age groups
// still make the Age Group control possible.
applyFilters(all, { fallbackAgeGroups: summary.age_groups || [] });
selectedAgeGroupId.value = ageGroups.value.some(
ag => ag.id === wanted.ageGroupId
)
? wanted.ageGroupId
: pickDefaultAgeGroupId(ageGroups.value);
// That answer's groups span every age; the scoped one below replaces it.
groups.value = null;
// A first guess at the day from every age's days, so the page and the
// scoped filters can be asked for together; corrected below if this age
// does not play it.
selectedDay.value = pickDefaultDay(days.value, today(), wanted.day);
selectedConferenceId.value = wanted.conferenceId ?? null;
selectedGroup.value = wanted.group ?? null;
selectedGroupStage.value = wanted.group
? (wanted.groupStage ?? null)
: null;
selectedLeague.value = wanted.league ?? null;
selectedStage.value = wanted.stage ?? null;
viewBeforeTeam = null;
selectedTeam.value = wanted.teamId != null ? teamStub(wanted.teamId) : null;
if (selectedTeam.value) {
const age = await resolveTeamAge(
id,
wanted.ageGroupId ?? selectedAgeGroupId.value
);
if (seq !== loadSeq) return;
if (age != null) selectedAgeGroupId.value = age;
}
const roundAsked = roundOfSelection();
const [scoped, page] = await Promise.all([
fetchFilters(id, selectedAgeGroupId.value, selectedDay.value),
fetchPage(id, 0),
]);
if (seq !== loadSeq) return;
applyFilters(scoped);
const dayAsked = selectedDay.value;
const stale = reconcile() || roundOfSelection() !== roundAsked;
isLarge.value = true;
pageError.value = null;
pageLoading.value = false;
total.value = page?.total ?? null;
tournament.value = { ...summary, matches: page?.matches ?? [] };
nameTeamFromMatches();
// A team's list does not depend on the day or the filters reconciled.
if (stale && !selectedTeam.value) await settle(dayAsked);
};
// What is known of a team before its row is: its id, and a name once its
// matches say it.
const teamStub = teamId =>
knownTeams.get(teamId) ?? {
team_id: teamId,
name: null,
club_name: null,
logo_url: null,
age_groups: [],
league: null,
};
// A team opened from a link has no name until its matches arrive.
const nameTeamFromMatches = (matches = tournament.value?.matches) => {
const team = selectedTeam.value;
if (!team || team.name) return;
for (const m of matches ?? []) {
for (const side of ['home', 'away']) {
if (m[`${side}_team`]?.id === team.team_id) {
const club = m[`${side}_team_club`];
selectedTeam.value = {
...team,
name: m[`${side}_team`].name ?? null,
club_name: club?.name ?? null,
logo_url: club?.logo_url ?? null,
};
return;
}
}
}
};
// First page for the current filters, replacing what is on screen.
const reloadPage = async () => {
const id = tournament.value?.id;
if (id == null) return;
const seq = ++pageSeq;
pageLoading.value = true;
pageError.value = null;
total.value = null;
// The rows on screen belong to the previous filter.
setMatches([]);
try {
const page = await fetchPage(id, 0);
if (seq !== pageSeq) return;
total.value = page?.total ?? null;
setMatches(page?.matches ?? []);
nameTeamFromMatches();
} catch (err) {
if (seq !== pageSeq) return;
console.error('Error fetching tournament matches:', err);
pageError.value = 'Could not load these matches.';
} finally {
if (seq === pageSeq) pageLoading.value = false;
}
};
// Groups already known survive an answer that has none to give: after an
// age-group change they were cleared and stay unknown, and on a refresh the
// Group control stays on screen — a group may be selected, and hiding the
// control would leave the list narrowed with nothing to clear it.
// Resolves true when the answer was applied.
// Dropped only when a newer filters request has gone out, or the age group
// or day it was for is no longer the one selected.
const reloadFilters = async () => {
const id = tournament.value?.id;
if (id == null) return false;
const seq = ++filtersSeq;
const ageGroupId = selectedAgeGroupId.value;
const day = selectedDay.value;
const data = await fetchFilters(id, ageGroupId, day);
if (
seq !== filtersSeq ||
ageGroupId !== selectedAgeGroupId.value ||
day !== selectedDay.value
) {
return false;
}
if (tournament.value?.id !== id) return false;
applyFilters(data, { keepGroups: true });
return true;
};
// After `reconcile()` dropped part of the selection: ask again for what
// changed. A different day means the facets on screen were counted for the
// old day, so they are asked for again too — once; `days` does not depend
// on the day asked for, so the day cannot move twice.
const settle = async dayAsked => {
if (selectedDay.value === dayAsked) {
await reloadPage();
return;
}
const [, applied] = await Promise.all([reloadPage(), reloadFilters()]);
if (applied && reconcile()) await reloadPage();
};
// Page and filters together; when the new facets drop part of the
// selection, the page is asked for again with what is left.
const reloadBoth = async () => {
const dayAsked = selectedDay.value;
const roundAsked = roundOfSelection();
const [, applied] = await Promise.all([reloadPage(), reloadFilters()]);
if (applied && (reconcile() || roundOfSelection() !== roundAsked)) {
await settle(dayAsked);
}
};
const setAgeGroup = async ageGroupId => {
if (!isLarge.value || ageGroupId === selectedAgeGroupId.value) return;
selectedAgeGroupId.value = ageGroupId;
selectedGroup.value = null;
// The old age's groups are not this age's; unknown until they arrive.
groups.value = null;
await reloadBoth();
};
// `option`: the Group option picked, when known — its stage tells two
// options of one stored group apart (SB-1875).
const setGroup = async (groupKey, option = null) => {
const next = groupKey || null;
const stage = next ? (option?.stage ?? null) : null;
if (
!isLarge.value ||
(next === selectedGroup.value && stage === selectedGroupStage.value)
) {
return;
}
selectedGroup.value = next;
selectedGroupStage.value = stage;
await reloadPage();
};
// A day the age does not play stays selectable from a link only until the
// facets say otherwise; the list for it is simply empty meanwhile.
const setDay = async day => {
if (!isLarge.value || !isDateKey(day) || day === selectedDay.value) return;
selectedDay.value = day;
await Promise.all([reloadPage(), reloadFilters()]);
};
const setConference = async conferenceId => {
const next = conferenceId ?? null;
if (!isLarge.value || next === selectedConferenceId.value) return;
selectedConferenceId.value = next;
// A group on the other side of the new conference goes with it.
dropUnofferedGroup();
await reloadPage();
};
// Homegrown / Academy, or null for both. A conference or group of the other
// league goes with the change.
const setLeague = async league => {
const next = league || null;
if (!isLarge.value || next === selectedLeague.value) return;
selectedLeague.value = next;
if (!conferenceFitsLeague()) selectedConferenceId.value = null;
dropUnofferedGroup();
await reloadPage();
};
/**
* The age a team is shown at. A team whose ages are not known (a link, or
* a row without them) is first asked for in every age; the ages its matches
* are listed under are its ages. Resolves null when the answer is no longer
* wanted. Never the page's default age for a team that does not play it.
*/
const resolveTeamAge = async (id, preferred) => {
const team = selectedTeam.value;
if (!team) return null;
if ((team.age_groups || []).length === 0) {
const page = await fetchPage(id, 0, { allAges: true });
if (selectedTeam.value?.team_id !== team.team_id) return null;
const ages = new Map();
for (const m of page?.matches ?? []) {
if (m.age_group?.id != null && !ages.has(m.age_group.id)) {
ages.set(m.age_group.id, {
id: m.age_group.id,
name: m.age_group.name,
});
}
}
selectedTeam.value = {
...selectedTeam.value,
age_groups: [...ages.values()],
};
nameTeamFromMatches(page?.matches);
knownTeams.set(team.team_id, selectedTeam.value);
}
return ageForTeam(selectedTeam.value, preferred);
};
const setStage = async stageKey => {
const next = stageKey || null;
if (!isLarge.value || next === selectedStage.value) return;
selectedStage.value = next;
// The option a group was picked as belongs to the stage left behind; the
// new stage's own option of it, if any, is the one now.
selectedGroupStage.value = null;
dropUnofferedGroup();
await reloadPage();
};
// The selection a team replaces, in `applyView`'s shape.
const currentView = () => ({
day: selectedDay.value,
ageGroupId: selectedAgeGroupId.value,
conferenceId: selectedConferenceId.value,
group: selectedGroup.value,
groupStage: selectedGroupStage.value,
league: selectedLeague.value,
stage: selectedStage.value,
});
// The age a team is shown at: the one on screen when the team plays it,
// else the team's first.
const ageForTeam = (team, preferred = selectedAgeGroupId.value) => {
const ids = (team?.age_groups || []).map(ag => ag.id);
if (ids.length === 0 || ids.includes(preferred)) return preferred;
return ids[0];
};
/**
* Open one team's whole tournament schedule. `team` is a row from
* `GET /api/tournaments/{id}/teams`. `ageGroupId`, when the visitor picked
* one of the team's ages in the search (SB-1892), is the age shown; else the
* age being viewed if the team plays it, else its first.
*/
const selectTeam = async (team, ageGroupId = null) => {
if (!isLarge.value || team?.team_id == null) return;
if (!selectedTeam.value) viewBeforeTeam = currentView();
knownTeams.set(team.team_id, team);
selectedTeam.value = team;
const age = await resolveTeamAge(
tournament.value?.id,
ageGroupId ?? selectedAgeGroupId.value
);
if (selectedTeam.value?.team_id !== team.team_id) return;
if (age != null) selectedAgeGroupId.value = age;
await reloadPage();
};
/**
* Show the selected team at another of its ages (SB-1892). An age the team
* does not play is ignored: it would be an empty schedule, not a filter.
*/
const setTeamAge = async ageGroupId => {
const team = selectedTeam.value;
if (!isLarge.value || !team || ageGroupId === selectedAgeGroupId.value) {
return;
}
if (!(team.age_groups || []).some(ag => ag.id === ageGroupId)) return;
selectedAgeGroupId.value = ageGroupId;
await reloadPage();
};
/** Back to the view the team replaced, or the default view. */
const clearTeam = async () => {
if (!isLarge.value || !selectedTeam.value) return;
const back = viewBeforeTeam ?? {
day: null,
ageGroupId: selectedAgeGroupId.value,
};
viewBeforeTeam = null;
selectedTeam.value = null;
await restoreView(back);
};
// Put a whole selection in place and ask for its page and facets.
const restoreView = async ({
day = null,
ageGroupId = null,
conferenceId = null,
group = null,
groupStage = null,
league = null,
stage = null,
}) => {
const age = ageGroups.value.some(ag => ag.id === ageGroupId)
? ageGroupId
: selectedAgeGroupId.value;
if (age !== selectedAgeGroupId.value) groups.value = null;
selectedAgeGroupId.value = age;
selectedDay.value = day || pickDefaultDay(days.value, today(), null);
selectedConferenceId.value = conferenceId;
selectedGroup.value = group;
selectedGroupStage.value = group ? groupStage : null;
selectedLeague.value = league;
selectedStage.value = stage;
await reloadBoth();
};
/**
* Put the whole selection back at once — back / forward to a URL. Values
* the tournament does not offer are dropped once its facets say so.
*/
const applyView = async ({
day = null,
ageGroupId = null,
conferenceId = null,
group = null,
groupStage = null,
league = null,
stage = null,
teamId = null,
} = {}) => {
if (!isLarge.value) return;
if (teamId != null) {
const same = selectedTeam.value?.team_id === teamId;
if (same && ageGroupId === selectedAgeGroupId.value) return;
if (!selectedTeam.value) viewBeforeTeam = currentView();
if (!same) selectedTeam.value = teamStub(teamId);
const age = ageGroups.value.some(ag => ag.id === ageGroupId)
? ageGroupId
: await resolveTeamAge(tournament.value?.id, selectedAgeGroupId.value);
if (selectedTeam.value?.team_id !== teamId) return;
if (age != null) selectedAgeGroupId.value = age;
await reloadPage();
return;
}
if (selectedTeam.value) {
selectedTeam.value = null;
viewBeforeTeam = null;
await restoreView({
day,
ageGroupId,
conferenceId,
group,
groupStage,
league,
stage,
});
return;
}
const age = ageGroups.value.some(ag => ag.id === ageGroupId)
? ageGroupId
: selectedAgeGroupId.value;
const ageChanged = age !== selectedAgeGroupId.value;
if (
!ageChanged &&
(day ?? selectedDay.value) === selectedDay.value &&
conferenceId === selectedConferenceId.value &&
group === selectedGroup.value &&
(group ? groupStage : null) === selectedGroupStage.value &&
league === selectedLeague.value &&
stage === selectedStage.value
) {
return;
}
selectedAgeGroupId.value = age;
if (day) selectedDay.value = day;
selectedConferenceId.value = conferenceId;
selectedGroupStage.value = group ? groupStage : null;
selectedGroup.value = group;
selectedLeague.value = league;
selectedStage.value = stage;
if (ageChanged) groups.value = null;
await reloadBoth();
};
const loadMore = async () => {
const id = tournament.value?.id;
if (id == null || !hasMore.value || loadingMore.value) return;
const seq = pageSeq;
loadingMore.value = true;
pageError.value = null;
try {
const page = await fetchPage(id, loadedCount.value);
if (seq !== pageSeq) return;
const seen = new Set(tournament.value.matches.map(m => m.id));
total.value = page?.total ?? total.value;
setMatches([
...tournament.value.matches,
...(page?.matches ?? []).filter(m => !seen.has(m.id)),
]);
} catch (err) {
if (seq !== pageSeq) return;
console.error('Error fetching more tournament matches:', err);
pageError.value = 'Could not load more matches.';
} finally {
loadingMore.value = false;
}
};
/**
* Refetch what is on screen without disturbing it: the detail in small
* mode, the pages already loaded in large mode. Throws on failure and
* leaves the current rows in place.
*
* Does nothing while a tournament is loading, or when the last one asked
* for is not the one on screen: `tournament` is then the previous
* selection, and refetching it would put it back under the new one.
*/
const refresh = async () => {
const id = tournament.value?.id;
if (id == null || loadsInFlight > 0 || id !== wantedId) return;
const seq = loadSeq;
// Still the tournament that was fetched, with no load started since.
const current = () =>
seq === loadSeq &&
loadsInFlight === 0 &&
wantedId === id &&
tournament.value?.id === id;
if (!isLarge.value) {
const data = await get(`${getApiBaseUrl()}/api/tournaments/${id}`);
if (current()) tournament.value = data;
return;
}
const pSeq = pageSeq;
const wanted = Math.max(loadedCount.value, 1);
const rows = [];
let newTotal = total.value;
for (let offset = 0; offset < wanted; offset += TOURNAMENT_PAGE_SIZE) {
const page = await fetchPage(id, offset);
if (!current() || pSeq !== pageSeq) return;
newTotal = page?.total ?? newTotal;
rows.push(...(page?.matches ?? []));
if (rows.length >= (newTotal ?? 0)) break;
}
total.value = newTotal;
setMatches(rows);
reloadFilters();
};
return {
tournament,
isLarge,
ageGroups,
groups,
selectedAgeGroupId,
selectedGroup,
selectedGroupStage,
days,
conferences,
unplaced,
venueToday,
selectedDay,
selectedConferenceId,
leagues,
stages,
unstagedCount,
selectedLeague,
selectedStage,
selectedTeam,
teamMode,
total,
loadedCount,
hasMore,
pageLoading,
loadingMore,
pageError,
load,
refresh,
reloadPage,
setAgeGroup,
setGroup,
setDay,
setConference,
setLeague,
setStage,
selectTeam,
setTeamAge,
clearTeam,
applyView,
loadMore,
};
}
|