Skip to content

Commit b68f7ee

Browse files
authored
Merge pull request #903 from CvX/theme-deep-function-values
Allow accessing deep paths with function values via theme helper
2 parents fccfd58 + 23b720b commit b68f7ee

File tree

2 files changed

+65
-3
lines changed

2 files changed

+65
-3
lines changed

__tests__/resolveConfig.test.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -830,6 +830,59 @@ test('the theme function can resolve function values', () => {
830830
})
831831
})
832832

833+
test('the theme function can resolve deep function values', () => {
834+
const userConfig = {
835+
theme: {
836+
minWidth: theme => ({
837+
'1/3': theme('width.1/3'),
838+
}),
839+
},
840+
}
841+
842+
const defaultConfig = {
843+
prefix: '-',
844+
important: false,
845+
separator: ':',
846+
theme: {
847+
spacing: {
848+
'0': '0',
849+
},
850+
width: theme => ({
851+
...theme('spacing'),
852+
'1/3': '33.33333%',
853+
}),
854+
},
855+
variants: {
856+
backgroundColor: ['responsive', 'hover', 'focus'],
857+
borderColor: ['responsive', 'hover', 'focus'],
858+
},
859+
}
860+
861+
const result = resolveConfig([userConfig, defaultConfig])
862+
863+
expect(result).toEqual({
864+
prefix: '-',
865+
important: false,
866+
separator: ':',
867+
theme: {
868+
spacing: {
869+
'0': '0',
870+
},
871+
width: {
872+
'0': '0',
873+
'1/3': '33.33333%',
874+
},
875+
minWidth: {
876+
'1/3': '33.33333%',
877+
},
878+
},
879+
variants: {
880+
backgroundColor: ['responsive', 'hover', 'focus'],
881+
borderColor: ['responsive', 'hover', 'focus'],
882+
},
883+
})
884+
})
885+
833886
test('theme values in the extend section are lazily evaluated', () => {
834887
const userConfig = {
835888
theme: {

src/util/resolveConfig.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import mergeWith from 'lodash/mergeWith'
22
import isFunction from 'lodash/isFunction'
33
import defaults from 'lodash/defaults'
44
import map from 'lodash/map'
5-
import get from 'lodash/get'
5+
import toPath from 'lodash/toPath'
66

77
const configUtils = {
88
negative(scale) {
@@ -40,8 +40,17 @@ function mergeExtensions({ extend, ...theme }) {
4040

4141
function resolveFunctionKeys(object) {
4242
const resolveThemePath = (key, defaultValue) => {
43-
const val = get(object, key, defaultValue)
44-
return isFunction(val) ? val(resolveThemePath) : val
43+
const path = toPath(key)
44+
45+
let index = 0
46+
let val = object
47+
48+
while (val !== undefined && val !== null && index < path.length) {
49+
val = val[path[index++]]
50+
val = isFunction(val) ? val(resolveThemePath) : val
51+
}
52+
53+
return val === undefined ? defaultValue : val
4554
}
4655

4756
return Object.keys(object).reduce((resolved, key) => {

0 commit comments

Comments
 (0)