seti-ramesesv1
Version:
Reusable components and context for Next.js apps
86 lines (83 loc) • 3.03 kB
JavaScript
import { isCqShorthand, getContainerQuery } from '../cssContainerQueries/cssContainerQueries.js';
// The breakpoint **start** at this value.
// For instance with the first breakpoint xs: [xs, sm[.
const values = {
xs: 0,
// phone
sm: 600,
// tablet
md: 900,
// small laptop
lg: 1200,
// desktop
xl: 1536 // large screen
};
const defaultBreakpoints = {
// Sorted ASC by size. That's important.
// It can't be configured as it's used statically for propTypes.
keys: ['xs', 'sm', 'md', 'lg', 'xl'],
up: key => `@media (min-width:${values[key]}px)`
};
const defaultContainerQueries = {
containerQueries: containerName => ({
up: key => {
let result = typeof key === 'number' ? key : values[key] || key;
if (typeof result === 'number') {
result = `${result}px`;
}
return containerName ? `@container ${containerName} (min-width:${result})` : `@container (min-width:${result})`;
}
})
};
function handleBreakpoints(props, propValue, styleFromPropValue) {
const theme = props.theme || {};
if (Array.isArray(propValue)) {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return propValue.reduce((acc, item, index) => {
acc[themeBreakpoints.up(themeBreakpoints.keys[index])] = styleFromPropValue(propValue[index]);
return acc;
}, {});
}
if (typeof propValue === 'object') {
const themeBreakpoints = theme.breakpoints || defaultBreakpoints;
return Object.keys(propValue).reduce((acc, breakpoint) => {
if (isCqShorthand(themeBreakpoints.keys, breakpoint)) {
const containerKey = getContainerQuery(theme.containerQueries ? theme : defaultContainerQueries, breakpoint);
if (containerKey) {
acc[containerKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
}
}
// key is breakpoint
else if (Object.keys(themeBreakpoints.values || values).includes(breakpoint)) {
const mediaKey = themeBreakpoints.up(breakpoint);
acc[mediaKey] = styleFromPropValue(propValue[breakpoint], breakpoint);
} else {
const cssKey = breakpoint;
acc[cssKey] = propValue[cssKey];
}
return acc;
}, {});
}
const output = styleFromPropValue(propValue);
return output;
}
function createEmptyBreakpointObject(breakpointsInput = {}) {
const breakpointsInOrder = breakpointsInput.keys?.reduce((acc, key) => {
const breakpointStyleKey = breakpointsInput.up(key);
acc[breakpointStyleKey] = {};
return acc;
}, {});
return breakpointsInOrder || {};
}
function removeUnusedBreakpoints(breakpointKeys, style) {
return breakpointKeys.reduce((acc, key) => {
const breakpointOutput = acc[key];
const isBreakpointUnused = !breakpointOutput || Object.keys(breakpointOutput).length === 0;
if (isBreakpointUnused) {
delete acc[key];
}
return acc;
}, style);
}
export { createEmptyBreakpointObject, handleBreakpoints, removeUnusedBreakpoints, values };
//# sourceMappingURL=breakpoints.js.map