Skip to content

Commit

Permalink
useTheme to get theme
Browse files Browse the repository at this point in the history
  • Loading branch information
KishiTheMechanic committed Oct 28, 2024
1 parent 3cd7247 commit d8359ed
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
4 changes: 3 additions & 1 deletion deno.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@elsoul/fresh-theme",
"version": "1.0.3",
"version": "1.0.4",
"description": "Theme Module for Fresh v2 App.",
"runtimes": ["deno", "browser"],
"exports": "./mod.ts",
Expand All @@ -10,6 +10,8 @@
},
"license": "Apache-2.0",
"imports": {
"@preact/signals": "npm:@preact/[email protected]",
"preact/hooks": "npm:[email protected]/hooks"
},
"fmt": {
"options": {
Expand Down
30 changes: 30 additions & 0 deletions mod.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { useSignal } from '@preact/signals'
import { useEffect } from 'preact/hooks'

/**
* Theme module for setting up light or dark modes in a Fresh app.
* Provides a default dark mode script, a default light mode script,
Expand Down Expand Up @@ -67,3 +70,30 @@ export function setTheme(newTheme: 'dark' | 'light'): void {
document.documentElement.classList.toggle('dark', newTheme === 'dark')
}
}

/**
* Custom hook to manage the theme (light or dark) based on localStorage.
* Returns the current theme value.
*
* @returns {'dark' | 'light'} The current theme.
*/
export function useTheme(): 'dark' | 'light' {
const theme = useSignal<'dark' | 'light'>(
localStorage.getItem('theme') as 'dark' | 'light' || 'dark',
)

useEffect(() => {
const handleStorageChange = () => {
theme.value = localStorage.getItem('theme') as 'dark' | 'light' || 'dark'
}

globalThis.addEventListener('themeLocalStorage', handleStorageChange)

// Cleanup the event listener on unmount
return () => {
globalThis.removeEventListener('themeLocalStorage', handleStorageChange)
}
}, [])

return theme.value
}

0 comments on commit d8359ed

Please sign in to comment.