UNPKG

@hitachivantara/uikit-react-utils

Version:
52 lines (51 loc) 1.48 kB
import { useMemo } from "react"; import { useCss } from "../hooks/useCss.js"; function mapObject(inputObject, mapFn) { return Object.entries(inputObject).reduce( (acc, [key, value]) => { acc[key] = mapFn(key, value); return acc; }, {} ); } const deepRenameKeys = (obj, mapFn) => { const result = {}; for (const key in obj) { if (Object.hasOwn(obj, key)) { const newKey = mapFn(key); const value = obj[key]; result[newKey] = typeof value === "object" ? deepRenameKeys(value, mapFn) : value; } } return result; }; const replace$ = (stylesObj, name) => { return deepRenameKeys(stylesObj, (key) => { const matches = key.match(/\$\w+/g); if (!matches?.length) return key; const newKey = matches.reduce( (acc, match) => acc.replace(match, `.${name}-${match.slice(1)}`), key ); return newKey ?? key; }); }; function createClasses(name, stylesObject) { const styles = replace$(stylesObject, name); const staticClasses = mapObject(styles, (key) => `${name}-${key}`); function useClasses(classesProp = {}, addStatic = true) { const { cx, css } = useCss(); const classes = useMemo(() => { return mapObject( styles, (key) => cx(addStatic && `${name}-${key}`, css(styles[key]), classesProp?.[key]) ); }, [addStatic, classesProp, css, cx]); return { classes, css, cx }; } return { useClasses, staticClasses }; } export { createClasses };