-
-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathresolveStringLiteral.js
49 lines (45 loc) · 1.58 KB
/
resolveStringLiteral.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
// @flow
import {
isJSXExpressionContainer,
isStringLiteral,
JSXAttribute,
stringLiteral
} from '@babel/types';
import conditionalClassMerge from './conditionalClassMerge';
import getClassName from './getClassName';
import type {
StyleModuleImportMapType,
GetClassNameOptionsType
} from './types';
/**
* Updates the className value of a JSX element using a provided styleName attribute.
*/
export default (
path: *,
styleModuleImportMap: StyleModuleImportMapType,
sourceAttribute: JSXAttribute,
destinationName: string,
options: GetClassNameOptionsType
): void => {
const resolvedStyleName = getClassName(sourceAttribute.value.value, styleModuleImportMap, options);
const destinationAttribute = path.node.openingElement.attributes
.find((attribute) => {
return typeof attribute.name !== 'undefined' && attribute.name.name === destinationName;
});
if (destinationAttribute) {
if (isStringLiteral(destinationAttribute.value)) {
destinationAttribute.value.value += ' ' + resolvedStyleName;
} else if (isJSXExpressionContainer(destinationAttribute.value)) {
destinationAttribute.value.expression = conditionalClassMerge(
destinationAttribute.value.expression,
stringLiteral(resolvedStyleName)
);
} else {
throw new Error('Unexpected attribute value:' + destinationAttribute.value);
}
path.node.openingElement.attributes.splice(path.node.openingElement.attributes.indexOf(sourceAttribute), 1);
} else {
sourceAttribute.name.name = destinationName;
sourceAttribute.value.value = resolvedStyleName;
}
};