UNPKG

1.75 kBJavaScriptView Raw
1import flatten from 'array.prototype.flatten';
2import globalCache from 'global-cache';
3
4import { GLOBAL_CACHE_KEY } from './utils/constants';
5import getClassName from './utils/getClassName';
6import separateStyles from './utils/separateStyles';
7
8/**
9 * Function required as part of the react-with-styles interface. Parses the styles provided by
10 * react-with-styles to produce class names based on the style name and optionally the namespace if
11 * available.
12 *
13 * stylesObject {Object} The styles object passed to withStyles.
14 *
15 * Return an object mapping style names to class names.
16 */
17function create(stylesObject) {
18 const stylesToClasses = {};
19 const styleNames = Object.keys(stylesObject);
20 const sharedState = globalCache.get(GLOBAL_CACHE_KEY) || {};
21 const { namespace = '' } = sharedState;
22 styleNames.forEach((styleName) => {
23 const className = getClassName(namespace, styleName);
24 stylesToClasses[styleName] = className;
25 });
26 return stylesToClasses;
27}
28
29/**
30 * Process styles to be consumed by a component.
31 *
32 * stylesArray {Array} Array of the following: values returned by create, plain JavaScript objects
33 * representing inline styles, or arrays thereof.
34 *
35 * Return an object with optional className and style properties to be spread on a component.
36 */
37function resolve(stylesArray) {
38 const flattenedStyles = flatten(stylesArray, Infinity);
39 const { classNames, hasInlineStyles, inlineStyles } = separateStyles(flattenedStyles);
40 const specificClassNames = classNames.map((name, index) => `${name} ${name}_${index + 1}`);
41 const className = specificClassNames.join(' ');
42
43 const result = { className };
44 if (hasInlineStyles) result.style = inlineStyles;
45 return result;
46}
47
48export default { create, resolve };