Merge pull request #903 from CvX/theme-deep-function-values

Allow accessing deep paths with function values via theme helper
This commit is contained in:
Adam Wathan 2019-05-09 07:17:00 -04:00 committed by GitHub
commit b68f7ee114
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 65 additions and 3 deletions

View File

@ -830,6 +830,59 @@ test('the theme function can resolve function values', () => {
})
})
test('the theme function can resolve deep function values', () => {
const userConfig = {
theme: {
minWidth: theme => ({
'1/3': theme('width.1/3'),
}),
},
}
const defaultConfig = {
prefix: '-',
important: false,
separator: ':',
theme: {
spacing: {
'0': '0',
},
width: theme => ({
...theme('spacing'),
'1/3': '33.33333%',
}),
},
variants: {
backgroundColor: ['responsive', 'hover', 'focus'],
borderColor: ['responsive', 'hover', 'focus'],
},
}
const result = resolveConfig([userConfig, defaultConfig])
expect(result).toEqual({
prefix: '-',
important: false,
separator: ':',
theme: {
spacing: {
'0': '0',
},
width: {
'0': '0',
'1/3': '33.33333%',
},
minWidth: {
'1/3': '33.33333%',
},
},
variants: {
backgroundColor: ['responsive', 'hover', 'focus'],
borderColor: ['responsive', 'hover', 'focus'],
},
})
})
test('theme values in the extend section are lazily evaluated', () => {
const userConfig = {
theme: {

View File

@ -2,7 +2,7 @@ import mergeWith from 'lodash/mergeWith'
import isFunction from 'lodash/isFunction'
import defaults from 'lodash/defaults'
import map from 'lodash/map'
import get from 'lodash/get'
import toPath from 'lodash/toPath'
const configUtils = {
negative(scale) {
@ -40,8 +40,17 @@ function mergeExtensions({ extend, ...theme }) {
function resolveFunctionKeys(object) {
const resolveThemePath = (key, defaultValue) => {
const val = get(object, key, defaultValue)
return isFunction(val) ? val(resolveThemePath) : val
const path = toPath(key)
let index = 0
let val = object
while (val !== undefined && val !== null && index < path.length) {
val = val[path[index++]]
val = isFunction(val) ? val(resolveThemePath) : val
}
return val === undefined ? defaultValue : val
}
return Object.keys(object).reduce((resolved, key) => {