setmode.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. /**
  2. * Set the color mode on the `<html/>` element and in local storage.
  3. *
  4. * @param mode {"dark" | "light"} UI color mode.
  5. */
  6. function setMode(mode) {
  7. document.documentElement.setAttribute("data-bs-theme", mode);
  8. localStorage.setItem("netbox-color-mode", mode);
  9. }
  10. /**
  11. * Determine the best initial color mode to use prior to rendering.
  12. */
  13. function initMode() {
  14. try {
  15. // Determine the configured color mode, if any
  16. var clientMode = localStorage.getItem("netbox-color-mode");
  17. // Detect browser preference, if set
  18. var preferDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
  19. var preferLight = window.matchMedia("(prefers-color-scheme: light)").matches;
  20. // Use the selected color mode, if any
  21. if (clientMode !== null) {
  22. return setMode(clientMode, false);
  23. }
  24. // Fall back to the mode preferred by the browser, if specified
  25. if (preferDark) {
  26. return setMode("dark", true);
  27. }
  28. else if (preferLight) {
  29. return setMode("light", true);
  30. }
  31. } catch (error) {
  32. // In the event of an error, log it to the console and set the mode to light mode.
  33. console.error(error);
  34. }
  35. // Default to light mode
  36. return setMode("light", true);
  37. }