A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
---
// SPDX-License-Identifier: AGPL-3.0-or-later
import Select from '@astrojs/starlight/components/Select.astro';
---
<starlight-theme-select>
<Select
icon="moon"
label={Astro.locals.t('themeSelect.accessibleLabel')}
options={[
{label: Astro.locals.t('themeSelect.dark'), selected: true, value: 'dark'},
{label: Astro.locals.t('themeSelect.light'), selected: false, value: 'light'},
{label: Astro.locals.t('themeSelect.auto'), selected: false, value: 'auto'},
]}
width="6.25em"
/>
</starlight-theme-select>
<script is:inline>
StarlightThemeProvider.updatePickers();
</script>
<script>
type Theme = 'auto' | 'dark' | 'light';
declare const StarlightThemeProvider: {readonly updatePickers: (theme?: Theme) => void};
const storageKey = 'starlight-theme';
const parseTheme = (theme: unknown): Theme =>
theme === 'auto' || theme === 'dark' || theme === 'light' ? theme : 'dark';
const loadTheme = (): Theme =>
parseTheme(typeof localStorage !== 'undefined' && localStorage.getItem(storageKey));
function storeTheme(theme: Theme): void {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(storageKey, theme);
}
}
const getPreferredColorScheme = (): Theme => (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
function onThemeChange(theme: Theme): void {
StarlightThemeProvider.updatePickers(theme);
document.documentElement.dataset.theme = theme === 'auto' ? getPreferredColorScheme() : theme;
storeTheme(theme);
}
matchMedia('(prefers-color-scheme: light)').addEventListener('change', () => {
if (loadTheme() === 'auto') onThemeChange('auto');
});
class StarlightThemeSelect extends HTMLElement {
constructor() {
super();
onThemeChange(loadTheme());
this.querySelector('select')?.addEventListener('change', (e) => {
if (e.currentTarget instanceof HTMLSelectElement) {
onThemeChange(parseTheme(e.currentTarget.value));
}
});
}
}
customElements.define('starlight-theme-select', StarlightThemeSelect);
</script>