https://github.com/lixelv/theme-selector
https://github.com/lixelv/theme-selector
Last synced: 5 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/lixelv/theme-selector
- Owner: lixelv
- License: mit
- Created: 2024-09-04T16:31:08.000Z (almost 2 years ago)
- Default Branch: main
- Last Pushed: 2024-09-04T16:43:40.000Z (almost 2 years ago)
- Last Synced: 2025-02-23T20:52:06.227Z (over 1 year ago)
- Language: TypeScript
- Size: 48.8 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE.md
Awesome Lists containing this project
README
# theme-selector
A simple Svelte store library that lets you switch between light and dark themes, with support for system theme by default.
## Installation
Install the package via npm:
```bash
npm i theme-selector
```
### (Optional) Instant Theme Switch
To ensure the theme is applied instantly on page load (before Svelte mounts), you can add this script to the `` section of your `app.html`. This is especially useful if you're using libraries like ShadCN:
```html
const theme = localStorage.getItem('theme');
let currentTheme;
if (theme === 'system' || !theme) {
currentTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
} else {
currentTheme = theme;
}
if (currentTheme === 'dark') {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
if (!theme) {
localStorage.setItem('theme', 'system');
}
```
## Usage
Import the `theme` store and use it in your components:
```svelte
import { theme } from 'theme-selector';
Your current theme is {$theme}
theme.set('dark')}>Dark
theme.set('light')}>Light
theme.set('system')}>System
```
### Custom Theme Store
You can create a new theme store using the `createThemeStore` function. This allows you to specify a callback function that will be invoked whenever the theme changes (either by system preferences or user selection):
```svelte
import { createThemeStore } from 'theme-selector';
function onThemeChange(theme) {
console.log('Theme changed to:', theme);
}
const theme = createThemeStore(onThemeChange);
The current theme is: {$theme}
```
### Default Behavior with ShadCN
By default, if no callback function is provided to `createThemeStore`, it will automatically update the `html` class to reflect the current theme.
## License
This project is licensed under the MIT License.