add more feature
This commit is contained in:
50
src/hooks/useTheme.ts
Normal file
50
src/hooks/useTheme.ts
Normal file
@@ -0,0 +1,50 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
|
||||
// Cookie utility functions
|
||||
const setCookie = (name: string, value: string, days: number = 365) => {
|
||||
const expires = new Date()
|
||||
expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000))
|
||||
document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/`
|
||||
}
|
||||
|
||||
const getCookie = (name: string): string | null => {
|
||||
const nameEQ = name + "="
|
||||
const ca = document.cookie.split(';')
|
||||
for (let i = 0; i < ca.length; i++) {
|
||||
let c = ca[i]
|
||||
while (c.charAt(0) === ' ') c = c.substring(1, c.length)
|
||||
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length)
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
// Apply theme to document
|
||||
const applyTheme = (theme: 'light' | 'dark') => {
|
||||
document.documentElement.classList.remove('light', 'dark')
|
||||
document.documentElement.classList.add(theme)
|
||||
document.documentElement.setAttribute('data-theme', theme)
|
||||
}
|
||||
|
||||
export const useTheme = () => {
|
||||
const [theme, setTheme] = useState<'light' | 'dark'>('light')
|
||||
|
||||
useEffect(() => {
|
||||
// Get theme from cookie on mount
|
||||
const storedTheme = getCookie('theme') as 'light' | 'dark' | null
|
||||
if (storedTheme) {
|
||||
setTheme(storedTheme)
|
||||
applyTheme(storedTheme)
|
||||
} else {
|
||||
// Default to light theme and apply it
|
||||
applyTheme('light')
|
||||
}
|
||||
}, [])
|
||||
|
||||
const changeTheme = (newTheme: 'light' | 'dark') => {
|
||||
setTheme(newTheme)
|
||||
setCookie('theme', newTheme)
|
||||
applyTheme(newTheme)
|
||||
}
|
||||
|
||||
return { theme, changeTheme }
|
||||
}
|
||||
Reference in New Issue
Block a user