utils/kioskParams.jsjavascript
import { CONFIG_SCHEMA } from "../services/config/config-schema";

const STORAGE_KEY = "kioskParams";

// the URL params useConfig understands (stageDevice, hideAppSwitch, ...)
const PARAM_NAMES = CONFIG_SCHEMA.filter(({ source }) => source === "param").map(
  ({ name }) => name
);

// installed app (home screen / desktop install) instead of a browser tab;
// navigator.standalone is iOS Safari's own flag
const isInstalledApp = () =>
  window.matchMedia?.("(display-mode: standalone)").matches ||
  window.matchMedia?.("(display-mode: fullscreen)").matches ||
  navigator.standalone === true;

const pickConfigParams = (params) =>
  PARAM_NAMES.filter((name) => params.has(name)).map((name) => [name, params.get(name)]);

/**
 * Keeps the kiosk config params (config-schema.js) of an installed app, the
 * iPads' home-screen PWA: it has no address bar, and depending on the iPadOS
 * version a launch may not get back the exact URL it was installed from -
 * without `stageDevice=ipad` the iPad would render the 4K layout. (The
 * tracking `deviceId` needs nothing here, messe-tracking stores it itself.)
 *
 * Runs once at boot, before the router reads the hash:
 * - config params in the URL win and are stored - in the hash
 *   (`#/route?stageDevice=ipad`) or, in case a launch drops the fragment,
 *   before it (`/?stageDevice=ipad`), from where they're moved into the hash
 *   useConfig reads;
 * - a launch without any is given the stored ones back.
 *
 * Browser tabs are left alone, so the 4K kiosks and development keep using
 * exactly the URL they were opened with.
 */
export const restoreKioskParams = () => {
  if (!isInstalledApp()) return;

  const { pathname, search, hash } = window.location;
  const queryStart = hash.indexOf("?");
  const route = (queryStart === -1 ? hash.slice(1) : hash.slice(1, queryStart)) || "/";
  const hashParams = new URLSearchParams(queryStart === -1 ? "" : hash.slice(queryStart + 1));

  // hash last, so it wins over the same param before the fragment
  const fromUrl = Object.fromEntries([
    ...pickConfigParams(new URLSearchParams(search)),
    ...pickConfigParams(hashParams),
  ]);

  try {
    let params = fromUrl;
    if (Object.keys(params).length > 0) {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(params));
    } else {
      params = JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
    }

    let changed = false;
    for (const [name, value] of Object.entries(params)) {
      if (hashParams.get(name) === value) continue;
      hashParams.set(name, value);
      changed = true;
    }
    if (changed) {
      window.history.replaceState(
        window.history.state,
        "",
        `${pathname}${search}#${route}?${hashParams}`
      );
    }
  } catch (err) {
    // eslint-disable-next-line no-console
    console.warn("[kioskParams] could not restore the kiosk params.", err);
  }
};