forked from javivelasco/react-css-themr
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy paththemr.js
241 lines (204 loc) · 6.73 KB
/
themr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import invariant from 'invariant'
/**
* @typedef {Object.<string, TReactCSSThemrTheme>} TReactCSSThemrTheme
*/
/**
* @typedef {{}} TReactCSSThemrOptions
* @property {String|Boolean} [composeTheme=COMPOSE_DEEPLY]
* @property {Boolean} [withRef=false]
*/
const COMPOSE_DEEPLY = 'deeply'
const COMPOSE_SOFTLY = 'softly'
const DONT_COMPOSE = false
const DEFAULT_OPTIONS = {
composeTheme: COMPOSE_DEEPLY,
withRef: false
}
const THEMR_CONFIG = typeof Symbol !== 'undefined' ?
Symbol('THEMR_CONFIG') :
'__REACT_CSS_THEMR_CONFIG__'
/**
* Themr decorator
* @param {String|Number|Symbol} componentName - Component name
* @param {TReactCSSThemrTheme} [localTheme] - Base theme
* @param {{}} [options] - Themr options
* @returns {function(ThemedComponent:Function):Function} - ThemedComponent
*/
export default (componentName, localTheme, options = {}) => (ThemedComponent) => {
const { composeTheme: optionComposeTheme, withRef: optionWithRef } = { ...DEFAULT_OPTIONS, ...options }
validateComposeOption(optionComposeTheme)
let config = ThemedComponent[THEMR_CONFIG]
if (config && config.componentName === componentName) {
config.localTheme = themeable(config.localTheme, localTheme)
return ThemedComponent
}
config = {
componentName,
localTheme
}
/**
* @property {{wrappedInstance: *}} refs
*/
class Themed extends Component {
static displayName = `Themed${ThemedComponent.name}`;
static contextTypes = {
themr: PropTypes.object
}
static propTypes = {
...ThemedComponent.propTypes,
composeTheme: PropTypes.oneOf([ COMPOSE_DEEPLY, COMPOSE_SOFTLY, DONT_COMPOSE ]),
theme: PropTypes.object,
themeNamespace: PropTypes.string
}
static defaultProps = {
...ThemedComponent.defaultProps,
composeTheme: optionComposeTheme
}
constructor(...args) {
super(...args)
this.theme_ = this.calcTheme(this.props)
}
getWrappedInstance() {
invariant(optionWithRef,
'To access the wrapped instance, you need to specify ' +
'{ withRef: true } as the third argument of the themr() call.'
)
return this.refs.wrappedInstance
}
getNamespacedTheme(props) {
const { themeNamespace, theme } = props
if (!themeNamespace) return theme
if (themeNamespace && !theme) throw new Error('Invalid themeNamespace use in react-css-themr. ' +
'themeNamespace prop should be used only with theme prop.')
return Object.keys(theme)
.filter(key => key.startsWith(themeNamespace))
.reduce((result, key) => ({ ...result, [removeNamespace(key, themeNamespace)]: theme[key] }), {})
}
getThemeNotComposed(props) {
if (props.theme) return this.getNamespacedTheme(props)
if (config.localTheme) return config.localTheme
return this.getContextTheme()
}
getContextTheme() {
return this.context.themr
? this.context.themr.theme[config.componentName]
: {}
}
getTheme(props) {
return props.composeTheme === COMPOSE_SOFTLY
? {
...this.getContextTheme(),
...config.localTheme,
...this.getNamespacedTheme(props)
}
: themeable(
themeable(this.getContextTheme(), config.localTheme),
this.getNamespacedTheme(props)
)
}
calcTheme(props) {
const { composeTheme } = props
return composeTheme
? this.getTheme(props)
: this.getThemeNotComposed(props)
}
componentWillReceiveProps(nextProps) {
if (
nextProps.composeTheme !== this.props.composeTheme ||
nextProps.theme !== this.props.theme ||
nextProps.themeNamespace !== this.props.themeNamespace
) {
this.theme_ = this.calcTheme(nextProps)
}
}
render() {
let renderedElement
//exclude themr-only props
//noinspection JSUnusedLocalSymbols
const { composeTheme, themeNamespace, ...props } = this.props //eslint-disable-line no-unused-vars
if (optionWithRef) {
renderedElement = React.createElement(ThemedComponent, {
...props,
ref: 'wrappedInstance',
theme: this.theme_
})
} else {
renderedElement = React.createElement(ThemedComponent, {
...props,
theme: this.theme_
})
}
return renderedElement
}
}
Themed[THEMR_CONFIG] = config
return Themed
}
/**
* Merges two themes by concatenating values with the same keys
* @param {TReactCSSThemrTheme} [original] - Original theme object
* @param {TReactCSSThemrTheme} [mixin] - Mixing theme object
* @returns {TReactCSSThemrTheme} - Merged resulting theme
*/
export function themeable(original = {}, mixin) {
//don't merge if no mixin is passed
if (!mixin) return original
//merge themes by concatenating values with the same keys
return Object.keys(mixin).reduce(
//merging reducer
(result, key) => {
const originalValue = original[key] || ''
const mixinValue = mixin[key] || ''
let newValue
//when you are mixing an string with a object it should fail
invariant(!(typeof originalValue === 'string' && typeof mixinValue === 'object'),
`You are merging a string "${originalValue}" with an Object,` +
'Make sure you are passing the proper theme descriptors.'
)
//check if values are nested objects
if (typeof originalValue === 'object' && typeof mixinValue === 'object') {
//go recursive
newValue = themeable(originalValue, mixinValue)
} else {
//either concat or take mixin value
newValue = originalValue.split(' ')
.concat(mixinValue.split(' '))
.filter((item, pos, self) => self.indexOf(item) === pos && item !== '')
.join(' ')
}
return {
...result,
[key]: newValue
}
},
//use original theme as an acc
original
)
}
/**
* Validates compose option
* @param {String|Boolean} composeTheme - Compose them option
* @throws
* @returns {undefined}
*/
function validateComposeOption(composeTheme) {
if ([ COMPOSE_DEEPLY, COMPOSE_SOFTLY, DONT_COMPOSE ].indexOf(composeTheme) === -1) {
throw new Error(
`Invalid composeTheme option for react-css-themr. Valid composition options\
are ${COMPOSE_DEEPLY}, ${COMPOSE_SOFTLY} and ${DONT_COMPOSE}. The given\
option was ${composeTheme}`
)
}
}
/**
* Removes namespace from key
* @param {String} key - Key
* @param {String} themeNamespace - Theme namespace
* @returns {String} - Key
*/
function removeNamespace(key, themeNamespace) {
const capitalized = key.substr(themeNamespace.length)
return capitalized.slice(0, 1).toLowerCase() + capitalized.slice(1)
}