UNPKG

@dyst/react

Version:

Dynamic Css-in-Js styles engine, based on Emotion for React

65 lines (62 loc) 2.2 kB
import { serializeStyles } from '@emotion/serialize'; import { getRegisteredStyles, insertStyles } from '@emotion/utils'; import clsx from 'clsx'; var __defProp = Object.defineProperty; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; class CssFactory { constructor(key = "unknown") { this.refPropertyName = "ref"; this.key = key; } build(cache) { const css = (...styles) => { const refs = []; const _styles = []; for (const style of styles) { const { ref, arg } = this.extractRef(style); if (ref != null) refs.push(ref); if (arg != null) _styles.push(arg); } const serialized = serializeStyles(_styles, cache.registered); insertStyles(cache, serialized, false); return `${cache.key}-${serialized.name}${refs.length > 0 ? refs.map((ref) => ` ${ref}`) : ""}`; }; const cx = (...args) => this.merge(cache.registered, clsx(args), css); return { css, cx }; } merge(registeredCache, classNames, css) { const registeredStyles = []; const rawClassName = getRegisteredStyles(registeredCache, registeredStyles, classNames); if (registeredStyles.length < 2) { return classNames; } return rawClassName + css(registeredStyles); } extractRef(arg) { let ref = null; if (!(arg instanceof Object) || !(this.refPropertyName in arg)) { return { arg, ref }; } ref = arg[this.refPropertyName]; const argCopy = __spreadValues({}, arg); delete argCopy[this.refPropertyName]; return { arg: argCopy, ref }; } } export { CssFactory };