summaryrefslogtreecommitdiff
path: root/src/components/common/ApplyColorMode.astro
blob: d0d97fe57fd3c819f961c730624b4c06436f8d31 (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
---
import { UI } from 'astrowind:config';

// TODO: This code is temporary
---

<script is:inline define:vars={{ defaultTheme: UI.theme || 'system' }}>
  function applyTheme(theme) {
    if (theme === 'dark') {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
    const matches = document.querySelectorAll('[data-aw-toggle-color-scheme] > input');

    if (matches && matches.length) {
      matches.forEach((elem) => {
        elem.checked = theme !== 'dark';
      });
    }
  }

  if ((defaultTheme && defaultTheme.endsWith(':only')) || (!localStorage.theme && defaultTheme !== 'system')) {
    applyTheme(defaultTheme.replace(':only', ''));
  } else if (
    localStorage.theme === 'dark' ||
    (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)
  ) {
    applyTheme('dark');
  } else {
    applyTheme('light');
  }
</script>