UNPKG

@patreon/studio

Version:

Patreon Studio Design System

58 lines (57 loc) 2.57 kB
import { useMemo } from 'react'; import { useColorSystemContainerState } from '../../components/ColorSystemContainer'; import { useTokenModes } from '../../components/TokenModeProvider'; import { useTokenValueCache } from '../../components/TokenValueCache'; import { getCacheKey } from '../../utilities/color-system'; import { getTokenName } from '../../utilities/tokens'; /** * This hook can be used as an escape hatch when you need * to get the underlying value of a token as a css string. */ export function useExtractedTokenCss(tokens) { const { currentColorMode } = useTokenModes(); const tokenValueCache = useTokenValueCache(); // this is casts to the non-partial type because we know that the default token values are always complete const defaultTokenValues = tokenValueCache.default; const { inputColor, tokenMap } = useColorSystemContainerState(); const cacheKey = inputColor !== 'default' ? getCacheKey({ inputColor, tokenMap }) : null; const { light, dark } = useMemo(() => { const tokenMapList = (Array.isArray(tokens) ? tokens : [tokens]).map((token) => { const tokenName = getTokenName(token); return { tokenName, light: cacheKey ? tokenValueCache[cacheKey].light?.[tokenName] ?? defaultTokenValues.light[tokenName] : defaultTokenValues.light[tokenName], dark: cacheKey ? tokenValueCache[cacheKey].dark?.[tokenName] ?? defaultTokenValues.dark[tokenName] : defaultTokenValues.dark[tokenName], }; }); return { light: tokenMapList .filter(({ light: isLight }) => Boolean(isLight)) .map(({ tokenName, light: isLight }) => `${tokenName}: ${isLight};`) .join(' '), dark: tokenMapList .filter(({ dark: isDark }) => Boolean(isDark)) .map(({ tokenName, dark: isDark }) => `${tokenName}: ${isDark};`) .join(' '), }; }, [cacheKey, defaultTokenValues.light, defaultTokenValues.dark, tokenValueCache, tokens]); return useMemo(() => { if (currentColorMode === 'light' || dark.length === 0) { return light; } if (currentColorMode === 'dark') { return dark; } return ` ${light} @media (prefers-color-scheme: dark) { ${dark} } `; }, [currentColorMode, dark, light]); } //# sourceMappingURL=useExtractedTokenCss.js.map