Skip to content

Commit

Permalink
fix: use legacy methods for old browsers (#110)
Browse files Browse the repository at this point in the history
* fix: use legacy methods for old browsers

* chore: bump pnpm
  • Loading branch information
capJavert authored Apr 3, 2024
1 parent 16d2b62 commit cf5728e
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,5 +53,5 @@
"engines": {
"node": ">=16.0.0"
},
"packageManager": "pnpm@8.2.0"
"packageManager": "pnpm@8.6.12"
}
26 changes: 26 additions & 0 deletions packages/react/src/hooks/useMediaQuery/useMediaQuery.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,4 +126,30 @@ describe('useMediaQuery', () => {

expect(matchMediaSpy).toHaveBeenCalledTimes(2)
})

it('should use fallback to listener polyfill for old browsers', () => {
const onChangeSpy = jest.fn()
const offChangeSpy = jest.fn()
const matchMediaLegacy = jest.fn((query: string) => {
return {
matches: query.includes('max-width: 600px'),
media: query,
// eslint-disable-next-line unicorn/no-null
onchange: null,
addListener: onChangeSpy,
removeListener: offChangeSpy
}
})
global.matchMedia = matchMediaLegacy as never

const { unmount } = renderHook(() => useMediaQuery('(max-width: 600px)'))

expect(matchMediaLegacy).toHaveBeenCalledTimes(1)
expect(onChangeSpy).toHaveBeenCalledTimes(1)
expect(offChangeSpy).toHaveBeenCalledTimes(0)

unmount()

expect(offChangeSpy).toHaveBeenCalledTimes(1)
})
})
12 changes: 10 additions & 2 deletions packages/react/src/hooks/useMediaQuery/useMediaQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,21 @@ const getMediaQueryInstance = (query: string): TMediaQueryPoolItem => {
for (const callback of callbacks) callback(event)
}

mediaQuery.addEventListener('change', handleChange)
if (typeof mediaQuery.addEventListener === 'function') {
mediaQuery.addEventListener('change', handleChange)
} else {
mediaQuery.addListener(handleChange)
}

mediaQueryPool[query] = {
mediaQuery,
callbacks,
removeListener: () => {
mediaQuery.removeEventListener('change', handleChange)
if (typeof mediaQuery.removeEventListener === 'function') {
mediaQuery.removeEventListener('change', handleChange)
} else {
mediaQuery.removeListener(handleChange)
}
}
}
}
Expand Down

0 comments on commit cf5728e

Please sign in to comment.