@hitachivantara/uikit-react-utils
Version:
UI Kit utilities package.
58 lines (57 loc) • 1.77 kB
JavaScript
import { useCss } from "../hooks/useCss.js";
import { useMemo } from "react";
//#region src/utils/classes.ts
/** Maps over an object, preserving the original keys */
function mapObject(inputObject, mapFn) {
return Object.entries(inputObject).reduce((acc, [key, value]) => {
acc[key] = mapFn(key, value);
return acc;
}, {});
}
var 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;
};
/** Given a `stylesObj`, replaces its keys' `$myClass` with `.{name}-myClass`. */
var replace$ = (stylesObj, name) => {
return deepRenameKeys(stylesObj, (key) => {
const matches = key.match(/\$\w+/g);
if (!matches?.length) return key;
return matches.reduce((acc, match) => acc.replace(match, `.${name}-${match.slice(1)}`), key) ?? key;
});
};
/** Utility function to create classes for a component. */
function createClasses(name, stylesObject) {
const styles = replace$(stylesObject, name);
const staticClasses = mapObject(styles, (key) => `${name}-${key}`);
/**
* Hook that takes in a component's `classesProp` overrides, and returns the
* concatenated static/internal/override `classes`, and the cached `cx` and `css` utilities.
*/
function useClasses(classesProp = {}, addStatic = true) {
const { cx, css } = useCss();
return {
classes: useMemo(() => {
return mapObject(styles, (key) => cx(addStatic && `${name}-${key}`, css(styles[key]), classesProp?.[key]));
}, [
addStatic,
classesProp,
css,
cx
]),
css,
cx
};
}
return {
useClasses,
staticClasses
};
}
//#endregion
export { createClasses };