💡Feature Request: support setting system theme
Is your feature request related to a problem? Please describe.
I want to have a "System" or "Automatic" option in my theme selector. As in, I want the user to be able to select it. Right now if I call document.documentElement.attributes.getNamedItem('data-theme')?.value I always get light or dark, the current inferred theme.
Describe the solution you'd like
I would like a way of getting the fact that there is no setting, so the theme is inferred. That way my "System" <option> would be selected.
Describe alternatives you've considered Not having a system option?
Additional context n/a
hey! thanks for the issue, we should definitely make this possible. I probably won't personally have time to get to this for a couple of weeks, but I'll definitely get to it as soon as possible. I would happily review a PR if you're open to making one, the change should be as simple as updating this line to clear the theme (set it to '') instead of writing the resolved theme.
I also have a simple snippet I'm using on another non-Astro project that works this way that may be easier to adapt in the meantime.
Thinking through this further, I'm actually not sure if updating the behavior of the data-theme attribute is the right approach. If you're using [data-theme=dark] in your CSS as suggested in the README, then the attribute needs to be the actual inferred theme. Changing it to be "system" would mean your dark mode styles don't apply even if they should because the OS preference is dark.
2 ideas I have here, would love your thoughts:
- Add a second attribute you can read that is the actual preference,
"light" | "dark" | "system" - You can read the preference from
localStorage(will be null for system)
I do think it should be possible to implement a select-based toggle, and it seems like it's currently not straightforward, so we can use this issue to track that. May also include addressing #42 or documenting the workaround.
Yeah I think the way this is usually handled is to have a second thing you pull up, the preference. So, assuming you want to keep things as attributes on the data element, you'd have:
System / Default:
color-scheme: light dark
data-theme=<light or dark, from system>
data-theme-preference=system
Light:
color-scheme: light
data-theme=light
data-theme-preference=light
Dark
color-scheme: dark
data-theme=dark
data-theme-preference=dark
So like, data-theme is the resolved theme, always either light or dark, and data-theme-preference is the actual user setting, always either light, dark, or system.