Last active
May 21, 2019 08:47
-
-
Save mattpocock/92068df5d977ad9b3611c8bd5fb73b50 to your computer and use it in GitHub Desktop.
Function for creating theme functions out of a theme file for styled components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import optionalChain from 'utils/helperFunctions/optionalChain'; | |
| const recursivelyCreateThemeFunctions = ( | |
| themeObject: ThemeObject, | |
| steps: (string | number)[] = [], | |
| ): ThemeFunction | ThemeObjectReturn => { | |
| if (Array.isArray(themeObject)) { | |
| // @ts-ignore | |
| return themeObject.map((value, index) => | |
| recursivelyCreateThemeFunctions(value, [...steps, index]), | |
| ); | |
| } | |
| if (typeof themeObject === 'object' && themeObject !== null) { | |
| return { | |
| ...Object.keys(themeObject) | |
| .map(key => ({ | |
| [key]: recursivelyCreateThemeFunctions(themeObject[key], [ | |
| ...steps, | |
| key, | |
| ]), | |
| })) | |
| .reduce((a, b) => ({ ...a, ...b }), {}), | |
| }; | |
| } | |
| return ({ theme }) => optionalChain(theme, ...steps); | |
| }; | |
| type ThemeObject = { [index: string]: ThemeObject } | string | number | any[]; | |
| type ThemeObjectReturn = | |
| | { [index: string]: ThemeFunction | ThemeObjectReturn } | |
| | ({ [index: string]: ThemeFunction | ThemeObjectReturn } | ThemeFunction)[]; | |
| type ThemeFunction = (param: { theme: any }) => any; | |
| const createThemeFunctions = <Theme>( | |
| themeObject: ThemeObject, | |
| ): { [K in keyof Theme]: ThemeFunction } => { | |
| // @ts-ignore | |
| return recursivelyCreateThemeFunctions(themeObject); | |
| }; | |
| export default createThemeFunctions; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { variables } from 'cssSettings'; | |
| import createThemeFunctions from 'createThemeFunctions'; | |
| const theme = createThemeFunctions<typeof variables>(variables); | |
| export default theme; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment