summaryrefslogtreecommitdiffstats
path: root/assets/js/theme-toggle.js
blob: 9f0fd5ab4f439490709895f11fdbcdf04b80e7d3 (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
// theme-toggle.js
(function() {
  const STORAGE_KEY = 'danix-theme';
  const DARK_CLASS = 'theme-dark';
  const LIGHT_CLASS = 'theme-light';

  // Initialize theme on page load
  function init() {
    const saved = localStorage.getItem(STORAGE_KEY);
    const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const isDark = saved === null ? prefersDark : saved === 'dark';

    applyTheme(isDark ? 'dark' : 'light');
  }

  // Apply theme to document
  function applyTheme(theme) {
    const html = document.documentElement;

    html.classList.remove(DARK_CLASS, LIGHT_CLASS);

    if (theme === 'dark') {
      html.classList.remove(LIGHT_CLASS);
      localStorage.setItem(STORAGE_KEY, 'dark');
    } else {
      html.classList.add(LIGHT_CLASS);
      localStorage.setItem(STORAGE_KEY, 'light');
    }
  }

  // Get current theme
  function getCurrentTheme() {
    return document.documentElement.classList.contains(LIGHT_CLASS) ? 'light' : 'dark';
  }

  // Toggle theme
  function toggleTheme() {
    const current = getCurrentTheme();
    const next = current === 'dark' ? 'light' : 'dark';
    applyTheme(next);

    // Dispatch custom event for other scripts to listen
    window.dispatchEvent(new CustomEvent('theme-changed', { detail: { theme: next } }));
  }

  // Setup toggle button
  function setupToggleButton() {
    const btn = document.getElementById('theme-toggle-btn');
    if (btn) {
      btn.addEventListener('click', toggleTheme);
      updateToggleButtonLabel();

      // Listen for theme changes to update button label
      window.addEventListener('theme-changed', updateToggleButtonLabel);
    }
  }

  function updateToggleButtonLabel() {
    const btn = document.getElementById('theme-toggle-btn');
    if (btn) {
      const current = getCurrentTheme();
      btn.textContent = current === 'dark' ? '☀️ light' : '🌙 dark';
    }
  }

  // Initialize on DOMContentLoaded
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', function() {
      init();
      setupToggleButton();
    });
  } else {
    init();
    setupToggleButton();
  }

  // Expose to global scope for testing
  window.ThemeToggle = {
    toggle: toggleTheme,
    set: applyTheme,
    get: getCurrentTheme,
  };
})();