themeLoader.js 984 B

1234567891011121314151617181920212223242526272829303132
  1. const DEFAULT_THEME_FETCH_TIMEOUT_MS = 5000
  2. export async function applyThemeStyles (themePreference = '') {
  3. let themeStyle = document.getElementById('theme-style')
  4. if (!themeStyle) {
  5. themeStyle = document.createElement('style')
  6. themeStyle.id = 'theme-style'
  7. themeStyle.type = 'text/css'
  8. document.head.appendChild(themeStyle)
  9. }
  10. const themeUrl = themePreference && themePreference !== ''
  11. ? `/custom-webui/themes/${encodeURIComponent(themePreference)}/theme.css`
  12. : '/theme.css'
  13. const response = await fetch(themeUrl, {
  14. cache: 'no-store',
  15. signal: AbortSignal.timeout(DEFAULT_THEME_FETCH_TIMEOUT_MS)
  16. })
  17. if (!response.ok) {
  18. throw new Error(`theme fetch failed: ${response.status}`)
  19. }
  20. const css = await response.text()
  21. themeStyle.textContent = `@layer theme { ${css} }`
  22. document.body.setAttribute('loaded-theme', themeUrl)
  23. }
  24. export function getStoredThemePreference () {
  25. return localStorage.getItem('olivetin-theme') || ''
  26. }