All files / app/features/analytics foregroundTracker.ts

58.82% Statements 10/17
44.44% Branches 4/9
66.66% Functions 2/3
62.5% Lines 10/16

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                      10x 10x 10x   10x       10x                     10x 10x 10x 10x   10x              
/**
 * Accumulates wall-clock and foreground (document visible) time since creation.
 *
 * Wire `onVisibilityChange` to the document's `visibilitychange` event, then
 * call `finalize()` once (e.g. on unmount) to read the totals.
 */
export interface ForegroundTracker {
  onVisibilityChange: () => void;
  finalize: () => { foregroundMs: number; totalMs: number };
}
 
export function createForegroundTracker(): ForegroundTracker {
  const startedAt = performance.now();
  let foregroundAccumMs = 0;
  let visibleSince: number | null =
    typeof document !== "undefined" && document.visibilityState === "visible"
      ? startedAt
      : null;
 
  return {
    onVisibilityChange() {
      const now = performance.now();
      if (document.visibilityState === "visible") {
        Iif (visibleSince === null) visibleSince = now;
      } else Iif (visibleSince !== null) {
        foregroundAccumMs += now - visibleSince;
        visibleSince = null;
      }
    },
    finalize() {
      const now = performance.now();
      if (visibleSince !== null) {
        foregroundAccumMs += now - visibleSince;
        visibleSince = null;
      }
      return {
        foregroundMs: Math.round(foregroundAccumMs),
        totalMs: Math.round(now - startedAt),
      };
    },
  };
}