mirror of
https://github.com/d0zingcat/NotionNext.git
synced 2026-05-17 23:16:50 +00:00
使用cookie管理会话主题,并修复深色主题初始化的BUG
This commit is contained in:
39
lib/theme.js
39
lib/theme.js
@@ -1,5 +1,5 @@
|
||||
import { useContext, createContext, useState, useEffect } from 'react'
|
||||
import localStorage from 'localStorage'
|
||||
import { useContext, createContext, useState, useEffect, useRef } from 'react'
|
||||
import cookie from 'react-cookies'
|
||||
|
||||
const ThemeContext = createContext()
|
||||
|
||||
@@ -10,21 +10,38 @@ const ThemeContext = createContext()
|
||||
* @constructor
|
||||
*/
|
||||
export function ThemeProvider ({ children }) {
|
||||
// 用户自定义主题设置在变量中
|
||||
const userTheme = localStorage.getItem('theme')
|
||||
const [theme, changeTheme] = useState(userTheme)
|
||||
const [theme, changeTheme] = useState(loadUserThemeFromCookies())
|
||||
|
||||
// 由于Server采用服务端静态渲染,无法获取前端Cookie配置,故在渲染hooks中做初始化主题
|
||||
useEffect(() => {
|
||||
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
if (prefersDarkMode) {
|
||||
changeTheme('dark')
|
||||
localStorage.setItem('theme', 'dark')
|
||||
} else {
|
||||
changeTheme(userTheme)
|
||||
// 若用户当前会话无指定主题,将根据深色偏好及访问时间决定默认主题
|
||||
if (!theme) {
|
||||
const date = new Date()
|
||||
const prefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches
|
||||
const useDark = prefersDarkMode || (date.getHours() >= 18 || date.getHours() < 6)
|
||||
if (useDark) {
|
||||
changeTheme('dark')
|
||||
saveTheme('dark')
|
||||
}
|
||||
}
|
||||
|
||||
const baseLayoutClass = document.getElementById('wrapper').classList
|
||||
if (!baseLayoutClass.contains(theme)) {
|
||||
baseLayoutClass.add(theme)
|
||||
}
|
||||
})
|
||||
|
||||
return (
|
||||
<ThemeContext.Provider value={{ theme, changeTheme }}>{children}</ThemeContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export const loadUserThemeFromCookies = () => {
|
||||
return cookie.load('theme')
|
||||
}
|
||||
|
||||
export const saveTheme = (newTheme) => {
|
||||
cookie.save('theme', newTheme, { path: '/' })
|
||||
}
|
||||
|
||||
export const useTheme = () => useContext(ThemeContext)
|
||||
|
||||
Reference in New Issue
Block a user