@dnb/eufemia
Version:
DNB Eufemia Design System UI Library
95 lines (94 loc) • 2.33 kB
JavaScript
"use client";
import React from 'react';
import Context from "./Context.js";
import { makeMediaQueryList, createMediaQueryListener, onMediaQueryChange, isMatchMediaSupported } from "./MediaQueryUtils.js";
import { Fragment as _Fragment, jsx as _jsx } from "react/jsx-runtime";
export { onMediaQueryChange };
function MediaQuery(props) {
const context = React.useContext(Context);
const listenerRef = React.useRef(null);
const getInitialState = () => {
const state = {
match: null,
mediaQueryList: null
};
if (!isMatchMediaSupported() && props.matchOnSSR) {
state.match = true;
}
if (isMatchMediaSupported()) {
const {
query,
when,
not
} = props;
const {
disabled,
correctRange = true,
log
} = props;
state.mediaQueryList = makeMediaQueryList({
query,
when,
not
}, context?.breakpoints, {
disabled,
correctRange,
log
});
if (state.mediaQueryList?.matches) {
state.match = true;
}
}
return state;
};
const [state, setState] = React.useState(getInitialState);
React.useEffect(() => {
if (listenerRef.current) {
listenerRef.current();
listenerRef.current = null;
}
if (!isMatchMediaSupported()) {
return undefined;
}
const {
query,
when,
not,
disabled,
correctRange = true,
log
} = props;
const mediaQueryList = makeMediaQueryList({
query,
when,
not
}, context?.breakpoints, {
disabled,
correctRange,
log
});
setState({
match: mediaQueryList?.matches,
mediaQueryList
});
if (mediaQueryList) {
listenerRef.current = createMediaQueryListener(mediaQueryList, match => {
setState(prev => ({
...prev,
match
}));
});
}
return () => {
if (listenerRef.current) {
listenerRef.current();
listenerRef.current = null;
}
};
}, [props.query, props.when, props.not, props.disabled, props.correctRange, props.log, context?.breakpoints]);
return _jsx(_Fragment, {
children: state.match ? props.children : null
});
}
export default MediaQuery;
//# sourceMappingURL=MediaQuery.js.map