@cerberus-design/react
Version:
The Cerberus Design React component library.
37 lines (34 loc) • 1.07 kB
JavaScript
'use client';
import { useReducer, useCallback, useEffect, useMemo } from 'react';
function useRootColors(colors = []) {
const [state, dispatch] = useReducer(rootColorsReducer, {});
const handleRefetch = useCallback(() => {
return new Promise((resolve) => {
dispatch(formatColors(colors));
resolve();
});
}, [colors]);
useEffect(() => {
if (Object.keys(state).length === colors.length) return;
dispatch(formatColors(colors));
}, [colors, state]);
return useMemo(
() => ({ colors: state, refetch: handleRefetch }),
[state, handleRefetch]
);
}
function formatColors(colors) {
const rootStyles = getComputedStyle(document.body);
return colors.reduce(
(acc, color) => {
const formattedColor = color.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase().replaceAll(".", "-");
acc[color] = rootStyles.getPropertyValue(`--cerberus-colors-${formattedColor}`).trim();
return acc;
},
{}
);
}
function rootColorsReducer(state, action) {
return { ...state, ...action };
}
export { useRootColors };