-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
replaceJsxExpressionContainer.js
92 lines (84 loc) · 2.81 KB
/
replaceJsxExpressionContainer.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
// @flow
import BabelTypes, {
binaryExpression,
Identifier,
isJSXExpressionContainer,
isStringLiteral,
jSXAttribute,
JSXAttribute,
jSXExpressionContainer,
jSXIdentifier
} from '@babel/types';
import type {
GetClassNameOptionsType
} from './types';
import conditionalClassMerge from './conditionalClassMerge';
import createObjectExpression from './createObjectExpression';
import optionsDefaults from './schemas/optionsDefaults';
export default (
t: BabelTypes,
// eslint-disable-next-line flowtype/no-weak-types
path: Object,
sourceAttribute: JSXAttribute,
destinationName: string,
importedHelperIndentifier: Identifier,
styleModuleImportMapIdentifier: Identifier,
options: GetClassNameOptionsType
): void => {
const expressionContainerValue = sourceAttribute.value;
const destinationAttribute = path.node.openingElement.attributes
.find((attribute) => {
return typeof attribute.name !== 'undefined' && attribute.name.name === destinationName;
});
if (destinationAttribute) {
path.node.openingElement.attributes.splice(path.node.openingElement.attributes.indexOf(destinationAttribute), 1);
}
path.node.openingElement.attributes.splice(path.node.openingElement.attributes.indexOf(sourceAttribute), 1);
const args = [
expressionContainerValue.expression,
styleModuleImportMapIdentifier
];
// Only provide options argument if the options are something other than default
// This helps save a few bits in the generated user code
if (options.handleMissingStyleName !== optionsDefaults.handleMissingStyleName ||
options.autoResolveMultipleImports !== optionsDefaults.autoResolveMultipleImports) {
args.push(createObjectExpression(t, options));
}
const styleNameExpression = t.callExpression(
t.clone(importedHelperIndentifier),
args
);
if (destinationAttribute) {
if (isStringLiteral(destinationAttribute.value)) {
path.node.openingElement.attributes.push(jSXAttribute(
jSXIdentifier(destinationName),
jSXExpressionContainer(
binaryExpression(
'+',
t.stringLiteral(destinationAttribute.value.value + ' '),
styleNameExpression
)
)
));
} else if (isJSXExpressionContainer(destinationAttribute.value)) {
path.node.openingElement.attributes.push(jSXAttribute(
jSXIdentifier(destinationName),
jSXExpressionContainer(
conditionalClassMerge(
destinationAttribute.value.expression,
styleNameExpression
)
)
));
} else {
throw new Error('Unexpected attribute value: ' + destinationAttribute.value);
}
} else {
path.node.openingElement.attributes.push(jSXAttribute(
jSXIdentifier(destinationName),
jSXExpressionContainer(
styleNameExpression
)
));
}
};