https://github.com/ghostdevv/svelte-kit-theme-switcher-demo
https://github.com/ghostdevv/svelte-kit-theme-switcher-demo
Last synced: 7 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/ghostdevv/svelte-kit-theme-switcher-demo
- Owner: ghostdevv
- Created: 2023-06-12T02:08:36.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2023-10-07T22:20:03.000Z (over 2 years ago)
- Last Synced: 2025-06-12T23:42:09.928Z (9 months ago)
- Language: Svelte
- Size: 34.2 KB
- Stars: 2
- Watchers: 1
- Forks: 0
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Svelte Kit Theme Switcher Demo
Simple theme switcher demo for svelte kit, supports SSR. Run this repo locally to play around with it, or setup using the files below.
## lib/themes.ts
```ts
export type Theme = 'light' | 'dark' | undefined;
export function getDefaultTheme(): Theme {
const { matches } = window.matchMedia('(prefers-color-scheme: dark)');
return matches ? 'dark' : 'light';
}
export function isValidTheme(string: any): string is Theme {
return ['light', 'dark', undefined].includes(string);
}
```
## lib/ThemeSwitcher.svelte
```html
import { getDefaultTheme } from '$lib/themes';
import { page } from '$app/stores';
import cookies from 'js-cookie';
function changeTheme(event: { currentTarget: HTMLSelectElement }) {
const theme = event.currentTarget.value;
if (theme) {
cookies.set('theme', theme, { path: '/' });
document.documentElement.dataset.theme = theme;
} else {
cookies.remove('theme', { path: '/' });
document.documentElement.dataset.theme = getDefaultTheme();
}
}
Auto
Light
Dark
```
## hooks.server.ts
```ts
import { isValidTheme } from '$lib/themes';
export async function handle({ event, resolve }) {
const cookieTheme = event.cookies.get('theme');
event.locals.theme = isValidTheme(cookieTheme) ? cookieTheme : undefined;
return await resolve(event, {
transformPageChunk({ html }) {
if (event.locals.theme) {
html = html.replace('%sveltekit.theme%', event.locals.theme);
}
return html;
},
});
}
```
## +layout.server.ts
```ts
export async function load({ locals }) {
return {
theme: locals.theme,
};
}
```
## app.d.ts
```ts
import type { Theme } from '$lib/themes';
declare global {
namespace App {
interface Locals {
theme: Theme;
}
}
}
export {};
```
## app.html
Add `data-theme="%sveltekit.theme%"` to your `` tag.