diff --git a/src/__tests__/index.spec.js b/src/__tests__/index.spec.js index b6f8675..b004449 100644 --- a/src/__tests__/index.spec.js +++ b/src/__tests__/index.spec.js @@ -38,4 +38,51 @@ describe('makeTheme', () => { new Color(colors.red).darken(0.1).toString() ) }) + + it('extracts theme structure', () => { + const exampleTheme = { + background: 'white', + color: 'red', + ui: { + background: 'gray', + color: 'red' + } + } + + const theme = makeTheme(exampleTheme) + + const colorSelector = theme.color + expect(colorSelector).toBeA('function') + expect(colorSelector.length).toBe(1) + + const uiColorSelector = theme.ui.color + expect(uiColorSelector).toBeA('function') + expect(uiColorSelector.length).toBe(1) + + const themeFromProvider = { + theme: { + background: '#FFFFFF', + color: '#2A2A2A', + ui: { + background: '#000000', + color: '#9B1919' + } + } + } + + expect(colorSelector(themeFromProvider)) + .toBe(themeFromProvider.theme.color) + expect(uiColorSelector(themeFromProvider)) + .toBe(themeFromProvider.theme.ui.color) + + const darkerColor = colorSelector.darken(0.1) + const lighterUIColor = uiColorSelector.lighten(0.4) + + expect(darkerColor(themeFromProvider)).toBe( + new Color(themeFromProvider.theme.color).darken(0.1).toString() + ) + expect(lighterUIColor(themeFromProvider)).toBe( + new Color(themeFromProvider.theme.ui.color).lighten(0.4).toString() + ) + }) }) diff --git a/src/index.js b/src/index.js index 5177a7f..22b22ae 100755 --- a/src/index.js +++ b/src/index.js @@ -1,11 +1,28 @@ import makeThemeColor from './makeThemeColor' -const makeTheme = (...colors) => - colors.reduce((result, color) => { - result[color] = makeThemeColor(color) +const makeTheme = (theme, ...themePath) => { + if (typeof(theme) !== 'object') { + // compat mode + // make theme object with keys of all arguments + theme = [theme, ...themePath].reduce( + (result, color) => { + result[color] = '' + return result + }, {}) + return makeTheme(theme) + } + + themePath = themePath.length ? themePath : ['theme'] + + return Object.entries(theme).reduce((result, [key, item]) => { + if (typeof(item) === 'object') { + result[key] = makeTheme(item, ...themePath, key) + } else { + result[key] = makeThemeColor(...themePath, key) + } return result }, {}) +} -export { makeThemeColor } export default makeTheme diff --git a/src/makeThemeColor.js b/src/makeThemeColor.js index d622aa1..3006be0 100755 --- a/src/makeThemeColor.js +++ b/src/makeThemeColor.js @@ -1,5 +1,10 @@ import decorateSelector from './decorateSelector' -const makeThemeColor = key => decorateSelector(props => props.theme[key]) +const makeThemeColor = (...propsPath) => + decorateSelector(props => { + propsPath.forEach(key => props = props[key]) + return props + }) + export default makeThemeColor