summaryrefslogtreecommitdiff
path: root/static/boot.js
blob: 0bec294a22a91a39e56a5db2d4e11fd3823925e9 (plain)
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
(() => {
  if (window.__wsapBootInitialized) return;
  window.__wsapBootInitialized = true;

  const getCurrentTheme = () =>
    document.documentElement.getAttribute("data-theme") === "dark"
      ? "dark"
      : "light";

  const updateThemeToggleLabels = (theme) => {
    const label =
      theme === "dark" ? "Switch to light mode" : "Switch to dark mode";
    document.querySelectorAll(".theme-toggle").forEach((button) => {
      if (button instanceof HTMLElement) {
        button.setAttribute("aria-label", label);
        button.setAttribute("title", label);
      }
    });
  };

  const applyTheme = (theme, persist = true) => {
    document.documentElement.setAttribute("data-theme", theme);
    updateThemeToggleLabels(theme);

    if (!persist) return;

    try {
      localStorage.setItem("theme", theme);
    } catch {
      // Ignore read/write failures in strict privacy modes.
    }
  };

  const initThemeToggle = () => {
    applyTheme(getCurrentTheme(), false);

    document.addEventListener("click", (event) => {
      const eventTarget = event.target;
      if (!(eventTarget instanceof Element)) return;

      const toggleButton = eventTarget.closest(".theme-toggle");
      if (!(toggleButton instanceof HTMLElement)) return;

      const currentTheme = getCurrentTheme();
      const nextTheme = currentTheme === "dark" ? "light" : "dark";
      applyTheme(nextTheme);
    });
  };

  const loadAnalytics = () => {
    if (document.querySelector('script[data-goatcounter-script="true"]'))
      return;

    const script = document.createElement("script");
    script.src = "https://stats.wsap.dev/count.js";
    script.async = true;
    script.defer = true;
    script.setAttribute("data-goatcounter", "https://stats.wsap.dev/count");
    script.setAttribute("data-goatcounter-script", "true");
    document.head.appendChild(script);
  };

  const scheduleAnalytics = () => {
    if ("requestIdleCallback" in window) {
      window.requestIdleCallback(loadAnalytics, { timeout: 3000 });
      return;
    }
    window.setTimeout(loadAnalytics, 1500);
  };

  const init = () => {
    initThemeToggle();

    if (document.readyState === "complete") scheduleAnalytics();
    else window.addEventListener("load", scheduleAnalytics, { once: true });
  };

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init, { once: true });
    return;
  }

  init();
})();