Skip to content
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

fix(dark-mode): avoid localStorage overwrite by system dark mode status #636

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/old-cows-mix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"usehooks-ts": patch
---

Fix `useDarkMode` to avoid os dark mode overwriting localStorage
25 changes: 25 additions & 0 deletions packages/usehooks-ts/src/useDarkMode/useDarkMode.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,4 +124,29 @@ describe('useDarkMode()', () => {

expect(result.current.isDarkMode).toBe(false)
})

it('should update dark mode when OS preference changes', () => {
const { updateMatches } = mockMatchMedia(false)
const { result, rerender } = renderHook(() => useDarkMode())
expect(result.current.isDarkMode).toBe(false)
updateMatches(true)
rerender() // trigger `useIsomorphicLayoutEffect`
expect(result.current.isDarkMode).toBe(true)
})

it('should prioritize localStorage value over OS dark mode on page load', () => {
window.localStorage.setItem('custom-key', JSON.stringify(false))

mockMatchMedia(true)
const { result } = renderHook(() =>
useDarkMode({ localStorageKey: 'custom-key', initializeWithValue: true }),
)
expect(result.current.isDarkMode).toBe(false)

act(() => {
result.current.toggle()
})
expect(result.current.isDarkMode).toBe(true)
expect(window.localStorage.getItem('custom-key')).toBe(JSON.stringify(true))
})
})
4 changes: 3 additions & 1 deletion packages/usehooks-ts/src/useDarkMode/useDarkMode.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useIsMounted } from '../useIsMounted'
import { useIsomorphicLayoutEffect } from '../useIsomorphicLayoutEffect'
import { useLocalStorage } from '../useLocalStorage'
import { useMediaQuery } from '../useMediaQuery'
Expand Down Expand Up @@ -68,8 +69,9 @@ export function useDarkMode(options: DarkModeOptions = {}): DarkModeReturn {
)

// Update darkMode if os prefers changes
const allowDarkOSChange = useIsMounted()
useIsomorphicLayoutEffect(() => {
if (isDarkOS !== isDarkMode) {
if (allowDarkOSChange() && isDarkOS !== isDarkMode) {
setDarkMode(isDarkOS)
}
}, [isDarkOS])
Expand Down
66 changes: 52 additions & 14 deletions packages/usehooks-ts/tests/mocks.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,63 @@
/**
* Mocks the matchMedia API
* @param {boolean} matches - True for dark, false for light
* Mocks the matchMedia API.
* @param {boolean} matches - True for dark, false for light.
* @returns {object} An object with a function to change the matches value.
* @example
* mockMatchMedia(false)
*/
export const mockMatchMedia = (matches: boolean): void => {
export const mockMatchMedia = (matches: boolean) => {
type EventListener = (event: Event) => void
const eventListeners: Record<string, EventListener[]> = {}

const matchMedia = (query: string) => ({
get matches() {
return matches
},
media: query,
onchange: null,
addEventListener: vitest
.fn()
.mockImplementation((type: string, listener: EventListener) => {
if (!eventListeners[type]) eventListeners[type] = []
eventListeners[type].push(listener)
}),
removeEventListener: vitest
.fn()
.mockImplementation((type: string, listener: EventListener) => {
eventListeners[type] = eventListeners[type]?.filter(l => l !== listener)
}),
dispatchEvent: vitest.fn().mockImplementation((event: Event) => {
eventListeners[event.type]?.forEach(listener => {
listener(event)
})
return true
}),
})

Object.defineProperty(window, 'matchMedia', {
writable: true,
value: vitest.fn().mockImplementation(query => ({
matches,
media: query,
onchange: null,
addEventListener: vitest.fn(),
removeEventListener: vitest.fn(),
dispatchEvent: vitest.fn(),
})),
value: vitest.fn().mockImplementation(matchMedia),
})

return {
/**
* Updates the matches value. This will trigger the change event.
* @param m - The new value for matches.
* @example
* mockMatchMedia(false).updateMatches(true)
*/
updateMatches: (m: boolean) => {
matches = m
eventListeners.change?.forEach(listener => {
listener(new Event('change'))
})
},
}
}

/**
* Mocks the Storage API
* @param {'localStorage' | 'sessionStorage'} name - The name of the storage to mock
* Mocks the Storage API.
* @param {'localStorage' | 'sessionStorage'} name - The name of the storage to mock.
* @example
* mockStorage('localStorage')
* // Then use window.localStorage as usual (it will be mocked)
Expand All @@ -38,10 +75,11 @@ export const mockStorage = (name: 'localStorage' | 'sessionStorage'): void => {
}

setItem(key: string, value: unknown) {
this.store[key] = value + ''
this.store[key] = String(value)
}

removeItem(key: string) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this.store[key]
}
}
Expand Down