UNPKG

@indoqa/style-system

Version:

A style system for React with Typescript typed theme support and several base components.

75 lines 2.68 kB
import { sortBreakpoints } from '../theming/sortBreakpoints'; export const THEME_NOT_AVAILABLE_ERR_MSG = 'There is no theme available or one of its properties is missing. ' + 'Check if the Fela ThemeProvider is configured correctly.'; export const addUnitIfNeeded = (value, propertyUnit) => { const valueType = typeof value; if (valueType === 'number' || (valueType === 'string' && !isNaN(value))) { return `${value}${propertyUnit || 'px'}`; } return `${value}`; }; const initializeObjectArray = (length) => { const a = []; for (let i = 0; i < length; i++) { a.push({}); } return a; }; const validateSizes = (length, breakpointCount, name, value) => { if (length > breakpointCount + 1) { if (process.env.NODE_ENV !== 'production') { console.warn(`The property ${name} contains more values than available breakpoints.`, value); } return false; } return true; }; export function getPropsByBreakpoint(props, breakpoints) { const result = initializeObjectArray(breakpoints.length + 1); Object.keys(props).forEach((key) => { const value = props[key]; if (!Array.isArray(value)) { result[0][key] = value; } else { validateSizes(value.length, breakpoints.length, key, value); for (let i = 0; i <= breakpoints.length; i++) { const currentValue = value[i]; if (currentValue !== undefined) { result[i][key] = currentValue; } } } }); return result; } export function createResponsiveStyles(props, styleFunction) { const { theme } = props; if (!theme) { throw Error(THEME_NOT_AVAILABLE_ERR_MSG); } const sortedBreakpoints = sortBreakpoints(theme.breakpoints); const groupedProps = getPropsByBreakpoint(props, sortedBreakpoints); const styles = styleFunction(groupedProps[0], theme, true); for (let i = 0; i < sortedBreakpoints.length; i++) { const breakpointProps = groupedProps[i + 1]; if (Object.keys(breakpointProps).length === 0) { break; } const breakpointName = sortedBreakpoints[i].name; Object.assign(styles, { [breakpointName]: styleFunction(breakpointProps, theme, false), }); } return styles; } export function mergeThemedStyles(componentStyle, passedStyle) { if (!passedStyle) { return componentStyle; } if (passedStyle instanceof Array) { return [componentStyle, ...passedStyle]; } return [componentStyle, passedStyle]; } //# sourceMappingURL=utils.js.map