Becklyn / mojave

A library of commonly used JavaScript tools and helpers by Becklyn
BSD 3-Clause "New" or "Revised" License
5 stars 3 forks source link

add media query listener #235

Closed mangoischke closed 5 years ago

mangoischke commented 5 years ago

update mediaQuery and it’s test to matchMediaQuery

Q A
Bug fix? no
New feature? yes
Improvement? no
BC breaks? no
Deprecations? no
Docs PR missing
apfelbox commented 5 years ago

I might have an idea for a slightly different implementation / extension, so please have some patience.

apfelbox commented 5 years ago

So I finally was able to add my integration. I pushed it in this PR, to see the changes.

The idea is the following: get away from every component having its own media query, but instead having a single:

lib/media-queries.ts:

export const onContentWidth = mediaQueryMatcher("screen and (min-width: 1128px");
export const onStructureWidth = mediaQueryMatcher("screen and (min-width: 1440px");
// ...

And every component can then hook into these global media queries. You would have the definitions in a global file anyway, so we can just put the complete matcher there.

Usage for example in a hook:

let [isContentWidth, setContentWidth] = useState(onContentWidth.matches());

useEffect(() => {
    onContentWidth.on(setContentWidth);
    return () => onContentWidth.off(setContentWidth);
}, []);
apfelbox commented 5 years ago

I also added support for onOff(), so the example above can be written as:

let [isContentWidth, setContentWidth] = useState(onContentWidth.matches());

useEffect(() => onContentWidth.onOff(setContentWidth), []);