colorModeBootstrap.js 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*!
  2. * Color mode toggler for Bootstrap's docs (https://getbootstrap.com/)
  3. * Copyright 2011-2024 The Bootstrap Authors
  4. * Licensed under the Creative Commons Attribution 3.0 Unported License.
  5. */
  6. (() => {
  7. 'use strict'
  8. const getStoredTheme = () => localStorage.getItem('theme')
  9. const setStoredTheme = theme => localStorage.setItem('theme', theme)
  10. const getPreferredTheme = () => {
  11. const storedTheme = getStoredTheme()
  12. if (storedTheme) {
  13. return storedTheme
  14. }
  15. return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
  16. }
  17. const setTheme = theme => {
  18. if (theme === 'auto') {
  19. document.documentElement.setAttribute('data-bs-theme', (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'))
  20. } else {
  21. document.documentElement.setAttribute('data-bs-theme', theme)
  22. }
  23. }
  24. setTheme(getPreferredTheme())
  25. const showActiveTheme = (theme, focus = false) => {
  26. const themeSwitcher = document.querySelector('#bd-theme')
  27. if (!themeSwitcher) {
  28. return
  29. }
  30. const themeSwitcherText = document.querySelector('#bd-theme-text')
  31. const activeThemeIcon = document.querySelector('.theme-icon-active use')
  32. const btnToActive = document.querySelector(`[data-bs-theme-value="${theme}"]`)
  33. const svgOfActiveBtn = btnToActive.querySelector('svg use').getAttribute('href')
  34. document.querySelectorAll('[data-bs-theme-value]').forEach(element => {
  35. element.classList.remove('active')
  36. element.setAttribute('aria-pressed', 'false')
  37. })
  38. btnToActive.classList.add('active')
  39. btnToActive.setAttribute('aria-pressed', 'true')
  40. activeThemeIcon.setAttribute('href', svgOfActiveBtn)
  41. const themeSwitcherLabel = `${themeSwitcherText.textContent} (${btnToActive.dataset.bsThemeValue})`
  42. themeSwitcher.setAttribute('aria-label', themeSwitcherLabel)
  43. if (focus) {
  44. themeSwitcher.focus()
  45. }
  46. }
  47. window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
  48. const storedTheme = getStoredTheme()
  49. if (storedTheme !== 'light' && storedTheme !== 'dark') {
  50. setTheme(getPreferredTheme())
  51. }
  52. })
  53. window.addEventListener('DOMContentLoaded', () => {
  54. showActiveTheme(getPreferredTheme())
  55. document.querySelectorAll('[data-bs-theme-value]')
  56. .forEach(toggle => {
  57. toggle.addEventListener('click', () => {
  58. const theme = toggle.getAttribute('data-bs-theme-value')
  59. setStoredTheme(theme)
  60. setTheme(theme)
  61. showActiveTheme(theme, true)
  62. })
  63. })
  64. })
  65. })()