All files / src/components TournamentTeamSearch.vue

98.87% Statements 351/355
87.5% Branches 77/88
86.66% Functions 13/15
98.87% Lines 351/355

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 4201x 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 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 6x 6x 6x 6x 6x 6x   6x 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 45x 45x 45x 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 37x 37x           37x 37x 37x 1x 1x 1x 1x 1x 23x 23x 23x 23x   23x 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 199x 199x 199x 62x 1x 1x   1x 41x 41x 41x 41x 20x 20x 1x 1x   1x 22x 22x 22x 22x 22x 22x 22x 22x 22x 22x 20x 20x 22x 22x 22x 22x 1x 1x 1x 1x 1x 22x 22x 22x 22x   1x 29x 29x 29x 29x 6x 6x 6x 6x 6x 6x 6x 6x 6x 23x 1x   1x   1x 4x 4x 4x 4x 4x 4x   1x 12x 12x 12x 12x 12x 12x 12x 12x 12x   1x 1x 12x 12x 12x 1x 12x 11x 11x 12x   1x 1x 1x 10x 10x 10x 1x 1x 1x 1x 10x 10x 10x   1x       1x 3x 3x 3x 3x 3x   1x 2x 2x 2x 2x   1x 1x 2x 1x 1x 1x 1x     2x   1x   1x    
<template>
  <!-- Find a club or team in this tournament (SB-1870). On a phone a search
       button in the sticky bar opens it full screen; from `sm` up the field
       sits inline with a dropdown. One input either way — an ARIA combobox
       over the tournament's teams, asked for as the visitor types. -->
  <div class="min-w-0 sm:relative">
    <button
      ref="trigger"
      type="button"
      class="sm:hidden shrink-0 w-11 h-11 inline-flex items-center justify-center rounded-full border border-line bg-card text-fg hover:border-brand-400 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
      aria-label="Find a club or team"
      aria-haspopup="dialog"
      :aria-expanded="overlayOpen ? 'true' : 'false'"
      data-testid="team-search-open"
      @click="openOverlay"
    >
      <svg viewBox="0 0 20 20" class="w-5 h-5" aria-hidden="true">
        <circle
          cx="8.5"
          cy="8.5"
          r="5.5"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
        />
        <path
          d="M13 13l4 4"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
        />
      </svg>
    </button>
 
    <!-- Open on a phone, the panel is moved to <body>: the sticky bar is a
         stacking context below the app header, and a full-screen panel
         inside it would sit under the header. -->
    <Teleport to="body" :disabled="!overlayOpen">
      <div
        :role="overlayOpen ? 'dialog' : undefined"
        :aria-modal="overlayOpen ? 'true' : undefined"
        :aria-label="overlayOpen ? 'Find a club or team' : undefined"
        :class="[
          overlayOpen
            ? 'fixed inset-0 z-[1010] flex flex-col bg-card px-3 pt-[max(0.75rem,env(safe-area-inset-top))] pb-[max(0.75rem,env(safe-area-inset-bottom))]'
            : 'hidden',
          'sm:block sm:static sm:inset-auto sm:z-auto sm:bg-transparent sm:p-0',
        ]"
        data-testid="team-search-panel"
        @keydown.esc.stop="onEscape"
      >
        <div class="flex items-center gap-2 min-w-0">
          <div class="relative flex-1 min-w-0 sm:w-64">
            <svg
              viewBox="0 0 20 20"
              class="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-fg-muted"
              aria-hidden="true"
            >
              <circle
                cx="8.5"
                cy="8.5"
                r="5.5"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
              />
              <path
                d="M13 13l4 4"
                fill="none"
                stroke="currentColor"
                stroke-width="2"
                stroke-linecap="round"
              />
            </svg>
            <label :for="inputId" class="sr-only">Find a club or team</label>
            <input
              :id="inputId"
              ref="input"
              v-model="query"
              type="search"
              role="combobox"
              autocomplete="off"
              autocapitalize="off"
              spellcheck="false"
              enterkeyhint="search"
              placeholder="Find a club or team"
              aria-autocomplete="list"
              :aria-expanded="listOpen ? 'true' : 'false'"
              :aria-controls="listId"
              :aria-activedescendant="
                listOpen && active >= 0 ? optionId(active) : undefined
              "
              :disabled="disabled"
              data-testid="team-search-input"
              class="block w-full h-11 sm:h-10 pl-9 pr-3 border border-line bg-card text-fg placeholder:text-fg-muted rounded-full sm:rounded-lg shadow-sm text-base sm:text-sm focus:outline-none focus:ring-2 focus:ring-brand-500 focus:border-brand-500 disabled:opacity-60"
              @focus="focused = true"
              @blur="onBlur"
              @keydown.down.prevent="move(1)"
              @keydown.up.prevent="move(-1)"
              @keydown.enter.prevent="chooseActive"
            />
          </div>
          <button
            v-if="overlayOpen"
            type="button"
            class="sm:hidden shrink-0 h-11 px-3 rounded-full text-sm font-semibold text-brand-600 dark:text-brand-300 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500"
            data-testid="team-search-cancel"
            @click="closeOverlay"
          >
            Cancel
          </button>
        </div>
 
        <div
          v-if="showDropdown"
          :class="[
            overlayOpen ? 'mt-3 flex-1 min-h-0 overflow-y-auto' : '',
            'sm:absolute sm:right-0 sm:top-full sm:mt-1 sm:w-96 sm:max-w-[calc(100vw-2rem)] sm:max-h-96 sm:overflow-y-auto sm:rounded-xl sm:border sm:border-line sm:bg-card sm:shadow-xl sm:z-50',
          ]"
          data-testid="team-search-dropdown"
        >
          <ul
            v-show="listOpen"
            :id="listId"
            role="listbox"
            aria-label="Teams"
            class="py-1"
          >
            <li
              v-for="(team, i) in results"
              :id="optionId(i)"
              :key="team.team_id"
              role="option"
              :aria-selected="i === active ? 'true' : 'false'"
              data-testid="team-search-option"
              :data-team-id="team.team_id"
              :class="[
                'flex items-center gap-3 min-h-[3.25rem] px-3 py-2 cursor-pointer rounded-lg',
                i === active ? 'bg-surface-alt' : '',
              ]"
              @mousedown.prevent
              @click="choose(team)"
              @mousemove="active = i"
            >
              <ClubLogo
                v-if="team.logo_url"
                :logo-url="team.logo_url"
                :name="team.club_name || team.name || ''"
                size="sm"
              />
              <span
                v-else
                class="w-8 h-8 shrink-0 rounded-full bg-surface-alt flex items-center justify-center text-xs font-bold text-fg-muted"
                aria-hidden="true"
                >{{ initialOf(team.name) }}</span
              >
              <span class="flex-1 min-w-0">
                <span class="block truncate text-sm font-semibold text-fg">{{
                  team.name
                }}</span>
                <span
                  v-if="team.club_name && team.club_name !== team.name"
                  class="block truncate text-xs text-fg-muted"
                  >{{ team.club_name }}</span
                >
              </span>
              <span class="shrink-0 flex items-center gap-1">
                <!-- Several ages: each opens the team at that age (SB-1892). -->
                <template v-if="(team.age_groups || []).length > 1">
                  <button
                    v-for="ag in team.age_groups"
                    :key="ag.id"
                    type="button"
                    tabindex="-1"
                    :aria-label="`${team.name} ${ag.name}`"
                    class="rounded focus:outline-none hover:ring-2 hover:ring-brand-400"
                    data-testid="team-search-age"
                    @click.stop="choose(team, ag.id)"
                  >
                    <TournamentChip variant="age">{{ ag.name }}</TournamentChip>
                  </button>
                </template>
                <TournamentChip
                  v-for="ag in team.age_groups || []"
                  v-else
                  :key="ag.id"
                  variant="age"
                  >{{ ag.name }}</TournamentChip
                >
                <!-- The league lookup failed: unknown, which is not the
                     same as a team placed in no conference (no badge). -->
                <span
                  v-if="team.league_known === false"
                  class="inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-bold bg-surface-alt text-fg-muted"
                  title="Conference unknown"
                  aria-label="Conference unknown"
                  data-testid="team-search-league-unknown"
                  >?</span
                >
                <span
                  v-else-if="leagueBadge(team.league)"
                  :class="[
                    'inline-flex items-center px-1.5 py-0.5 rounded text-[11px] font-bold tracking-wide',
                    team.league === 'Academy'
                      ? 'bg-accent-100 text-accent-800 dark:bg-accent-900 dark:text-accent-100'
                      : 'bg-brand-600 text-white dark:bg-brand-500',
                  ]"
                  :title="team.league"
                  data-testid="team-search-league"
                  >{{ leagueBadge(team.league) }}</span
                >
              </span>
            </li>
          </ul>
          <p
            v-if="statusText"
            class="px-3 py-3 text-sm text-fg-muted"
            role="status"
            data-testid="team-search-status"
          >
            {{ statusText }}
          </p>
        </div>
      </div>
    </Teleport>
  </div>
</template>
 
<script setup>
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
import { useAuthStore } from '../stores/auth';
import { getApiBaseUrl } from '../config/api';
import ClubLogo from './shared/ClubLogo.vue';
import TournamentChip from './ui/TournamentChip.vue';
import { leagueBadge } from '../utils/tournamentDays';
 
// Typing pauses this long before the server is asked.
const TEAM_SEARCH_DEBOUNCE_MS = 250;
// The server answers nothing shorter, so nothing shorter is sent.
const TEAM_SEARCH_MIN_CHARS = 2;
const TEAM_SEARCH_LIMIT = 20;
 
const props = defineProps({
  tournamentId: { type: Number, required: true },
  disabled: { type: Boolean, default: false },
});
 
const emit = defineEmits(['select']);
 
const authStore = useAuthStore();
 
const inputId = 'tournament-team-search';
const listId = 'tournament-team-search-list';
const optionId = i => `${listId}-${i}`;
 
const query = ref('');
// [{ team_id, name, club_id, club_name, logo_url, age_groups, league }]
const results = ref([]);
// The query the results are for; null while nothing has been answered.
const answeredFor = ref(null);
const searching = ref(false);
const failed = ref(false);
const active = ref(-1);
const focused = ref(false);
const dismissed = ref(false);
const overlayOpen = ref(false);
const input = ref(null);
const trigger = ref(null);
 
let timer = null;
let seq = 0;
 
const trimmed = computed(() => query.value.trim());
const longEnough = computed(
  () => trimmed.value.length >= TEAM_SEARCH_MIN_CHARS
);
 
const showDropdown = computed(
  () =>
    (focused.value || overlayOpen.value) &&
    !dismissed.value &&
    longEnough.value &&
    (searching.value || failed.value || answeredFor.value != null)
);
const listOpen = computed(() => showDropdown.value && results.value.length > 0);
 
const statusText = computed(() => {
  if (!showDropdown.value) return '';
  if (failed.value) return "Search isn't available right now.";
  if (results.value.length > 0) return '';
  if (searching.value || answeredFor.value !== trimmed.value) {
    return 'Searching…';
  }
  return `No teams match '${trimmed.value}'`;
});
 
const search = async q => {
  const mine = ++seq;
  searching.value = true;
  failed.value = false;
  try {
    const params = new URLSearchParams({ q, limit: TEAM_SEARCH_LIMIT });
    const data = await authStore.apiRequest(
      `${getApiBaseUrl()}/api/tournaments/${props.tournamentId}/teams?${params}`,
      { method: 'GET' }
    );
    if (mine !== seq) return;
    results.value = Array.isArray(data)
      ? data.filter(t => t?.team_id != null)
      : [];
    answeredFor.value = q;
    active.value = results.value.length > 0 ? 0 : -1;
  } catch (err) {
    if (mine !== seq) return;
    console.error('Error searching tournament teams:', err);
    results.value = [];
    answeredFor.value = null;
    failed.value = true;
  } finally {
    if (mine === seq) searching.value = false;
  }
};
 
watch(query, () => {
  clearTimeout(timer);
  dismissed.value = false;
  const q = trimmed.value;
  if (q.length < TEAM_SEARCH_MIN_CHARS) {
    // Anything in flight is for text that is no longer there.
    seq += 1;
    results.value = [];
    answeredFor.value = null;
    searching.value = false;
    failed.value = false;
    active.value = -1;
    return;
  }
  timer = setTimeout(() => search(q), TEAM_SEARCH_DEBOUNCE_MS);
});
 
onBeforeUnmount(() => clearTimeout(timer));
 
const move = step => {
  dismissed.value = false;
  const n = results.value.length;
  if (n === 0) return;
  active.value =
    active.value < 0 ? (step > 0 ? 0 : n - 1) : (active.value + step + n) % n;
};
 
const reset = () => {
  clearTimeout(timer);
  seq += 1;
  query.value = '';
  results.value = [];
  answeredFor.value = null;
  searching.value = false;
  failed.value = false;
  active.value = -1;
};
 
// `ageGroupId`: the age chip the visitor picked, if any (SB-1892).
const choose = (team, ageGroupId = null) => {
  emit('select', team, ageGroupId);
  reset();
  if (overlayOpen.value) {
    overlayOpen.value = false;
  } else {
    input.value?.blur?.();
  }
};
 
// Enter while the results on screen are for older text (typing has not
// paused yet, or the answer is in flight) asks for the text now, then picks.
const chooseActive = async () => {
  const q = trimmed.value;
  if (q.length < TEAM_SEARCH_MIN_CHARS) return;
  if (answeredFor.value !== q || searching.value) {
    clearTimeout(timer);
    await search(q);
    if (trimmed.value !== q) return;
  }
  const team = results.value[active.value];
  if (team) choose(team);
};
 
const onBlur = () => {
  focused.value = false;
};
 
const openOverlay = async () => {
  overlayOpen.value = true;
  dismissed.value = false;
  await nextTick();
  input.value?.focus?.();
};
 
const closeOverlay = async () => {
  overlayOpen.value = false;
  await nextTick();
  trigger.value?.focus?.();
};
 
// Escape closes the list first, then the phone overlay.
const onEscape = () => {
  if (overlayOpen.value) {
    closeOverlay();
  } else if (showDropdown.value) {
    dismissed.value = true;
  } else if (query.value) {
    reset();
  }
};
 
const initialOf = name => (name || '?').trim().charAt(0).toUpperCase();
 
defineExpose({ overlayOpen, openOverlay, closeOverlay });
</script>