services/screensaver.jsxjavascript
/*
  Combines idle detection (useIdle) with the configured timeout/fade values
  (useConfig) into a single ScreensaverContext. Waking from idle also resets
  the kiosk session: the app re-navigates to the same route (pathname+search,
  not back to "/") while the screensaver is still fading out, so the next
  visitor starts that page fresh instead of inheriting the previous visitor's
  open menus and selections - re-navigating remounts the page component,
  which is what clears that per-page state, no explicit reset needed.
  Previously this went back to the app-selection screen ("/") instead; that
  was changed to stay on the current page/app so a visitor's search params
  and place in the exhibit survive a screensaver interruption (see
  "refactor: Refine navigation flow and screensaver exit behavior"). The
  reset deliberately happens on wake-up rather than when going idle: the
  screensaver video is defined by the current route's content file (see
  Screensaver.jsx), and navigating away at idle start would unload it
  mid-show.

  Must be mounted inside the Router (see src/HashRouter.jsx): useConfig (via
  useSearchParams) requires router context, and the session reset needs
  useNavigate/useLocation. Same reason ContentProvider now lives in
  HashRouter.jsx instead of App.jsx - TabProvider stays in App.jsx since it
  doesn't use useConfig.
*/

// allow export of contexts and hooks - shouldn't be flagged as non-component
/* eslint react-refresh/only-export-components: 0 */

import { createContext, useCallback, useContext, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { useNavigate, useLocation } from "react-router";
import { useTracking } from "./tracking/useTracking";
import { useConfig } from "./config/config";
import { areaForPath } from "./tracking/area";
import { useIdle } from "../hooks/idle";

const ScreensaverContext = createContext();

/**
 * Tracks idle state and exposes it via ScreensaverContext.
 */
export const ScreensaverProvider = ({ children }) => {
  const { screensaverTimeout, screensaverFadeDuration, stageDevice } = useConfig();
  // On the iPad (stageDevice=ipad) the app is browsed personally rather than
  // run as an unattended kiosk, so it has no screensaver at all: no idle
  // timeout (null disables useIdle's), no overlay (Screensaver.jsx) and no
  // "Screensaver" buttons - every button checks `enabled`.
  const enabled = stageDevice !== "ipad";
  // screensaverTimeout is in seconds (see config.jsx), useIdle expects ms.
  const idleTimeout = enabled ? screensaverTimeout * 1000 : null;
  const { isIdle, trigger, forceIdle } = useIdle(idleTimeout);
  const navigate = useNavigate();
  const { pathname, search } = useLocation();
  const { trackEvent } = useTracking();

  // set by showNow() (the "Screensaver" buttons) so screensaver_start can
  // tell a deliberate start apart from the inactivity timeout
  const forcedRef = useRef(false);
  const showNow = useCallback(() => {
    if (!enabled) return;
    forcedRef.current = true;
    forceIdle();
  }, [enabled, forceIdle]);

  // session reset on the idle -> active transition only (not on mount, not
  // while idle): happens behind the still-opaque fading screensaver, no view
  // transition needed; keeps the kiosk config params (config-schema.js) alive.
  // Both transitions are also tracked - screensaver_end marks the start of a
  // new visitor session in the raw tracking data (there is no session concept
  // in the SDK itself), and is sent before the reset navigation so it
  // precedes that navigation's page_view.
  const wasIdleRef = useRef(false);
  const idleSinceRef = useRef(null);
  useEffect(() => {
    const area = areaForPath(pathname);
    if (!wasIdleRef.current && isIdle) {
      idleSinceRef.current = Date.now();
      trackEvent?.("screensaver_start", {
        element: area,
        payload: { reason: forcedRef.current ? "button" : "timeout" },
      });
      forcedRef.current = false;
    }
    if (wasIdleRef.current && !isIdle) {
      trackEvent?.("screensaver_end", {
        element: area,
        payload: { trigger, idleDurationMs: Date.now() - idleSinceRef.current },
      });
      if (pathname !== "/") navigate(`${pathname}${search}`);
    }
    wasIdleRef.current = isIdle;
  }, [isIdle, trigger, pathname, search, navigate, trackEvent]);

  return (
    <ScreensaverContext.Provider
      value={{ enabled, isIdle, trigger, screensaverFadeDuration, showNow }}>
      {children}
    </ScreensaverContext.Provider>
  );
};

ScreensaverProvider.propTypes = {
  children: PropTypes.node.isRequired,
};

/**
 * React hook to access { enabled, isIdle, trigger, screensaverFadeDuration, showNow }.
 * Must be used within a `<ScreensaverProvider>`.
 */
export const useScreensaver = () => {
  return useContext(ScreensaverContext);
};