Add support for lazy values in theme

This commit is contained in:
Adam Wathan 2019-02-05 20:18:19 -05:00
parent a4854006ba
commit 40413690a2
2 changed files with 140 additions and 1 deletions

View File

@ -300,3 +300,133 @@ test('missing top level keys are pulled from the default config', () => {
},
})
})
test('functions in the default theme section are lazily evaluated', () => {
const userConfig = {
theme: {
colors: {
red: 'red',
green: 'green',
blue: 'blue',
},
},
}
const defaultConfig = {
prefix: '-',
important: false,
separator: ':',
theme: {
colors: {
cyan: 'cyan',
magenta: 'magenta',
yellow: 'yellow',
},
backgroundColors: ({ colors }) => colors,
textColors: ({ colors }) => colors,
},
variants: {
backgroundColors: ['responsive', 'hover', 'focus'],
textColors: ['responsive', 'hover', 'focus'],
},
}
const result = mergeConfigWithDefaults(userConfig, defaultConfig)
expect(result).toEqual({
prefix: '-',
important: false,
separator: ':',
theme: {
colors: {
red: 'red',
green: 'green',
blue: 'blue',
},
backgroundColors: {
red: 'red',
green: 'green',
blue: 'blue',
},
textColors: {
red: 'red',
green: 'green',
blue: 'blue',
},
},
variants: {
backgroundColors: ['responsive', 'hover', 'focus'],
textColors: ['responsive', 'hover', 'focus'],
},
})
})
test('functions in the user theme section are lazily evaluated', () => {
const userConfig = {
theme: {
colors: {
red: 'red',
green: 'green',
blue: 'blue',
},
backgroundColors: ({ colors }) => ({
...colors,
customBackground: '#bada55',
}),
textColors: ({ colors }) => ({
...colors,
customText: '#facade',
}),
},
}
const defaultConfig = {
prefix: '-',
important: false,
separator: ':',
theme: {
colors: {
cyan: 'cyan',
magenta: 'magenta',
yellow: 'yellow',
},
backgroundColors: ({ colors }) => colors,
textColors: ({ colors }) => colors,
},
variants: {
backgroundColors: ['responsive', 'hover', 'focus'],
textColors: ['responsive', 'hover', 'focus'],
},
}
const result = mergeConfigWithDefaults(userConfig, defaultConfig)
expect(result).toEqual({
prefix: '-',
important: false,
separator: ':',
theme: {
colors: {
red: 'red',
green: 'green',
blue: 'blue',
},
backgroundColors: {
red: 'red',
green: 'green',
blue: 'blue',
customBackground: '#bada55',
},
textColors: {
red: 'red',
green: 'green',
blue: 'blue',
customText: '#facade',
},
},
variants: {
backgroundColors: ['responsive', 'hover', 'focus'],
textColors: ['responsive', 'hover', 'focus'],
},
})
})

View File

@ -1,9 +1,18 @@
import _ from 'lodash'
function resolveFunctionKeys(object) {
return Object.keys(object).reduce((resolved, key) => {
return {
...resolved,
[key]: _.isFunction(object[key]) ? object[key](object) : object[key]
}
}, {})
}
export default function(userConfig, defaultConfig) {
return _.defaults(
{
theme: _.defaults(userConfig.theme, defaultConfig.theme),
theme: resolveFunctionKeys(_.defaults(userConfig.theme, defaultConfig.theme)),
variants: _.defaults(userConfig.variants, defaultConfig.variants),
},
userConfig,