diff --git a/deno.json b/deno.json index ed6edfb..6636330 100644 --- a/deno.json +++ b/deno.json @@ -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", @@ -10,6 +10,8 @@ }, "license": "Apache-2.0", "imports": { + "@preact/signals": "npm:@preact/signals@1.3.0", + "preact/hooks": "npm:preact@10.24.3/hooks" }, "fmt": { "options": { diff --git a/mod.ts b/mod.ts index b150b9a..a278bd6 100644 --- a/mod.ts +++ b/mod.ts @@ -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, @@ -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 +}