css-vars-hook
Version:
css-vars-hook contains React hooks to set and manipulate CSS custom properties from React component.
1 lines • 16.5 kB
Source Map (JSON)
{"version":3,"file":"index.umd.cjs","sources":["../src/lib/RootTheme/RootContext.ts","../src/lib/RootTheme/useRootThemePublic.ts","../src/lib/utils.ts","../src/lib/RootTheme/useRootTheme.ts","../src/lib/RootTheme/RootThemeProvider.tsx","../src/lib/LocalTheme/LocalRoot.tsx","../src/lib/LocalTheme/useLocalTheme.tsx"],"sourcesContent":["import {useContext, createContext} from 'react';\n\nimport type {HookInterface} from './HookInterfaceType';\n\nexport const RootContext = createContext<HookInterface>({\n setTheme: () => {},\n getTheme: () => ({}),\n setVariable: () => {},\n getVariable: () => '',\n removeVariable: () => {},\n});\n\nexport const useRootContext = () => useContext<HookInterface>(RootContext);\n","import {useRootContext} from './RootContext';\n\n/**\n * @public\n * React hook to apply multiple CSS variables to theme root and manipulate them.\n * `ThemeType` is defined on project level.\n * @see ThemeType\n * @see https://github.com/morewings/css-vars-hook#type-safety\n */\nexport const useRootThemePublic = () => {\n const {setTheme, getTheme, setVariable, getVariable, removeVariable} =\n useRootContext();\n return {\n /** Effect to apply new theme to the application */\n setTheme,\n /** Get current theme */\n getTheme,\n /** Effect to set new variable value within active theme */\n setVariable,\n /** Get variable value within active theme */\n getVariable,\n /** Effect to remove variable within active theme */\n removeVariable,\n };\n};\n","import type {MutableRefObject, CSSProperties} from 'react';\nimport type {ThemeType} from 'css-vars-hook';\n\nimport type {UnitType} from '@/lib/UnitType';\n\nconst normalizeUnit = (unit: UnitType) => {\n if (typeof unit === 'string') {\n return unit;\n }\n return `${unit}`;\n};\n\n/** @function\n * @name setCSSVariable\n * @description Set CSS variable at the provided DOM node\n */\nexport const setCSSVariable =\n (element: HTMLElement) => (variableName: string, value: UnitType) => {\n element.style.setProperty(`--${variableName}`, normalizeUnit(value));\n };\n\n/** @function\n * @name removeCSSVariable\n * @description Remove CSS variable from the provided DOM node\n */\nexport const removeCSSVariable =\n (ref: MutableRefObject<HTMLElement>) => (variableName: string) => {\n const element = ref.current;\n element?.style?.removeProperty?.(`--${variableName}`);\n };\n\n/** @function\n * @name getCSSVariable\n * @description Get CSS variable value at the provided DOM node\n */\nexport const getCSSVariable =\n (ref: MutableRefObject<HTMLElement>) => (variableName: string) => {\n const element = ref.current;\n return element?.style?.getPropertyValue?.(`--${variableName}`);\n };\n\n/** @function\n * @name createStyleObject\n * @description Add `--` prefix to property names in theme object in order to make it applicable to DOM node\n */\nexport const createStyleObject = (theme: ThemeType): CSSProperties => {\n const keys = Object.keys(theme);\n const result = {} as ThemeType;\n keys.forEach(key => {\n result[`--${key}`] = theme[key];\n });\n return result;\n};\n\n/** @function\n * @name setRootVariable\n * @description Set CSS variable on theme root element\n */\nexport const setRootVariable =\n (id: string) => (variableName: string, value: UnitType) => {\n const root = document.getElementById(id)!;\n root?.style?.setProperty?.(`--${variableName}`, normalizeUnit(value));\n };\n\n/** @function\n * @name getRootVariable\n * @description Get CSS variable on theme root element\n */\nexport const getRootVariable =\n (id: string) =>\n (variableName: string): string => {\n const root = document.getElementById(id)!;\n return root?.style?.getPropertyValue?.(`--${variableName}`);\n };\n\n/** @function\n * @name removeRootVariable\n * @description Remove CSS variable from theme root element\n */\nexport const removeRootVariable = (id: string) => (variableName: string) => {\n const root = document.getElementById(id)!;\n root?.style?.removeProperty?.(`--${variableName}`);\n};\n","import {useCallback, useMemo, useRef} from 'react';\nimport type {CSSProperties} from 'react';\nimport type {ThemeType} from 'css-vars-hook';\n\nimport type {UnitType} from '@/lib/UnitType';\n\nimport {\n createStyleObject,\n getRootVariable,\n removeRootVariable,\n setRootVariable,\n} from '../utils';\nimport type {HookInterface} from './HookInterfaceType';\n\n/**\n * @private\n * Logic for root theme handling such as updates and CSS style creation\n */\nexport const useRootTheme = (\n theme: ThemeType,\n id: string\n): HookInterface & {style: CSSProperties} => {\n const themeRef = useRef(theme);\n\n const setTheme = useCallback(\n (nextTheme: ThemeType) => {\n Object.keys(nextTheme).forEach(key => {\n setRootVariable(id)(key, nextTheme[key]);\n });\n\n themeRef.current = nextTheme;\n },\n [id]\n );\n\n const getTheme = useCallback(() => themeRef.current, []);\n\n const getVariable = useCallback(\n (variableName: string) => getRootVariable(id)(variableName),\n [id]\n );\n const setVariable = useCallback(\n (variableName: string, value: UnitType) => {\n setRootVariable(id)(variableName, value);\n themeRef.current = {\n ...themeRef.current,\n [variableName]: value,\n };\n },\n [id]\n );\n\n const removeVariable = useCallback(\n (variableName: string) => {\n removeRootVariable(id)(variableName);\n const nextTheme = {...themeRef.current};\n delete nextTheme[variableName];\n themeRef.current = nextTheme;\n },\n [id]\n );\n\n const style = useMemo(() => createStyleObject(themeRef.current), []);\n\n return {\n /** Effect to apply new theme to the application */\n setTheme,\n /** CSSProperties object to apply to container div */\n style,\n /** Get current theme */\n getTheme,\n /** Get variable value within active theme */\n getVariable,\n /** Effect to set new variable value within active theme */\n setVariable,\n /** Effect to remove variable within active theme */\n removeVariable,\n };\n};\n","import type {FC, ReactNode} from 'react';\nimport {useMemo, useEffect, useId} from 'react';\nimport type {ThemeType} from 'css-vars-hook';\n\nimport type {DataAttributes, LibraryProps} from '../NativeProps';\nimport {RootContext} from './RootContext';\nimport {useRootTheme} from './useRootTheme';\n\n/**\n * @public\n */\nexport type RootThemeProviderProps = DataAttributes &\n LibraryProps & {children: ReactNode; theme: ThemeType};\n\n/**\n * @public\n * Root theme context provider also creates div to contain CSS properties.\n * `ThemeType` is declared globally.\n * @see ThemeType\n * @see https://github.com/morewings/css-vars-hook#type-safety\n */\nexport const RootThemeProvider: FC<RootThemeProviderProps> = ({\n children,\n theme,\n className,\n id,\n ...nativeProps\n}) => {\n const backupId = useId();\n const rootId = id ? id : backupId;\n const {setTheme, style, getTheme, getVariable, setVariable, removeVariable} =\n useRootTheme(theme, rootId);\n\n const {Provider} = RootContext;\n\n const actions = useMemo(\n () => ({setTheme, getTheme, getVariable, setVariable, removeVariable}),\n [setTheme, getTheme, getVariable, setVariable, removeVariable]\n );\n\n useEffect(() => {\n setTheme(theme);\n }, [theme, setTheme]);\n\n return (\n <Provider value={actions}>\n <div {...nativeProps} id={rootId} className={className} style={style}>\n {children}\n </div>\n </Provider>\n );\n};\n","import type {HTMLAttributes, ReactNode} from 'react';\nimport {createElement, forwardRef, useEffect, useMemo} from 'react';\nimport type {ThemeType} from 'css-vars-hook';\n\nimport {createStyleObject} from '@/lib/utils';\nimport type {DataAttributes, LibraryProps} from '@/lib/NativeProps';\n\n/**\n * @public\n */\nexport type LocalRootProps = DataAttributes &\n LibraryProps &\n HTMLAttributes<HTMLElement> & {\n children?: ReactNode;\n /** Choose which HTMLElement to render as a root. div is default. */\n as?: string;\n /** Apply initial theme. */\n theme?: ThemeType;\n /** Provide theme setter function. */\n setTheme?: (arg0: ThemeType) => void;\n };\n\nexport const LocalRoot = forwardRef<HTMLElement, LocalRootProps>((props, ref) => {\n // This is needed to fix an error introduced in version 0.6.14.\n // Props were not transported to returned HTMLElement.\n const {children, as = 'div', theme = {}, setTheme = () => {}, ...restProps} = props;\n\n const initialStyle = useMemo(() => createStyleObject(theme), [theme]);\n\n useEffect(() => {\n setTheme(theme);\n }, [theme, setTheme]);\n\n return createElement(as, {...restProps, style: initialStyle, ref}, children);\n});\n\nLocalRoot.displayName = 'LocalRoot';\n","import {useCallback, useRef, useMemo} from 'react';\nimport type {ThemeType} from 'css-vars-hook';\n\nimport {setCSSVariable} from '@/lib/utils';\nimport type {UnitType} from '@/lib/UnitType';\n\nimport type {LocalRootProps} from './LocalRoot';\nimport {LocalRoot} from './LocalRoot';\n\n/**\n * @public\n * React hook to apply multiple CSS variables to generated local root element (LocalRoot) and manipulate them.\n * Theme type is inferred from provided theme parameter.\n * @example\n * const {setTheme, getTheme, LocalRoot, getVariable, setVariable} = useLocalTheme();\n * const setThemeIvory = () => {\n * setTheme({foo: 'ivory'});\n * console.log('full theme', getTheme()) // => {foo: 'ivory'};\n * console.log('foo value', getVariable('foo')) // => 'ivory';\n *};\n * return <LocalRoot theme={{foo: 'bar'}} className=\"demo-local\">//...\n */\nexport const useLocalTheme = <TElement extends HTMLElement>() => {\n const themeRef = useRef<ThemeType>();\n const elementRef = useRef<TElement>(null);\n\n const setTheme = useCallback((nextTheme: ThemeType) => {\n Object.keys(nextTheme).forEach((key: string) => {\n setCSSVariable(elementRef.current!)(key, nextTheme[key]);\n });\n\n themeRef.current = nextTheme;\n }, []);\n\n const getTheme = useCallback(() => themeRef.current, []);\n\n const getVariable = useCallback(\n (variableName: string) => themeRef.current?.[variableName],\n []\n );\n\n const setVariable = useCallback((variableName: string, variableValue: UnitType) => {\n setCSSVariable(elementRef.current!)(variableName, variableValue);\n themeRef.current = {...themeRef.current, [variableName]: variableValue};\n }, []);\n\n const MemoRoot = useMemo(\n () =>\n // eslint-disable-next-line react/display-name\n ({children, ...restProps}: Omit<LocalRootProps, 'setTheme'>) => (\n <LocalRoot {...restProps} setTheme={setTheme} ref={elementRef}>\n {children}\n </LocalRoot>\n ),\n [setTheme]\n );\n\n return {\n /** Effect to apply new theme to LocalRoot */\n setTheme,\n /** Get current theme set for LocalRoot */\n getTheme,\n /** Wrapper component which creates DOM node to store theme data */\n LocalRoot: MemoRoot,\n /** React Mutable Ref object attached to LocalRoot */\n ref: elementRef,\n /** Get variable value within LocalRoot theme */\n getVariable,\n /** Effect to set new variable value within LocalRoot theme */\n setVariable,\n };\n};\n"],"names":["RootContext","createContext","useRootContext","useContext","useRootThemePublic","setTheme","getTheme","setVariable","getVariable","removeVariable","normalizeUnit","unit","setCSSVariable","element","variableName","value","createStyleObject","theme","keys","result","key","setRootVariable","id","root","_b","_a","getRootVariable","removeRootVariable","useRootTheme","themeRef","useRef","useCallback","nextTheme","style","useMemo","RootThemeProvider","children","className","nativeProps","backupId","useId","rootId","Provider","actions","useEffect","jsx","LocalRoot","forwardRef","props","ref","as","restProps","initialStyle","createElement","useLocalTheme","elementRef","variableValue","MemoRoot"],"mappings":"2UAIO,MAAMA,EAAcC,EAAAA,cAA6B,CACpD,SAAU,IAA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