-
Notifications
You must be signed in to change notification settings - Fork 2.8k
feat: add useTheme #2617
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+236
−1
Merged
feat: add useTheme #2617
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
b70cb75
feat: useTheme
ianzone e17317c
test: useTheme
ianzone 3c5a026
feat: useTheme add localStorageKey
ianzone 1322db3
docs: useTheme add localStorageKey
ianzone 15b2681
Update packages/hooks/src/useTheme/index.en-US.md
ianzone 61a8165
Update packages/hooks/src/useTheme/index.ts
ianzone d3c8c2c
fix: missing localStorage.getItem(localStorageKey)
ianzone fc98b12
docs: useTheme add Params
ianzone a782819
feat: useTheme add default props
ianzone 737957f
Update packages/hooks/src/useTheme/index.zh-CN.md
liuyib cca8d27
Update packages/hooks/src/useTheme/index.zh-CN.md
liuyib 8b97c54
Update packages/hooks/src/useTheme/index.en-US.md
liuyib 87f8076
style: optimize
liuyib 2aabd37
feat: useTheme add onChange callback
ianzone c8a9cc5
Merge branch 'master' into pr/2617
crazylxr 2d2f1d6
feat: remove onChange
ianzone File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -31,6 +31,7 @@ export const menus = [ | |
'useCounter', | ||
'useTextSelection', | ||
'useWebSocket', | ||
'useTheme', | ||
], | ||
}, | ||
{ | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
Object.defineProperty(window, 'matchMedia', { | ||
writable: true, | ||
value: jest.fn().mockImplementation((query) => ({ | ||
matches: false, | ||
media: query, | ||
onchange: null, | ||
addListener: jest.fn(), // deprecated | ||
removeListener: jest.fn(), // deprecated | ||
addEventListener: jest.fn(), | ||
removeEventListener: jest.fn(), | ||
dispatchEvent: jest.fn(), | ||
})), | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import { act, renderHook } from '@testing-library/react'; | ||
import useTheme from '../index'; | ||
|
||
describe('useTheme', () => { | ||
test('themeMode init', () => { | ||
const { result } = renderHook(useTheme); | ||
expect(result.current.themeMode).toBe('system'); | ||
}); | ||
|
||
test('setThemeMode light', () => { | ||
const { result } = renderHook(useTheme); | ||
act(() => result.current.setThemeMode('light')); | ||
expect(result.current.theme).toBe('light'); | ||
expect(result.current.themeMode).toBe('light'); | ||
}); | ||
|
||
test('setThemeMode dark', () => { | ||
const { result } = renderHook(useTheme); | ||
act(() => result.current.setThemeMode('dark')); | ||
expect(result.current.theme).toBe('dark'); | ||
expect(result.current.themeMode).toBe('dark'); | ||
}); | ||
|
||
test('setThemeMode system', () => { | ||
const { result } = renderHook(useTheme); | ||
act(() => result.current.setThemeMode('system')); | ||
expect(result.current.themeMode).toBe('system'); | ||
}); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,47 @@ | ||
/** | ||
* title: Basic usage | ||
* desc: The 'theme' is the system display theme ("light" or "dark"), the 'themeMode' can set 'theme' to "light" or "dark" or follow the system setting. | ||
* | ||
* title.zh-CN: 基础用法 | ||
* desc.zh-CN: 'theme' 为系统当前显示主题("light" 或 "dark"),'themeMode' 为当前主题设置("light" 或 "dark" 或 "system")。 | ||
*/ | ||
|
||
import { useTheme } from 'ahooks'; | ||
import React from 'react'; | ||
|
||
export default () => { | ||
const { theme, themeMode, setThemeMode } = useTheme({ | ||
localStorageKey: 'themeMode', | ||
}); | ||
|
||
return ( | ||
<> | ||
<div>theme: {theme}</div> | ||
<div>themeMode: {themeMode}</div> | ||
<button | ||
type="button" | ||
onClick={() => { | ||
setThemeMode('dark'); | ||
}} | ||
> | ||
use dark theme | ||
</button> | ||
<button | ||
type="button" | ||
onClick={() => { | ||
setThemeMode('light'); | ||
}} | ||
> | ||
use light theme | ||
</button> | ||
<button | ||
type="button" | ||
onClick={() => { | ||
setThemeMode('system'); | ||
}} | ||
> | ||
follow the system | ||
</button> | ||
</> | ||
); | ||
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
--- | ||
nav: | ||
path: /hooks | ||
--- | ||
|
||
# useTheme | ||
|
||
This hook is used to get and set the theme, and store the `themeMode` into `localStorage`. | ||
|
||
## Examples | ||
|
||
### Default usage | ||
|
||
<code src="./demo/demo1.tsx" /> | ||
|
||
## API | ||
|
||
```typescript | ||
const { theme, themeMode, setThemeMode } = useTheme({ | ||
localStorageKey?: string; | ||
}); | ||
``` | ||
|
||
### Params | ||
|
||
| Property | Description | Type | Default | | ||
| --------------- | ----------------------------------------------------- | -------- | --------- | | ||
| localStorageKey | The key in localStorage to store selected theme mode | `string` | `undefined` | | ||
|
||
### Result | ||
|
||
| Property | Description | Type | Default | | ||
| ------------ | --------------------- | ----------------------------------------------- | ------------------------------------------------------------------------------------- | | ||
| theme | current display theme | `"light" \| "dark"` | if themeMode is "system" then equals to system setting,otherwise equals to themeMode | | ||
| themeMode | selected theme mode | `"light" \| "dark" \| "system"` | equals to localStorage "themeMode", otherwise equals to "system" | | ||
| setThemeMode | select theme mode | `(mode: "light" \| "dark" \| "system") => void` | | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
import { useEffect, useState } from 'react'; | ||
import useMemoizedFn from '../useMemoizedFn'; | ||
|
||
export enum ThemeMode { | ||
LIGHT = 'light', | ||
DARK = 'dark', | ||
SYSTEM = 'system', | ||
} | ||
|
||
export type ThemeModeType = `${ThemeMode}`; | ||
|
||
export type ThemeType = 'light' | 'dark'; | ||
|
||
const matchMedia = window.matchMedia('(prefers-color-scheme: dark)'); | ||
|
||
function useCurrentTheme() { | ||
const [theme, setTheme] = useState<ThemeType>(() => { | ||
const init = matchMedia.matches ? ThemeMode.DARK : ThemeMode.LIGHT; | ||
return init; | ||
}); | ||
|
||
useEffect(() => { | ||
const onThemeChange: MediaQueryList['onchange'] = (event) => { | ||
if (event.matches) { | ||
setTheme(ThemeMode.DARK); | ||
} else { | ||
setTheme(ThemeMode.LIGHT); | ||
} | ||
}; | ||
|
||
matchMedia.addEventListener('change', onThemeChange); | ||
|
||
return () => { | ||
matchMedia.removeEventListener('change', onThemeChange); | ||
}; | ||
}, []); | ||
|
||
return theme; | ||
} | ||
|
||
type Options = { | ||
localStorageKey?: string; | ||
}; | ||
|
||
export default function useTheme(options: Options = {}) { | ||
const { localStorageKey } = options; | ||
|
||
const [themeMode, setThemeMode] = useState<ThemeModeType>(() => { | ||
ianzone marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const preferredThemeMode = | ||
localStorageKey?.length && (localStorage.getItem(localStorageKey) as ThemeModeType | null); | ||
|
||
return preferredThemeMode ? preferredThemeMode : ThemeMode.SYSTEM; | ||
}); | ||
|
||
const setThemeModeWithLocalStorage = (mode: ThemeModeType) => { | ||
setThemeMode(mode); | ||
|
||
if (localStorageKey?.length) { | ||
localStorage.setItem(localStorageKey, mode); | ||
} | ||
}; | ||
|
||
const currentTheme = useCurrentTheme(); | ||
const theme = themeMode === ThemeMode.SYSTEM ? currentTheme : themeMode; | ||
|
||
return { | ||
theme, | ||
themeMode, | ||
setThemeMode: useMemoizedFn(setThemeModeWithLocalStorage), | ||
}; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
--- | ||
nav: | ||
path: /hooks | ||
--- | ||
|
||
# useTheme | ||
|
||
获取并设置当前主题,并将 `themeMode` 存储在 `localStorage` 中。 | ||
|
||
## 代码演示 | ||
|
||
### 基础用法 | ||
|
||
<code src="./demo/demo1.tsx" /> | ||
|
||
## API | ||
|
||
```typescript | ||
const { theme, themeMode, setThemeMode } = useTheme({ | ||
localStorageKey?: string; | ||
}); | ||
``` | ||
ianzone marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
### 参数 | ||
|
||
| 参数 | 说明 | 类型 | 默认值 | | ||
| --------------- | ------------------------------------ | -------- | --------- | | ||
| localStorageKey | localStorage 中用于存放主题模式的键 | `string` | `undefined` | | ||
|
||
### 返回值 | ||
|
||
| 值 | 说明 | 类型 | 默认值 | | ||
| ------------ | -------------- | ----------------------------------------------- | ---------------------------------------------------------------------- | | ||
| theme | 当前显示的主题 | `"light" \| "dark"` | 若 themeMode 为 "system" 则为系统当前使用主题,否则与 themeMode 值相同 | | ||
| themeMode | 选择的主题模式 | `"light" \| "dark" \| "system"` | 等于 localStorage "themeMode" 字段的值,否则为 "system" | | ||
| setThemeMode | 选择主题模式 | `(mode: "light" \| "dark" \| "system") => void` | | |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.