UNPKG

2.77 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = void 0;
7
8var _helperPluginUtils = require("@babel/helper-plugin-utils");
9
10var _core = require("@babel/core");
11
12var _helperAnnotateAsPure = _interopRequireDefault(require("@babel/helper-annotate-as-pure"));
13
14function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
16var _default = (0, _helperPluginUtils.declare)((api, options) => {
17 api.assertVersion(7);
18 const {
19 allowMutablePropsOnTags
20 } = options;
21
22 if (allowMutablePropsOnTags != null && !Array.isArray(allowMutablePropsOnTags)) {
23 throw new Error(".allowMutablePropsOnTags must be an array, null, or undefined.");
24 }
25
26 const HOISTED = new WeakSet();
27 const immutabilityVisitor = {
28 enter(path, state) {
29 const stop = () => {
30 state.isImmutable = false;
31 path.stop();
32 };
33
34 if (path.isJSXClosingElement()) {
35 path.skip();
36 return;
37 }
38
39 if (path.isJSXIdentifier({
40 name: "ref"
41 }) && path.parentPath.isJSXAttribute({
42 name: path.node
43 })) {
44 return stop();
45 }
46
47 if (path.isJSXIdentifier() || path.isIdentifier() || path.isJSXMemberExpression()) {
48 return;
49 }
50
51 if (!path.isImmutable()) {
52 if (path.isPure()) {
53 const expressionResult = path.evaluate();
54
55 if (expressionResult.confident) {
56 const {
57 value
58 } = expressionResult;
59 const isMutable = !state.mutablePropsAllowed && value && typeof value === "object" || typeof value === "function";
60
61 if (!isMutable) {
62 path.skip();
63 return;
64 }
65 } else if (_core.types.isIdentifier(expressionResult.deopt)) {
66 return;
67 }
68 }
69
70 stop();
71 }
72 }
73
74 };
75 return {
76 name: "transform-react-constant-elements",
77 visitor: {
78 JSXElement(path) {
79 if (HOISTED.has(path.node)) return;
80 HOISTED.add(path.node);
81 const state = {
82 isImmutable: true
83 };
84
85 if (allowMutablePropsOnTags != null) {
86 let namePath = path.get("openingElement.name");
87
88 while (namePath.isJSXMemberExpression()) {
89 namePath = namePath.get("property");
90 }
91
92 const elementName = namePath.node.name;
93 state.mutablePropsAllowed = allowMutablePropsOnTags.indexOf(elementName) > -1;
94 }
95
96 path.traverse(immutabilityVisitor, state);
97
98 if (state.isImmutable) {
99 const hoisted = path.hoist();
100
101 if (hoisted) {
102 (0, _helperAnnotateAsPure.default)(hoisted);
103 }
104 }
105 }
106
107 }
108 };
109});
110
111exports.default = _default;
\No newline at end of file