Sha256: 8ae90b88b74053ad3aafd232e824b59d19f61fff15a0ff90f61b055abc191170

Contents?: true

Size: 1.21 KB

Versions: 14

Compression:

Stored size: 1.21 KB

Contents

import Rails from '@rails/ujs';

const THEME_KEY = "theme";
const darkModeMedia = window.matchMedia('(prefers-color-scheme: dark)');

const setTheme = () => {
  // On page load or when changing themes, best to add inline in `head` to avoid FOUC
  if (localStorage.getItem(THEME_KEY) === 'dark' || (!(THEME_KEY in localStorage) && darkModeMedia.matches)) {
    document.documentElement.classList.add('dark');
  } else {
    document.documentElement.classList.remove('dark');
  }
}

// Detect when user changes their system level preference to set theme.
darkModeMedia.addEventListener("change", setTheme);

// When the page loads, set theme. By default, uses the system preference.
document.addEventListener("DOMContentLoaded", setTheme);

// If user deletes the Local Storage key, then re-apply theme.
window.addEventListener("storage", (event) => {
  if (event.key === THEME_KEY) {
    setTheme()
  }
});

const toggleTheme = () => {
  if (localStorage.getItem(THEME_KEY) === 'dark' || (!(THEME_KEY in localStorage) && darkModeMedia.matches)) {
    localStorage.setItem(THEME_KEY, 'light');
  } else {
    localStorage.setItem(THEME_KEY, 'dark');
  }
  setTheme();
};

Rails.delegate(document, ".dark-mode-toggle", "click", toggleTheme);

Version data entries

14 entries across 14 versions & 1 rubygems

Version Path
activeadmin-4.0.0.beta14 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta13 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta12 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta11 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta10 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta9 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta8 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta7 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta6 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta5 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta4 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta3 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta2 app/javascript/active_admin/features/dark_mode_toggle.js
activeadmin-4.0.0.beta1 app/javascript/active_admin/features/dark_mode_toggle.js