UNPKG

12.5 kBJavaScriptView Raw
1"use strict";
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports.default = _default;
7
8var _babelPluginSyntaxJsx = _interopRequireDefault(require("babel-plugin-syntax-jsx"));
9
10var _babelExternal = require("./babel-external");
11
12var _utils = require("./_utils");
13
14var _constants = require("./_constants");
15
16function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
17
18function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
19
20function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
21
22function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
23
24function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
25
26function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
27
28function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
29
30function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); }
31
32function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); }
33
34function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); }
35
36function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } }
37
38function _default(_ref) {
39 var t = _ref.types;
40 var jsxVisitors = {
41 JSXOpeningElement: function JSXOpeningElement(path, state) {
42 var el = path.node;
43
44 var _ref2 = el.name || {},
45 name = _ref2.name;
46
47 if (!state.hasJSXStyle) {
48 return;
49 }
50
51 if (state.ignoreClosing === null) {
52 // We keep a counter of elements inside so that we
53 // can keep track of when we exit the parent to reset state
54 // note: if we wished to add an option to turn off
55 // selectors to reach parent elements, it would suffice to
56 // set this to `1` and do an early return instead
57 state.ignoreClosing = 0;
58 }
59
60 var tag = path.get('name');
61
62 if (name && name !== 'style' && name !== _constants.STYLE_COMPONENT && (name.charAt(0) !== name.charAt(0).toUpperCase() || Object.values(path.scope.bindings).some(function (binding) {
63 return binding.referencePaths.some(function (r) {
64 return r === tag;
65 });
66 }))) {
67 if (state.className) {
68 (0, _utils.addClassName)(path, state.className);
69 }
70 }
71
72 state.ignoreClosing++; // Next visit will be: JSXElement exit()
73 },
74 JSXElement: {
75 enter: function enter(path, state) {
76 if (state.hasJSXStyle !== null) {
77 return;
78 }
79
80 var styles = (0, _utils.findStyles)(path);
81
82 if (styles.length === 0) {
83 return;
84 }
85
86 state.styles = [];
87 state.externalStyles = [];
88 var scope = (0, _utils.getScope)(path);
89 var _iteratorNormalCompletion = true;
90 var _didIteratorError = false;
91 var _iteratorError = undefined;
92
93 try {
94 for (var _iterator = styles[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
95 var style = _step.value;
96 // Compute children excluding whitespace
97 var children = style.get('children').filter(function (c) {
98 return t.isJSXExpressionContainer(c.node) || // Ignore whitespace around the expression container
99 t.isJSXText(c.node) && c.node.value.trim() !== '';
100 });
101
102 if (children.length !== 1) {
103 throw path.buildCodeFrameError("Expected one child under " + "JSX Style tag, but got ".concat(children.length, " ") + "(eg: <style jsx>{`hi`}</style>)");
104 }
105
106 var child = children[0];
107
108 if (!t.isJSXExpressionContainer(child)) {
109 throw path.buildCodeFrameError("Expected a child of " + "type JSXExpressionContainer under JSX Style tag " + "(eg: <style jsx>{`hi`}</style>), got ".concat(child.type));
110 }
111
112 var expression = child.get('expression');
113
114 if (t.isIdentifier(expression)) {
115 var idName = expression.node.name;
116
117 if (expression.scope.hasBinding(idName)) {
118 var externalStylesIdentifier = t.identifier(idName);
119 var isGlobal = (0, _utils.isGlobalEl)(style.get('openingElement').node);
120 state.externalStyles.push([t.memberExpression(externalStylesIdentifier, t.identifier('__hash')), externalStylesIdentifier, isGlobal]);
121 continue;
122 }
123
124 throw path.buildCodeFrameError("The Identifier " + "`".concat(expression.getSource(), "` is either `undefined` or ") + "it is not an external StyleSheet reference i.e. " + "it doesn't come from an `import` or `require` statement");
125 }
126
127 if (!t.isTemplateLiteral(expression) && !t.isStringLiteral(expression)) {
128 throw path.buildCodeFrameError("Expected a template " + "literal or String literal as the child of the " + "JSX Style tag (eg: <style jsx>{`some css`}</style>)," + " but got ".concat(expression.type));
129 }
130
131 state.styles.push((0, _utils.getJSXStyleInfo)(expression, scope));
132 }
133 } catch (err) {
134 _didIteratorError = true;
135 _iteratorError = err;
136 } finally {
137 try {
138 if (!_iteratorNormalCompletion && _iterator.return != null) {
139 _iterator.return();
140 }
141 } finally {
142 if (_didIteratorError) {
143 throw _iteratorError;
144 }
145 }
146 }
147
148 var externalJsxId;
149
150 if (state.externalStyles.length > 0) {
151 var expressions = state.externalStyles // Remove globals
152 .filter(function (s) {
153 return !s[2];
154 }).map(function (s) {
155 return s[0];
156 });
157 var expressionsLength = expressions.length;
158
159 if (expressionsLength === 0) {
160 externalJsxId = null;
161 } else {
162 // Construct a template literal of this form:
163 // `jsx-${styles.__scopedHash} jsx-${otherStyles.__scopedHash}`
164 externalJsxId = t.templateLiteral([t.templateElement({
165 raw: 'jsx-',
166 cooked: 'jsx-'
167 })].concat(_toConsumableArray(_toConsumableArray(new Array(expressionsLength - 1)).map(function () {
168 return t.templateElement({
169 raw: ' jsx-',
170 cooked: ' jsx-'
171 });
172 })), [t.templateElement({
173 raw: '',
174 cooked: ''
175 }, true)]), expressions);
176 }
177 }
178
179 if (state.styles.length > 0 || externalJsxId) {
180 var _computeClassNames = (0, _utils.computeClassNames)(state.styles, externalJsxId),
181 staticClassName = _computeClassNames.staticClassName,
182 className = _computeClassNames.className;
183
184 state.className = className;
185 state.staticClassName = staticClassName;
186 }
187
188 state.hasJSXStyle = true;
189 state.file.hasJSXStyle = true; // Next visit will be: JSXOpeningElement
190 },
191 exit: function exit(path, state) {
192 var isGlobal = (0, _utils.isGlobalEl)(path.node.openingElement);
193
194 if (state.hasJSXStyle && ! --state.ignoreClosing && !isGlobal) {
195 state.hasJSXStyle = null;
196 state.className = null;
197 state.externalJsxId = null;
198 }
199
200 if (!state.hasJSXStyle || !(0, _utils.isStyledJsx)(path)) {
201 return;
202 }
203
204 if (state.ignoreClosing > 1) {
205 var styleTagSrc;
206
207 try {
208 styleTagSrc = path.getSource();
209 } catch (error) {}
210
211 throw path.buildCodeFrameError('Detected nested style tag' + (styleTagSrc ? ": \n\n".concat(styleTagSrc, "\n\n") : ' ') + 'styled-jsx only allows style tags ' + 'to be direct descendants (children) of the outermost ' + 'JSX element i.e. the subtree root.');
212 }
213
214 if (state.externalStyles.length > 0 && path.get('children').filter(function (child) {
215 if (!t.isJSXExpressionContainer(child)) {
216 return false;
217 }
218
219 var expression = child.get('expression');
220 return expression && expression.isIdentifier();
221 }).length === 1) {
222 var _state$externalStyles = state.externalStyles.shift(),
223 _state$externalStyles2 = _slicedToArray(_state$externalStyles, 2),
224 id = _state$externalStyles2[0],
225 _css = _state$externalStyles2[1];
226
227 path.replaceWith((0, _utils.makeStyledJsxTag)(id, _css));
228 return;
229 }
230
231 var _state$opts = state.opts,
232 vendorPrefixes = _state$opts.vendorPrefixes,
233 sourceMaps = _state$opts.sourceMaps;
234
235 var stylesInfo = _objectSpread({}, state.styles.shift(), {
236 file: state.file,
237 staticClassName: state.staticClassName,
238 isGlobal: isGlobal,
239 plugins: state.plugins,
240 vendorPrefixes: vendorPrefixes,
241 sourceMaps: sourceMaps
242 });
243
244 var splitRules = typeof state.opts.optimizeForSpeed === 'boolean' ? state.opts.optimizeForSpeed : process.env.NODE_ENV === 'production';
245
246 var _processCss = (0, _utils.processCss)(stylesInfo, {
247 splitRules: splitRules
248 }),
249 hash = _processCss.hash,
250 css = _processCss.css,
251 expressions = _processCss.expressions;
252
253 path.replaceWith((0, _utils.makeStyledJsxTag)(hash, css, expressions));
254 }
255 } // only apply JSXFragment visitor if supported
256
257 };
258
259 if (t.isJSXFragment) {
260 jsxVisitors.JSXFragment = jsxVisitors.JSXElement;
261 jsxVisitors.JSXOpeningFragment = {
262 enter: function enter(path, state) {
263 if (!state.hasJSXStyle) {
264 return;
265 }
266
267 if (state.ignoreClosing === null) {
268 // We keep a counter of elements inside so that we
269 // can keep track of when we exit the parent to reset state
270 // note: if we wished to add an option to turn off
271 // selectors to reach parent elements, it would suffice to
272 // set this to `1` and do an early return instead
273 state.ignoreClosing = 0;
274 }
275
276 state.ignoreClosing++;
277 }
278 };
279 }
280
281 var visitors = {
282 inherits: _babelPluginSyntaxJsx.default,
283 visitor: _objectSpread({
284 Program: {
285 enter: function enter(path, state) {
286 state.hasJSXStyle = null;
287 state.ignoreClosing = null;
288 state.file.hasJSXStyle = false;
289 (0, _utils.setStateOptions)(state); // we need to beat the arrow function transform and
290 // possibly others so we traverse from here or else
291 // dynamic values in classNames could be incorrect
292
293 path.traverse(jsxVisitors, state);
294 },
295 exit: function exit(_ref3, state) {
296 var node = _ref3.node,
297 scope = _ref3.scope;
298
299 if (!(state.file.hasJSXStyle && !state.hasInjectedJSXStyle && !scope.hasBinding(_constants.STYLE_COMPONENT))) {
300 return;
301 }
302
303 state.hasInjectedJSXStyle = true;
304 var importDeclaration = (0, _utils.createReactComponentImportDeclaration)();
305 node.body.unshift(importDeclaration);
306 }
307 }
308 }, _babelExternal.visitor)
309 };
310 return visitors;
311}
\No newline at end of file