This repository has been archived by the owner on Aug 19, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 308
/
Copy pathresolve-styles.js
488 lines (424 loc) · 13 KB
/
resolve-styles.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
/* @flow */
import type {Config} from './config';
import appendImportantToEachValue from './append-important-to-each-value';
import cssRuleSetToString from './css-rule-set-to-string';
import getState from './get-state';
import getStateKey from './get-state-key';
import cleanStateKey from './clean-state-key';
import getRadiumStyleState from './get-radium-style-state';
import hash from './hash';
import {isNestedStyle, mergeStyles} from './merge-styles';
import Plugins from './plugins/';
import ExecutionEnvironment from 'exenv';
import React from 'react';
import StyleKeeper from './style-keeper';
const DEFAULT_CONFIG = {
plugins: [
Plugins.mergeStyleArray,
Plugins.checkProps,
Plugins.resolveMediaQueries,
Plugins.resolveInteractionStyles,
Plugins.keyframes,
Plugins.visited,
Plugins.removeNestedStyles,
Plugins.prefix,
Plugins.checkProps
]
};
// Gross
let globalState = {};
// Only for use by tests
let __isTestModeEnabled = false;
export type EnhancerApi = {
state: Object,
setState: Function,
_radiumMediaQueryListenersByQuery?: {
[query: string]: {remove: () => void}
},
_radiumMouseUpListener?: {remove: () => void},
_radiumIsMounted: boolean,
_lastRadiumState: Object,
_extraRadiumStateKeys: any,
_radiumStyleKeeper?: StyleKeeper
};
type ResolvedStyles = {
extraStateKeyMap: {[key: string]: boolean},
element: any
};
// Declare early for recursive helpers.
let resolveStyles = ((null: any): (
component: any, // ReactComponent, flow+eslint complaining
renderedElement: any,
config: Config,
existingKeyMap: {[key: string]: boolean},
shouldCheckBeforeResolve: boolean,
extraStateKeyMap?: {[key: string]: boolean}
) => ResolvedStyles);
const _shouldResolveStyles = function(component) {
return component.type && !component.type._isRadiumEnhanced;
};
const _resolveChildren = function({
children,
component,
config,
existingKeyMap,
extraStateKeyMap
}) {
if (!children) {
return children;
}
const childrenType = typeof children;
if (childrenType === 'string' || childrenType === 'number') {
// Don't do anything with a single primitive child
return children;
}
if (childrenType === 'function') {
// Wrap the function, resolving styles on the result
return function() {
const result = children.apply(this, arguments);
if (React.isValidElement(result)) {
const key = getStateKey(result);
delete extraStateKeyMap[key];
const {element} = resolveStyles(
component,
result,
config,
existingKeyMap,
true,
extraStateKeyMap
);
return element;
}
return result;
};
}
if (React.Children.count(children) === 1 && children.type) {
// If a React Element is an only child, don't wrap it in an array for
// React.Children.map() for React.Children.only() compatibility.
const onlyChild = React.Children.only(children);
const key = getStateKey(onlyChild);
delete extraStateKeyMap[key];
const {element} = resolveStyles(
component,
onlyChild,
config,
existingKeyMap,
true,
extraStateKeyMap
);
return element;
}
return React.Children.map(children, function(child) {
if (React.isValidElement(child)) {
const key = getStateKey(child);
delete extraStateKeyMap[key];
const {element} = resolveStyles(
component,
child,
config,
existingKeyMap,
true,
extraStateKeyMap
);
return element;
}
return child;
});
};
// Recurse over props, just like children
const _resolveProps = function({
component,
config,
existingKeyMap,
props,
extraStateKeyMap
}) {
let newProps = props;
Object.keys(props).forEach(prop => {
// We already recurse over children above
if (prop === 'children') {
return;
}
const propValue = props[prop];
if (React.isValidElement(propValue)) {
const key = getStateKey(propValue);
delete extraStateKeyMap[key];
newProps = {...newProps};
const {element} = resolveStyles(
component,
propValue,
config,
existingKeyMap,
true,
extraStateKeyMap
);
newProps[prop] = element;
}
});
return newProps;
};
const _buildGetKey = function({
componentName,
existingKeyMap,
renderedElement
}) {
// We need a unique key to correlate state changes due to user interaction
// with the rendered element, so we know to apply the proper interactive
// styles.
const originalKey = getStateKey(renderedElement);
const key = cleanStateKey(originalKey);
let alreadyGotKey = false;
const getKey = function() {
if (alreadyGotKey) {
return key;
}
alreadyGotKey = true;
if (existingKeyMap[key]) {
let elementName;
if (typeof renderedElement.type === 'string') {
elementName = renderedElement.type;
} else if (renderedElement.type.constructor) {
elementName =
renderedElement.type.constructor.displayName ||
renderedElement.type.constructor.name;
}
throw new Error(
'Radium requires each element with interactive styles to have a unique ' +
'key, set using either the ref or key prop. ' +
(originalKey
? 'Key "' + originalKey + '" is a duplicate.'
: 'Multiple elements have no key specified.') +
' ' +
'Component: "' +
componentName +
'". ' +
(elementName ? 'Element: "' + elementName + '".' : '')
);
}
existingKeyMap[key] = true;
return key;
};
return getKey;
};
const _setStyleState = function(component, key, stateKey, value) {
if (!component._radiumIsMounted) {
return;
}
const existing = getRadiumStyleState(component);
const state = {_radiumStyleState: {...existing}};
state._radiumStyleState[key] = {...state._radiumStyleState[key]};
state._radiumStyleState[key][stateKey] = value;
component._lastRadiumState = state._radiumStyleState;
component.setState(state);
};
const _runPlugins = function({
component,
config,
existingKeyMap,
props,
renderedElement
}) {
// Don't run plugins if renderedElement is not a simple ReactDOMElement or has
// no style.
if (
!React.isValidElement(renderedElement) ||
typeof renderedElement.type !== 'string' ||
!props.style
) {
return props;
}
let newProps = props;
const plugins = config.plugins || DEFAULT_CONFIG.plugins;
const componentName =
component.constructor.displayName || component.constructor.name;
const getKey = _buildGetKey({
renderedElement,
existingKeyMap,
componentName
});
const getComponentField = key => component[key];
const getGlobalState = key => globalState[key];
const componentGetState = (stateKey, elementKey) =>
getState(component.state, elementKey || getKey(), stateKey);
const setState = (stateKey, value, elementKey) =>
_setStyleState(component, elementKey || getKey(), stateKey, value);
const addCSS = css => {
const styleKeeper = component._radiumStyleKeeper;
if (!styleKeeper) {
if (__isTestModeEnabled) {
return {remove() {}};
}
throw new Error(
'To use plugins requiring `addCSS` (e.g. keyframes, media queries), ' +
'please wrap your application in the StyleRoot component. Component ' +
'name: `' +
componentName +
'`.'
);
}
return styleKeeper.addCSS(css);
};
let newStyle = props.style;
plugins.forEach(plugin => {
const result =
plugin({
ExecutionEnvironment,
addCSS,
appendImportantToEachValue,
componentName,
config,
cssRuleSetToString,
getComponentField,
getGlobalState,
getState: componentGetState,
hash,
mergeStyles,
props: newProps,
setState,
isNestedStyle,
style: newStyle
}) || {};
newStyle = result.style || newStyle;
newProps =
result.props && Object.keys(result.props).length
? {...newProps, ...result.props}
: newProps;
const newComponentFields = result.componentFields || {};
Object.keys(newComponentFields).forEach(fieldName => {
component[fieldName] = newComponentFields[fieldName];
});
const newGlobalState = result.globalState || {};
Object.keys(newGlobalState).forEach(key => {
globalState[key] = newGlobalState[key];
});
});
if (newStyle !== props.style) {
newProps = {...newProps, style: newStyle};
}
return newProps;
};
// Wrapper around React.cloneElement. To avoid processing the same element
// twice, whenever we clone an element add a special prop to make sure we don't
// process this element again.
const _cloneElement = function(renderedElement, newProps, newChildren) {
// Only add flag if this is a normal DOM element
if (typeof renderedElement.type === 'string') {
newProps = {...newProps, 'data-radium': true};
}
return React.cloneElement(renderedElement, newProps, newChildren);
};
//
// The nucleus of Radium. resolveStyles is called on the rendered elements
// before they are returned in render. It iterates over the elements and
// children, rewriting props to add event handlers required to capture user
// interactions (e.g. mouse over). It also replaces the style prop because it
// adds in the various interaction styles (e.g. :hover).
//
/* eslint-disable max-params */
resolveStyles = function(
component: EnhancerApi,
renderedElement: any, // ReactElement
config: Config = DEFAULT_CONFIG,
existingKeyMap: {[key: string]: boolean} = {},
shouldCheckBeforeResolve: boolean = false,
extraStateKeyMap?: {[key: string]: boolean}
): ResolvedStyles {
// The extraStateKeyMap is for determining which keys should be erased from
// the state (i.e. which child components are unmounted and should no longer
// have a style state).
if (!extraStateKeyMap) {
const state = getRadiumStyleState(component);
extraStateKeyMap = Object.keys(state).reduce((acc, key) => {
// 'main' is the auto-generated key when there is only one element with
// interactive styles and if a custom key is not assigned. Because of
// this, it is impossible to know which child is 'main', so we won't
// count this key when generating our extraStateKeyMap.
if (key !== 'main') {
acc[key] = true;
}
return acc;
}, {});
}
if (Array.isArray(renderedElement) && !renderedElement.props) {
const elements = renderedElement.map(element => {
// element is in-use, so remove from the extraStateKeyMap
if (extraStateKeyMap) {
const key = getStateKey(element);
delete extraStateKeyMap[key];
}
// this element is an array of elements,
// so return an array of elements with resolved styles
return resolveStyles(
component,
element,
config,
existingKeyMap,
shouldCheckBeforeResolve,
extraStateKeyMap
).element;
});
return {
extraStateKeyMap,
element: elements
};
}
// ReactElement
if (
!renderedElement ||
// Bail if we've already processed this element. This ensures that only the
// owner of an element processes that element, since the owner's render
// function will be called first (which will always be the case, since you
// can't know what else to render until you render the parent component).
(renderedElement.props && renderedElement.props['data-radium']) ||
// Bail if this element is a radium enhanced element, because if it is,
// then it will take care of resolving its own styles.
(shouldCheckBeforeResolve && !_shouldResolveStyles(renderedElement))
) {
return {extraStateKeyMap, element: renderedElement};
}
const children = renderedElement.props.children;
const newChildren = _resolveChildren({
children,
component,
config,
existingKeyMap,
extraStateKeyMap
});
let newProps = _resolveProps({
component,
config,
existingKeyMap,
extraStateKeyMap,
props: renderedElement.props
});
newProps = _runPlugins({
component,
config,
existingKeyMap,
props: newProps,
renderedElement
});
// If nothing changed, don't bother cloning the element. Might be a bit
// wasteful, as we add the sentinel to stop double-processing when we clone.
// Assume benign double-processing is better than unneeded cloning.
if (newChildren === children && newProps === renderedElement.props) {
return {extraStateKeyMap, element: renderedElement};
}
const element = _cloneElement(
renderedElement,
newProps !== renderedElement.props ? newProps : {},
newChildren
);
return {extraStateKeyMap, element};
};
/* eslint-enable max-params */
// Only for use by tests
if (process.env.NODE_ENV !== 'production') {
resolveStyles.__clearStateForTests = function() {
globalState = {};
};
resolveStyles.__setTestMode = function(isEnabled) {
__isTestModeEnabled = isEnabled;
};
}
export default resolveStyles;