All files / src/composables useLiveRowSync.js

100% Statements 84/84
100% Branches 24/24
100% Functions 7/7
100% Lines 84/84

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 971x 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 162x   162x 457x 457x 457x 457x 457x 457x   162x 457x 457x 5x 4x 4x 4x 5x 457x 16x 15x 15x 16x 2x 2x 2x 2x 2x 16x 457x   162x 97x 97x 97x   162x   162x 20x 162x 162x 154x 154x   162x 97x 97x 97x 90x 90x 162x   162x 162x 162x   162x 162x 162x  
/**
 * Keep a list of match rows current while some of them are live (SB-909).
 *
 * A view that loads its matches once and then sits there goes stale the moment
 * a match ends somewhere else — another device, another tab, the live-scoring
 * screen. That is what happened to the Tournaments tab on 2026-08-29: the API
 * had the final score immediately, the open page never asked again.
 *
 * Two mechanisms, because neither alone is enough:
 *
 * 1. **Realtime** — one Supabase subscription per live row, merged into the
 *    list as UPDATEs arrive. Cheap and instant, but only while the socket is
 *    connected, and only for rows that were live when we subscribed.
 * 2. **Refresh on return** — a full refetch when the tab becomes visible
 *    again. Covers everything realtime missed: a dropped socket, a phone
 *    asleep in a pocket, a match that went live after the page loaded.
 *
 * Subscriptions are reconciled whenever the list changes and torn down on
 * unmount.
 */
 
import { getCurrentInstance, onUnmounted, watch } from 'vue';
import { subscribeToMatch } from './useMatchRealtime';
 
/**
 * @param {import('vue').Ref|import('vue').ComputedRef} matches - list of match
 *   objects; each needs `id` and `match_status`.
 * @param {(newRow: object) => void} applyUpdate - called with the raw `matches`
 *   row from a realtime UPDATE. The payload carries only real columns, so the
 *   consumer must merge rather than replace (joined display fields would be
 *   lost otherwise).
 * @param {object} [options]
 * @param {() => void} [options.onReturn] - called when the tab becomes visible
 *   again. Usually the view's own refetch.
 */
export function useLiveRowSync(matches, applyUpdate, { onReturn } = {}) {
  const subs = new Map(); // matchId → handle
 
  function liveIdsOf(list) {
    return new Set(
      (list || [])
        .filter(m => m?.match_status === 'live' && m?.id != null)
        .map(m => m.id)
    );
  }
 
  function reconcile(list) {
    const live = liveIdsOf(list);
    for (const [id, handle] of subs) {
      if (!live.has(id)) {
        handle.unsubscribe();
        subs.delete(id);
      }
    }
    for (const id of live) {
      if (subs.has(id)) continue;
      try {
        subs.set(id, subscribeToMatch(id, applyUpdate));
      } catch (err) {
        // Realtime is an enhancement, not the data path. A misconfigured or
        // unreachable socket must not take the view down with it — the
        // refresh-on-return half still keeps the page honest.
        console.error('Live row subscription failed:', err);
      }
    }
  }
 
  function teardown() {
    for (const handle of subs.values()) handle.unsubscribe();
    subs.clear();
  }
 
  const stopWatch = watch(matches, reconcile, { immediate: true });
 
  const onVisibility = () => {
    if (typeof document !== 'undefined' && !document.hidden) onReturn?.();
  };
  if (onReturn && typeof document !== 'undefined') {
    document.addEventListener('visibilitychange', onVisibility);
  }
 
  const stop = () => {
    stopWatch();
    teardown();
    if (onReturn && typeof document !== 'undefined') {
      document.removeEventListener('visibilitychange', onVisibility);
    }
  };
 
  // Called from a composable a test drives directly, there is no instance to
  // hang the hook on — and Vue warns about that rather than ignoring it.
  if (getCurrentInstance()) onUnmounted(stop);
 
  // Exposed for tests and for callers that manage their own lifetime.
  return { stop, subscribedIds: () => [...subs.keys()] };
}