UNPKG

2.24 kBJavaScriptView Raw
1import { from as flatten } from 'array-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);
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
48/**
49 * Register a namespace to use for constructing unique class names.
50 *
51 * CSSInterfaceNamespace {String} The namespace to be used. e.g. Name of the project
52 */
53function registerCSSInterfaceNamespace(CSSInterfaceNamespace) {
54 const sharedState = globalCache.get(GLOBAL_CACHE_KEY);
55 if (!sharedState) {
56 globalCache.set(GLOBAL_CACHE_KEY, { namespace: CSSInterfaceNamespace });
57 } else {
58 sharedState.namespace = CSSInterfaceNamespace;
59 }
60}
61
62export default { create, resolve };
63export { registerCSSInterfaceNamespace };