@nex-ui/styled
Version:
Styled API for creating atomic, theme-aware component styling.
94 lines (91 loc) • 3.54 kB
JavaScript
import { jsx, jsxs, Fragment } from 'react/jsx-runtime';
import { withEmotionCache } from '@emotion/react';
import { getRegisteredStyles } from '@emotion/utils';
import { __DEV__, forEach, map, isFunction, isArray } from '@nex-ui/utils';
import { useSystem } from '@nex-ui/system';
import { serializeStyles } from '@emotion/serialize';
import { getDefaultShouldForwardProp } from './utils.mjs';
import { tags } from './tags.mjs';
import { Insertion } from './Insertion.mjs';
const createStyled = (tag)=>{
if (__DEV__ && tag === undefined) {
throw new Error('[Nex UI] styled: You are trying to create a styled element with an undefined component.\nYou may have forgotten to import it.');
}
const defaultShouldForwardProp = getDefaultShouldForwardProp(tag);
const shouldUseAs = !defaultShouldForwardProp('as');
return (...args)=>{
const styles = args.slice();
const Styled = withEmotionCache(({ sx, ...props }, cache, ref)=>{
const FinalTag = shouldUseAs && props.as || tag;
const sys = useSystem();
const mergedSx = sx ? [
...styles,
sx
] : [
...styles
];
const finalShouldForwardProp = shouldUseAs ? getDefaultShouldForwardProp(FinalTag) : defaultShouldForwardProp;
const newProps = ref ? {
ref
} : {};
forEach(props, (prop, key)=>{
if (!(shouldUseAs && key === 'as') && finalShouldForwardProp(key)) {
newProps[key] = prop;
}
});
if (mergedSx.length === 0) {
return /*#__PURE__*/ jsx(FinalTag, {
...newProps
});
}
let className = '';
let registeredStyles = [];
if (typeof props.className === 'string') {
className = getRegisteredStyles(cache.registered, registeredStyles, props.className);
} else if (props.className != null) {
className = `${props.className} `;
}
// TODO
const resolveSx = (arg)=>{
return map(arg, (v)=>{
if (isFunction(v)) {
return v(props);
}
if (isArray(v)) {
return resolveSx(v);
}
return v;
});
};
const cssProp = sys.css(resolveSx(mergedSx));
registeredStyles = [
...registeredStyles,
cssProp
];
const serialized = serializeStyles(registeredStyles, cache.registered, props);
className += `${cache.key}-${serialized.name}`;
newProps.className = className;
return /*#__PURE__*/ jsxs(Fragment, {
children: [
/*#__PURE__*/ jsx(Insertion, {
cache: cache,
serialized: serialized,
isStringTag: typeof FinalTag === 'string'
}),
/*#__PURE__*/ jsx(FinalTag, {
...newProps
})
]
});
});
Styled.displayName = 'NexUIStyledComponent';
return Styled;
};
};
// @ts-ignore
const styled = createStyled.bind();
tags.forEach((tag)=>{
// @ts-ignore
styled[tag] = styled(tag);
});
export { styled };