-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy paththemr.js
306 lines (266 loc) · 8.55 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import hoistNonReactStatics from 'hoist-non-react-statics'
import invariant from 'invariant'
/**
* @typedef {Object.<string, TReactCSSThemrTheme>} TReactCSSThemrTheme
*/
/**
* @typedef {{}} TReactCSSThemrOptions
* @property {String|Boolean} [composeTheme=COMPOSE_DEEPLY]
*/
const COMPOSE_DEEPLY = 'deeply'
const COMPOSE_SOFTLY = 'softly'
const DONT_COMPOSE = false
const DEFAULT_OPTIONS = {
composeTheme: COMPOSE_DEEPLY,
mapThemrProps: defaultMapThemrProps
}
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,
mapThemrProps: optionMapThemrProps
} = { ...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 ]),
innerRef: PropTypes.func,
theme: PropTypes.object,
themeNamespace: PropTypes.string,
mapThemrProps: PropTypes.func
}
static defaultProps = {
...ThemedComponent.defaultProps,
composeTheme: optionComposeTheme,
mapThemrProps: optionMapThemrProps
}
constructor(...args) {
super(...args)
this.theme_ = this.calcTheme(this.props)
}
getWrappedInstance() {
invariant(true,
'DEPRECATED: To access the wrapped instance, you have to pass ' +
'{ innerRef: fn } and retrieve with a callback ref style.'
)
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() {
return React.createElement(
ThemedComponent,
this.props.mapThemrProps(this.props, this.theme_)
)
}
}
Themed[THEMR_CONFIG] = config
return hoistNonReactStatics(Themed, ThemedComponent)
}
/**
* Merges passed themes by concatenating string keys and processing nested themes
*
* @param {...TReactCSSThemrTheme} themes - Themes
* @returns {TReactCSSThemrTheme} - Resulting theme
*/
export function themeable(...themes) {
return themes.reduce((acc, theme) => merge(acc, theme), {})
}
/**
* @param {TReactCSSThemrTheme} [original] - Original theme
* @param {TReactCSSThemrTheme} [mixin] - Mixin theme
* @returns {TReactCSSThemrTheme} - resulting theme
*/
function merge(original = {}, mixin = {}) {
//make a copy to avoid mutations of nested objects
//also strip all functions injected by isomorphic-style-loader
const result = Object.keys(original).reduce((acc, key) => {
const value = original[key]
if (typeof value !== 'function') {
acc[key] = value
}
return acc
}, {})
//traverse mixin keys and merge them to resulting theme
Object.keys(mixin).forEach(key => {
//there's no need to set any defaults here
const originalValue = result[key]
const mixinValue = mixin[key]
switch (typeof mixinValue) {
case 'object': {
//possibly nested theme object
switch (typeof originalValue) {
case 'object': {
//exactly nested theme object - go recursive
result[key] = merge(originalValue, mixinValue)
break
}
case 'undefined': {
//original does not contain this nested key - just take it as is
result[key] = mixinValue
break
}
default: {
//can't merge an object with a non-object
throw new Error(`You are merging object ${key} with a non-object ${originalValue}`)
}
}
break
}
case 'undefined': //fallthrough - handles accidentally unset values which may come from props
case 'function': {
//this handles issue when isomorphic-style-loader addes helper functions to css-module
break //just skip
}
default: {
//plain values
switch (typeof originalValue) {
case 'object': {
//can't merge a non-object with an object
throw new Error(`You are merging non-object ${mixinValue} with an object ${key}`)
}
case 'undefined': {
//mixin key is new to original theme - take it as is
result[key] = mixinValue
break
}
case 'function': {
//this handles issue when isomorphic-style-loader addes helper functions to css-module
break //just skip
}
default: {
//finally we can merge
result[key] = originalValue.split(' ')
.concat(mixinValue.split(' '))
.filter((item, pos, self) => self.indexOf(item) === pos && item !== '')
.join(' ')
break
}
}
break
}
}
})
return result
}
/**
* 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)
}
/**
* Maps props and theme to an object that will be used to pass down props to the
* decorated component.
*
* @param {Object} ownProps - All props given to the decorated component
* @param {Object} theme - Calculated then that should be passed down
* @returns {Object} - Props that will be passed down to the decorated component
*/
function defaultMapThemrProps(ownProps, theme) {
const {
composeTheme, //eslint-disable-line no-unused-vars
innerRef,
themeNamespace, //eslint-disable-line no-unused-vars
mapThemrProps, //eslint-disable-line no-unused-vars
...rest
} = ownProps
return {
...rest,
ref: innerRef,
theme
}
}