Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 10 additions & 30 deletions src/components/ThemeToggle.astro
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const { class: classList } = Astro.props;
</HeaderIcon>

<script>
import { isTheme, type Theme } from '@/types/Theme';
import { isTheme, THEMES, type Theme } from '@/types/Theme';
type ThemeState = Theme | null;

const html = document.documentElement;
Expand Down Expand Up @@ -71,47 +71,27 @@ const { class: classList } = Astro.props;
/**
* 指定されたテーマを適用する
*
* 指定されたテーマを `<html>` のクラスに追加し、 localStorage に保存する
* 指定されたテーマを `<html>` のクラスに追加し、 localStorage に保存する。
* null の場合はクラスと保存値を外し、システム設定に従う
*
* @param theme
*/
const applyTheme = (theme: ThemeState) => {
html.classList.remove('dark', 'light', 'theme-system');

if (theme === 'dark') {
html.classList.add('dark');
html.style.colorScheme = 'dark';
storeTheme('dark');
return;
}

if (theme === 'light') {
html.classList.add('light');
html.style.colorScheme = 'light';
storeTheme('light');
return;
html.classList.remove(...THEMES);
if (theme !== null) {
html.classList.add(theme);
}

html.style.colorScheme = 'light dark';
storeTheme(null);
html.style.colorScheme = theme ?? 'light dark';
storeTheme(theme);
};

/**
* 現在適用されているテーマを <html> のクラスから取得する
*
* 'light' も 'dark' もどちらも適用されていない場合は null を返す
*/
const getCurrentTheme = (): ThemeState => {
if (html.classList.contains('dark')) {
return 'dark';
}

if (html.classList.contains('light')) {
return 'light';
}

return null;
};
const getCurrentTheme = (): ThemeState =>
THEMES.find((theme) => html.classList.contains(theme)) ?? null;

applyTheme(getStoredTheme());

Expand Down
2 changes: 1 addition & 1 deletion src/types/Theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@ export const THEMES = ['light', 'dark'] as const;
export type Theme = (typeof THEMES)[number];

export function isTheme(value: string | null): value is Theme {
return value === 'light' || value === 'dark';
return THEMES.some((theme) => theme === value);
}
12 changes: 12 additions & 0 deletions tests/unit/theme.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { describe, expect, test } from 'vitest';
import { isTheme, THEMES } from '../../src/types/Theme';

describe('isTheme', () => {
test.each(THEMES)('accepts %s', (theme) => {
expect(isTheme(theme)).toBe(true);
});

test.each([null, '', 'system', 'Dark', 'light '])('rejects %j', (value) => {
expect(isTheme(value)).toBe(false);
});
});
Loading