UNPKG

@onesy/style-react

Version:

Onesy CSS in JS styling solution for React

72 lines (68 loc) 2.27 kB
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; const _excluded = ["root", "remove", "value", "children"]; import React from 'react'; import is from '@onesy/utils/is'; import { OnesyStyle, makeClassName, unit, rtl, sort, valueObject, prefix } from '@onesy/style'; import StyleContext from './Context'; function makeOnesyStyle(element) { const onesyStyle = new OnesyStyle({ element }); // Add all the plugins onesyStyle.plugins.add = [unit, makeClassName, prefix, sort, rtl, valueObject]; return onesyStyle; } const Style = /*#__PURE__*/React.forwardRef((props, ref) => { const { root = false, remove, value: value_, children } = props, other = _objectWithoutProperties(props, _excluded); const refs = { root: React.useRef(undefined) }; const [value, setValue] = React.useState(() => { if (value_ === undefined || !(value_ instanceof OnesyStyle)) return makeOnesyStyle(); value_.remove = remove; return value_; }); React.useEffect(() => { if (refs.root.current) { value.element = refs.root.current; value.remove = remove; // Init value.init(); const valueNew = new OnesyStyle(); // Copy over from value Object.keys(value).forEach(prop => valueNew[prop] = value[prop]); setValue(valueNew); } }, []); const update = updateValue => { if (updateValue !== undefined) { const valueNew = new OnesyStyle(); valueNew.remove = remove; Object.keys(value).forEach(prop => valueNew[prop] = value[prop]); is('object', updateValue) && Object.keys(updateValue).forEach(prop => valueNew[prop] = updateValue[prop]); setValue(valueNew); return valueNew; } }; // Update method value.updateWithRerender = update; if (root) return /*#__PURE__*/React.createElement(StyleContext.Provider, { value: value }, /*#__PURE__*/React.createElement("div", _extends({ ref: item => { refs.root.current = item; if (ref?.current) ref.current = item; } }, other), children)); return /*#__PURE__*/React.createElement(StyleContext.Provider, { value: value }, children); }); export default Style;