Created
September 28, 2023 15:53
-
-
Save intrnl/643d174199ee07fecc054ccebcdf92b3 to your computer and use it in GitHub Desktop.
Solid.js media query
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
import { type Accessor, createSignal, onCleanup } from 'solid-js'; | |
interface MediaStore { | |
/** State backing */ | |
a: Accessor<boolean>; | |
/** Amount of subscriptions */ | |
n: number; | |
/** Cleanup function */ | |
c: () => void; | |
} | |
const map: Record<string, MediaStore> = {}; | |
export const useMediaQuery = (query: string): Accessor<boolean> => { | |
let media = map[query]; | |
if (!media) { | |
const matcher = window.matchMedia(query); | |
const [state, setState] = createSignal(matcher.matches); | |
const callback = () => setState(matcher.matches); | |
matcher.addEventListener('change', callback); | |
media = map[query] = { | |
n: 0, | |
a: state, | |
c: () => { | |
if (--media.n < 1) { | |
delete map[query]; | |
matcher.removeEventListener('change', callback); | |
} | |
}, | |
}; | |
} | |
media.n++; | |
onCleanup(media.c); | |
return media.a; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
App theming example