feat(docs): add bilingual package documentation site
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
---
|
||||
title: 主题偏好示例
|
||||
description: 构建完整的亮色、暗色和跟随系统主题偏好流程。
|
||||
order: 30
|
||||
toc:
|
||||
- id: define-theme-mode
|
||||
title: 定义主题模式
|
||||
- id: apply-the-theme
|
||||
title: 应用主题
|
||||
- id: render-a-control
|
||||
title: 渲染控件
|
||||
---
|
||||
|
||||
## 定义主题模式 {#define-theme-mode}
|
||||
|
||||
```ts
|
||||
import "@workspace/preferences"
|
||||
|
||||
declare module "@workspace/preferences" {
|
||||
interface PreferencesCustom {
|
||||
"theme-mode": "light" | "dark" | "system"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
在服务端读取 Cookie,并通过 `initialPreferences` 传入解析后的值,使服务端标记和水合过程使用同一个快照。
|
||||
|
||||
## 应用主题 {#apply-the-theme}
|
||||
|
||||
```tsx
|
||||
const themeEffects = [
|
||||
{
|
||||
layoutEffect: ({ preferences }) => {
|
||||
const systemDark = window.matchMedia(
|
||||
"(prefers-color-scheme: dark)"
|
||||
).matches
|
||||
const dark =
|
||||
preferences["theme-mode"] === "dark" ||
|
||||
(preferences["theme-mode"] === "system" && systemDark)
|
||||
|
||||
document.documentElement.classList.toggle("dark", dark)
|
||||
document.documentElement.style.colorScheme = dark ? "dark" : "light"
|
||||
},
|
||||
},
|
||||
] satisfies readonly PreferenceEffect[]
|
||||
```
|
||||
|
||||
## 渲染控件 {#render-a-control}
|
||||
|
||||
```tsx
|
||||
function ThemeModeSelect() {
|
||||
const [themeMode, setThemeMode] = usePreference("theme-mode")
|
||||
|
||||
return (
|
||||
<select
|
||||
value={themeMode}
|
||||
onChange={(event) =>
|
||||
setThemeMode(event.currentTarget.value as typeof themeMode)
|
||||
}
|
||||
>
|
||||
<option value="light">亮色</option>
|
||||
<option value="dark">暗色</option>
|
||||
<option value="system">跟随系统</option>
|
||||
</select>
|
||||
)
|
||||
}
|
||||
```
|
||||
Reference in New Issue
Block a user