@atlaskit/eslint-plugin-design-system 8.18.0 → 8.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cjs/rules/use-primitives/index.js +40 -35
  3. package/dist/cjs/rules/use-primitives/transformers/css-to-xcss.js +10 -3
  4. package/dist/cjs/rules/use-primitives/transformers/index.js +8 -1
  5. package/dist/cjs/rules/use-primitives/transformers/styled-component-to-primitive.js +68 -0
  6. package/dist/cjs/rules/use-primitives/utils/convert-ast-object-expression-to-js-object.js +16 -0
  7. package/dist/cjs/rules/use-primitives/utils/find-valid-jsx-usage-to-transform.js +39 -0
  8. package/dist/cjs/rules/use-primitives/utils/find-valid-styled-component-call.js +52 -0
  9. package/dist/cjs/rules/use-primitives/utils/index.js +21 -0
  10. package/dist/cjs/rules/use-primitives/utils/is-valid-css-properties-to-transform.js +38 -0
  11. package/dist/cjs/rules/use-primitives/utils/is-valid-tag-name.js +2 -2
  12. package/dist/cjs/rules/use-primitives/utils/update-jsx-element-name.js +1 -1
  13. package/dist/es2019/rules/use-primitives/index.js +41 -37
  14. package/dist/es2019/rules/use-primitives/transformers/css-to-xcss.js +9 -6
  15. package/dist/es2019/rules/use-primitives/transformers/index.js +2 -1
  16. package/dist/es2019/rules/use-primitives/transformers/styled-component-to-primitive.js +59 -0
  17. package/dist/es2019/rules/use-primitives/utils/convert-ast-object-expression-to-js-object.js +14 -0
  18. package/dist/es2019/rules/use-primitives/utils/find-valid-jsx-usage-to-transform.js +32 -0
  19. package/dist/es2019/rules/use-primitives/utils/find-valid-styled-component-call.js +47 -0
  20. package/dist/es2019/rules/use-primitives/utils/index.js +3 -0
  21. package/dist/es2019/rules/use-primitives/utils/is-valid-css-properties-to-transform.js +32 -0
  22. package/dist/es2019/rules/use-primitives/utils/is-valid-tag-name.js +1 -1
  23. package/dist/es2019/rules/use-primitives/utils/update-jsx-element-name.js +1 -1
  24. package/dist/esm/rules/use-primitives/index.js +41 -37
  25. package/dist/esm/rules/use-primitives/transformers/css-to-xcss.js +9 -2
  26. package/dist/esm/rules/use-primitives/transformers/index.js +2 -1
  27. package/dist/esm/rules/use-primitives/transformers/styled-component-to-primitive.js +61 -0
  28. package/dist/esm/rules/use-primitives/utils/convert-ast-object-expression-to-js-object.js +16 -0
  29. package/dist/esm/rules/use-primitives/utils/find-valid-jsx-usage-to-transform.js +34 -0
  30. package/dist/esm/rules/use-primitives/utils/find-valid-styled-component-call.js +47 -0
  31. package/dist/esm/rules/use-primitives/utils/index.js +3 -0
  32. package/dist/esm/rules/use-primitives/utils/is-valid-css-properties-to-transform.js +32 -0
  33. package/dist/esm/rules/use-primitives/utils/is-valid-tag-name.js +1 -1
  34. package/dist/esm/rules/use-primitives/utils/update-jsx-element-name.js +1 -1
  35. package/dist/types/rules/use-primitives/transformers/css-to-xcss.d.ts +2 -1
  36. package/dist/types/rules/use-primitives/transformers/index.d.ts +1 -0
  37. package/dist/types/rules/use-primitives/transformers/styled-component-to-primitive.d.ts +13 -0
  38. package/dist/types/rules/use-primitives/utils/convert-ast-object-expression-to-js-object.d.ts +1 -1
  39. package/dist/types/rules/use-primitives/utils/find-valid-jsx-usage-to-transform.d.ts +7 -0
  40. package/dist/types/rules/use-primitives/utils/find-valid-styled-component-call.d.ts +7 -0
  41. package/dist/types/rules/use-primitives/utils/index.d.ts +3 -0
  42. package/dist/types/rules/use-primitives/utils/is-valid-css-properties-to-transform.d.ts +3 -0
  43. package/dist/types/rules/use-primitives/utils/is-valid-tag-name.d.ts +1 -0
  44. package/dist/types/rules/use-primitives/utils/update-jsx-element-name.d.ts +1 -1
  45. package/dist/types-ts4.5/rules/use-primitives/transformers/css-to-xcss.d.ts +2 -1
  46. package/dist/types-ts4.5/rules/use-primitives/transformers/index.d.ts +1 -0
  47. package/dist/types-ts4.5/rules/use-primitives/transformers/styled-component-to-primitive.d.ts +13 -0
  48. package/dist/types-ts4.5/rules/use-primitives/utils/convert-ast-object-expression-to-js-object.d.ts +1 -1
  49. package/dist/types-ts4.5/rules/use-primitives/utils/find-valid-jsx-usage-to-transform.d.ts +7 -0
  50. package/dist/types-ts4.5/rules/use-primitives/utils/find-valid-styled-component-call.d.ts +7 -0
  51. package/dist/types-ts4.5/rules/use-primitives/utils/index.d.ts +3 -0
  52. package/dist/types-ts4.5/rules/use-primitives/utils/is-valid-css-properties-to-transform.d.ts +3 -0
  53. package/dist/types-ts4.5/rules/use-primitives/utils/is-valid-tag-name.d.ts +1 -0
  54. package/dist/types-ts4.5/rules/use-primitives/utils/update-jsx-element-name.d.ts +1 -1
  55. package/package.json +1 -1
@@ -0,0 +1,59 @@
1
+ import { isNodeOfType } from 'eslint-codemod-utils';
2
+ import { updateJSXElementName, upsertImportDeclaration } from '../utils';
3
+ import { styledObjectToXcssTokens } from './css-to-xcss';
4
+ /**
5
+ * All required validation steps have been taken care of before this
6
+ * transformer is called, so it just goes ahead providing all necessary fixes
7
+ */
8
+ export const styledComponentToPrimitive = ({
9
+ stylesRef,
10
+ jsxRef
11
+ }, context) => {
12
+ return fixer => {
13
+ // generates the new variable name: MyComponent -> myComponentStyles
14
+ const calculatedStylesVariableName = isNodeOfType(stylesRef.id, 'Identifier') && `${stylesRef.id.name.replace(stylesRef.id.name[0], stylesRef.id.name[0].toLowerCase())}Styles`;
15
+ if (!calculatedStylesVariableName) {
16
+ return [];
17
+ }
18
+ const importFixes = upsertImportDeclaration({
19
+ packageName: '@atlaskit/primitives',
20
+ specifiers: ['Box', 'xcss']
21
+ }, context, fixer);
22
+ const stylesFixes = convertStyledComponentToXcss(stylesRef, calculatedStylesVariableName, fixer);
23
+ const jsxFixes = convertJsxCallSite(jsxRef, calculatedStylesVariableName, fixer);
24
+ return [importFixes, ...stylesFixes, ...jsxFixes].filter(fix => Boolean(fix)); // Some of the transformers can return arrays with undefined, so filter them out
25
+ };
26
+ };
27
+
28
+ const convertStyledComponentToXcss = (stylesRef, newStylesVariableName, fixer) => {
29
+ const fixes = [];
30
+
31
+ // renames the variable from MyComponent to myComponentStyles
32
+ fixes.push(fixer.replaceText(stylesRef.id, newStylesVariableName));
33
+
34
+ // renames the function call from styled.<tag> to xcss
35
+ if (stylesRef.init && isNodeOfType(stylesRef.init, 'CallExpression')) {
36
+ fixes.push(fixer.replaceText(stylesRef.init.callee, 'xcss'));
37
+ }
38
+
39
+ // converts CSS values to XCSS-compatible tokens
40
+ if (stylesRef.init && isNodeOfType(stylesRef.init, 'CallExpression')) {
41
+ const objectExpression = stylesRef.init.arguments[0];
42
+ if (isNodeOfType(objectExpression, 'ObjectExpression')) {
43
+ fixes.push(...styledObjectToXcssTokens(objectExpression, fixer));
44
+ }
45
+ }
46
+ return fixes;
47
+ };
48
+ const convertJsxCallSite = (jsxRef, newStylesVariableName, fixer) => {
49
+ const fixes = [];
50
+
51
+ // renames the JSX call site
52
+ if (isNodeOfType(jsxRef.parent, 'JSXElement')) {
53
+ fixes.push(...updateJSXElementName(jsxRef.parent, 'Box', fixer));
54
+ }
55
+
56
+ // adds xcss prop
57
+ fixes.push(fixer.insertTextAfter(jsxRef.name, ` xcss={${newStylesVariableName}}`));
58
+ return fixes;
59
+ };
@@ -7,6 +7,20 @@ import { isNodeOfType } from 'eslint-codemod-utils';
7
7
  */
8
8
  export const convertASTObjectExpressionToJSObject = styles => {
9
9
  const styleObj = {};
10
+
11
+ // if we see any spread props we stop and return false to indicate this is unsupported
12
+ if (!styles.properties.every(prop => isNodeOfType(prop, 'Property'))) {
13
+ return false;
14
+ }
15
+
16
+ // TODO: We need to harden this logic.
17
+ // It currently generates a false positive for:
18
+ // styled.div({
19
+ // marginTop: "0px",
20
+ // marginBottom: token("space.100", "8px"),
21
+ // })
22
+ // as the value for `marginBottom` is not a string, so it is just skipped
23
+ // from the resulting map and this causes the rule to trigger when it shouldn't
10
24
  styles.properties.forEach(prop => {
11
25
  if (!isNodeOfType(prop, 'Property')) {
12
26
  return;
@@ -0,0 +1,32 @@
1
+ import { isNodeOfType } from 'eslint-codemod-utils';
2
+
3
+ /**
4
+ * Given a component name finds its JSX usages and performs some
5
+ * additional validations to ensure transformation can be done correctly
6
+ */
7
+ export const findValidJsxUsageToTransform = (componentName, scope) => {
8
+ const variableDeclaration = scope.variables.find(v => v.name === componentName);
9
+ if (!variableDeclaration) {
10
+ return;
11
+ }
12
+
13
+ // length here should be exactly 2 to indicate only two references:
14
+ // one being the variable declaration itself
15
+ // second being the JSX call site
16
+ // we might consider handling multiple local JSX call sites in the future
17
+ // but "this is good enough for now"™️
18
+ if (variableDeclaration.references.length !== 2) {
19
+ return;
20
+ }
21
+ const jsxUsage = variableDeclaration.references[1].identifier;
22
+ if (!isNodeOfType(jsxUsage, 'JSXIdentifier')) {
23
+ return;
24
+ }
25
+ const jsxOpeningElement = jsxUsage.parent;
26
+ // we could relatively easily support some safe attributes like
27
+ // "id" or "testId" but support will be expanded as we go
28
+ if (!isNodeOfType(jsxOpeningElement, 'JSXOpeningElement') || jsxOpeningElement.attributes.length > 0) {
29
+ return;
30
+ }
31
+ return jsxOpeningElement;
32
+ };
@@ -0,0 +1,47 @@
1
+ import { closestOfType, isNodeOfType } from 'eslint-codemod-utils';
2
+ import { validPrimitiveElements } from './is-valid-tag-name';
3
+
4
+ /**
5
+ * returns a variable reference if preconditions are favourable for
6
+ * the transformation to proceed, undefined otherwise.
7
+ */
8
+
9
+ export const findValidStyledComponentCall = node => {
10
+ // halts unless we are dealing with a styled component
11
+ if (!isStyledCallExpression(node)) {
12
+ return;
13
+ }
14
+ // halts if the component is being exported directly
15
+ if (closestOfType(node, 'ExportNamedDeclaration')) {
16
+ return;
17
+ }
18
+ const styledComponentVariableRef = node.parent;
19
+ // halts if the styled component is not assigned to a variable immediately
20
+ if (!isNodeOfType(styledComponentVariableRef, 'VariableDeclarator')) {
21
+ return;
22
+ }
23
+ return styledComponentVariableRef;
24
+ };
25
+
26
+ /**
27
+ * Some verbose precondition checks but all it does is check
28
+ * a call expression is of form `styled.div` or `styled2.div`
29
+ *
30
+ * In the future it could be enhanced to double check `styled` and `styled2`
31
+ * are Compiled imports but as is should work for the majority of use cases
32
+ */
33
+ const isStyledCallExpression = call => {
34
+ if (!isNodeOfType(call, 'CallExpression')) {
35
+ return false;
36
+ }
37
+ if (!isNodeOfType(call.callee, 'MemberExpression')) {
38
+ return false;
39
+ }
40
+ if (!isNodeOfType(call.callee.object, 'Identifier') || !isNodeOfType(call.callee.property, 'Identifier')) {
41
+ return false;
42
+ }
43
+ if (/^styled2?$/.test(call.callee.object.name) && validPrimitiveElements.has(call.callee.property.name)) {
44
+ return true;
45
+ }
46
+ return false;
47
+ };
@@ -1,11 +1,14 @@
1
1
  export { containsOnlySupportedAttrs } from './contains-only-supported-attrs';
2
2
  export { convertASTObjectExpressionToJSObject } from './convert-ast-object-expression-to-js-object';
3
+ export { findValidJsxUsageToTransform } from './find-valid-jsx-usage-to-transform';
4
+ export { findValidStyledComponentCall } from './find-valid-styled-component-call';
3
5
  export { getAttributeValueIdentifier } from './get-attribute-value-identifier';
4
6
  export { getFunctionArgumentAtPos } from './get-function-argument-at-pos';
5
7
  export { getJSXAttributeByName } from './get-jsx-attribute-by-name';
6
8
  export { getVariableDefinitionValue } from './get-variable-definition-value';
7
9
  export { getVariableUsagesCount } from './get-variable-usage-count';
8
10
  export { isFunctionNamed } from './is-function-named';
11
+ export { isValidCssPropertiesToTransform } from './is-valid-css-properties-to-transform';
9
12
  export { isValidTagName } from './is-valid-tag-name';
10
13
  export { updateJSXAttributeByName } from './update-jsx-attribute-by-name';
11
14
  export { updateJSXElementName } from './update-jsx-element-name';
@@ -0,0 +1,32 @@
1
+ import { isNodeOfType } from 'eslint-codemod-utils';
2
+ import { supportedStylesMap } from '../transformers/css-to-xcss';
3
+ import { convertASTObjectExpressionToJSObject } from './convert-ast-object-expression-to-js-object';
4
+ export const isValidCssPropertiesToTransform = node => {
5
+ const cssObjectExpression = node.arguments[0];
6
+ // Bail on empty object calls
7
+ if (!cssObjectExpression || !isNodeOfType(cssObjectExpression, 'ObjectExpression')) {
8
+ return false;
9
+ }
10
+ const cssObject = convertASTObjectExpressionToJSObject(cssObjectExpression);
11
+ // Bail if there are less or more than 1 styles defined
12
+ if (!cssObject || Object.keys(cssObject).length !== 1) {
13
+ return false;
14
+ }
15
+
16
+ // NOTE: Our approach with this lint rule is to strictly whitelist css properties we can map.
17
+ // It means we have to provide mappings for everything (e.g. `display: block`).
18
+ // However, from a maker's experience, it's much better that the rule doesn't report (if we miss a mapping)
19
+ // than the rule reporting on things that can't be mapped.
20
+ const containsOnlyValidStyles = Object.keys(cssObject).every(styleProperty => {
21
+ const styleValue = cssObject[styleProperty];
22
+ return supportedStylesMap[styleProperty] &&
23
+ // Is the key something we can map
24
+ supportedStylesMap[styleProperty][styleValue] // Is the value something we can map
25
+ ;
26
+ });
27
+
28
+ if (!containsOnlyValidStyles) {
29
+ return false;
30
+ }
31
+ return true;
32
+ };
@@ -1,4 +1,4 @@
1
- const validPrimitiveElements = new Set(['div']);
1
+ export const validPrimitiveElements = new Set(['div']);
2
2
  export const isValidTagName = node => {
3
3
  if (node.openingElement.name.type !== 'JSXIdentifier') {
4
4
  return false;
@@ -8,5 +8,5 @@ export const updateJSXElementName = (node, newName, fixer) => {
8
8
  const newClosingElement = closingElement &&
9
9
  // Self closing tags, like `<div />` don't need to have the closing tag updated
10
10
  fixer.replaceText(closingElement.name, jsxIdentifier(newName).toString());
11
- return [newOpeningElement, newClosingElement];
11
+ return [newOpeningElement, newClosingElement || undefined];
12
12
  };
@@ -1,8 +1,12 @@
1
1
  import { getIdentifierInParentScope, isNodeOfType } from 'eslint-codemod-utils';
2
+ import assign from 'lodash/assign';
2
3
  import { createLintRule } from '../utils/create-rule';
3
- import { jsxElementToBoxTransformer, supportedStylesMap } from './transformers';
4
- import { containsOnlySupportedAttrs, convertASTObjectExpressionToJSObject, getAttributeValueIdentifier, getFunctionArgumentAtPos, getJSXAttributeByName, getVariableDefinitionValue, getVariableUsagesCount, isFunctionNamed, isValidTagName } from './utils';
4
+ import { jsxElementToBoxTransformer, styledComponentToPrimitive } from './transformers';
5
+ import { containsOnlySupportedAttrs, findValidJsxUsageToTransform, findValidStyledComponentCall, getAttributeValueIdentifier, getJSXAttributeByName, getVariableDefinitionValue, getVariableUsagesCount, isFunctionNamed, isValidCssPropertiesToTransform, isValidTagName } from './utils';
5
6
  var boxDocsUrl = 'https://atlassian.design/components/primitives/box';
7
+ var defaultConfig = {
8
+ preview: false
9
+ };
6
10
  var rule = createLintRule({
7
11
  meta: {
8
12
  name: 'use-primitives',
@@ -15,11 +19,43 @@ var rule = createLintRule({
15
19
  severity: 'warn'
16
20
  },
17
21
  messages: {
18
- preferPrimitivesBox: "This \"{{element}}\" may be able to be replaced with a \"Box\". See ".concat(boxDocsUrl, " for guidance.")
22
+ preferPrimitivesBox: "This element can be replaced with a \"Box\" primitive. See ".concat(boxDocsUrl, " for additional guidance.")
19
23
  }
20
24
  },
21
25
  create: function create(context) {
26
+ var mergedConfig = assign({}, defaultConfig, context.options[0]);
22
27
  return {
28
+ // transforms styled.<html>(...) usages
29
+ CallExpression: function CallExpression(node) {
30
+ if (!mergedConfig.preview) {
31
+ return;
32
+ }
33
+ if (!isNodeOfType(node, 'CallExpression')) {
34
+ return;
35
+ }
36
+ var styledComponentVariableRef = findValidStyledComponentCall(node);
37
+ if (!styledComponentVariableRef || !isNodeOfType(styledComponentVariableRef.id, 'Identifier') || !isValidCssPropertiesToTransform(node)) {
38
+ return;
39
+ }
40
+ var styledComponentJsxRef = findValidJsxUsageToTransform(styledComponentVariableRef.id.name, context.getScope());
41
+ if (!styledComponentJsxRef) {
42
+ return;
43
+ }
44
+
45
+ // if we have both references at this point then we can offer a fix \o/
46
+ context.report({
47
+ node: styledComponentVariableRef,
48
+ messageId: 'preferPrimitivesBox',
49
+ suggest: [{
50
+ desc: "Convert ".concat(styledComponentVariableRef.id.name, " to Box"),
51
+ fix: styledComponentToPrimitive({
52
+ stylesRef: styledComponentVariableRef,
53
+ jsxRef: styledComponentJsxRef
54
+ }, context)
55
+ }]
56
+ });
57
+ },
58
+ // transforms <div css={...}> usages
23
59
  JSXOpeningElement: function JSXOpeningElement(node) {
24
60
  if (!isNodeOfType(node, 'JSXOpeningElement')) {
25
61
  return;
@@ -91,42 +127,10 @@ var shouldSuggestBox = function shouldSuggestBox(node, context
91
127
  // Find where `cssVariableName` is defined. We're looking for `const myStyles = css({...})`
92
128
  var cssVariableDefinition = getIdentifierInParentScope(context.getScope(), cssVariableName);
93
129
  var cssVariableValue = getVariableDefinitionValue(cssVariableDefinition);
94
-
95
130
  // Check if `cssVariableValue` is a function called `css()`
96
- if (!isFunctionNamed(cssVariableValue, 'css')) {
97
- return false;
98
- }
99
-
100
- // get the `{}` in `css({})`
101
- // Zero indexed
102
- var cssObjectExpression = getFunctionArgumentAtPos(cssVariableValue, 0);
103
-
104
- // Bail on empty `css()` calls
105
- if (!cssObjectExpression) {
106
- return false;
107
- }
108
- var cssObject = convertASTObjectExpressionToJSObject(cssObjectExpression);
109
-
110
- // Bail if there are less or more than 1 styles defined
111
- if (Object.keys(cssObject).length !== 1) {
112
- return false;
113
- }
114
-
115
- // NOTE: Our approach with this lint rule is to strictly whitelist css properties we can map.
116
- // It means we have to provide mappings for everything (e.g. `display: block`).
117
- // However, from a maker's experience, it's much better that the rule doesn't report (if we miss a mapping)
118
- // than the rule reporting on things that can't be mapped.
119
- var containsOnlyValidStyles = Object.keys(cssObject).every(function (styleProperty) {
120
- var styleValue = cssObject[styleProperty];
121
- return supportedStylesMap[styleProperty] &&
122
- // Is the key something we can map
123
- supportedStylesMap[styleProperty][styleValue] // Is the value something we can map
124
- ;
125
- });
126
-
127
- if (!containsOnlyValidStyles) {
131
+ if (!cssVariableValue || !isFunctionNamed(cssVariableValue, 'css')) {
128
132
  return false;
129
133
  }
130
- return true;
134
+ return isValidCssPropertiesToTransform(cssVariableValue.node.init);
131
135
  };
132
136
  export default rule;
@@ -29,7 +29,14 @@ export var cssToXcssTransformer = function cssToXcssTransformer(node, context, f
29
29
  var cssObjectExpression = getFunctionArgumentAtPos(cssVariableValue, 0);
30
30
  return [
31
31
  // Update `css` function name to `xcss`.
32
- fixer.replaceText(cssVariableValue.node.init.callee, identifier('xcss').toString())].concat(_toConsumableArray(cssObjectExpression.properties.map(function (entry) {
32
+ fixer.replaceText(cssVariableValue.node.init.callee, identifier('xcss').toString())].concat(_toConsumableArray(styledObjectToXcssTokens(cssObjectExpression, fixer)));
33
+ };
34
+
35
+ // Update css object values to xcss values. e.g. `'8px'` -> `'space.100'`
36
+ // Note: `properties` in this context is a group of AST nodes that make up a key/value pair in an object.
37
+ // e.g. `padding: '8px'`. For clarity, it's renamed to `entry` inside the `.map()`.
38
+ export var styledObjectToXcssTokens = function styledObjectToXcssTokens(styles, fixer) {
39
+ return styles.properties.map(function (entry) {
33
40
  if (!isNodeOfType(entry, 'Property')) {
34
41
  return;
35
42
  }
@@ -44,7 +51,7 @@ export var cssToXcssTransformer = function cssToXcssTransformer(node, context, f
44
51
  return;
45
52
  }
46
53
  return fixer.replaceText(entry.value, literal("'".concat(supportedStylesMap[entry.key.name][value], "'")).toString());
47
- })));
54
+ });
48
55
  };
49
56
  export var spaceTokenMap = {
50
57
  '0px': 'space.0',
@@ -1,2 +1,3 @@
1
1
  export { cssToXcssTransformer, supportedStylesMap, spaceTokenMap } from './css-to-xcss';
2
- export { jsxElementToBoxTransformer } from './jsx-element-to-box';
2
+ export { jsxElementToBoxTransformer } from './jsx-element-to-box';
3
+ export { styledComponentToPrimitive } from './styled-component-to-primitive';
@@ -0,0 +1,61 @@
1
+ import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray";
2
+ import { isNodeOfType } from 'eslint-codemod-utils';
3
+ import { updateJSXElementName, upsertImportDeclaration } from '../utils';
4
+ import { styledObjectToXcssTokens } from './css-to-xcss';
5
+ /**
6
+ * All required validation steps have been taken care of before this
7
+ * transformer is called, so it just goes ahead providing all necessary fixes
8
+ */
9
+ export var styledComponentToPrimitive = function styledComponentToPrimitive(_ref, context) {
10
+ var stylesRef = _ref.stylesRef,
11
+ jsxRef = _ref.jsxRef;
12
+ return function (fixer) {
13
+ // generates the new variable name: MyComponent -> myComponentStyles
14
+ var calculatedStylesVariableName = isNodeOfType(stylesRef.id, 'Identifier') && "".concat(stylesRef.id.name.replace(stylesRef.id.name[0], stylesRef.id.name[0].toLowerCase()), "Styles");
15
+ if (!calculatedStylesVariableName) {
16
+ return [];
17
+ }
18
+ var importFixes = upsertImportDeclaration({
19
+ packageName: '@atlaskit/primitives',
20
+ specifiers: ['Box', 'xcss']
21
+ }, context, fixer);
22
+ var stylesFixes = convertStyledComponentToXcss(stylesRef, calculatedStylesVariableName, fixer);
23
+ var jsxFixes = convertJsxCallSite(jsxRef, calculatedStylesVariableName, fixer);
24
+ return [importFixes].concat(stylesFixes, jsxFixes).filter(function (fix) {
25
+ return Boolean(fix);
26
+ }); // Some of the transformers can return arrays with undefined, so filter them out
27
+ };
28
+ };
29
+
30
+ var convertStyledComponentToXcss = function convertStyledComponentToXcss(stylesRef, newStylesVariableName, fixer) {
31
+ var fixes = [];
32
+
33
+ // renames the variable from MyComponent to myComponentStyles
34
+ fixes.push(fixer.replaceText(stylesRef.id, newStylesVariableName));
35
+
36
+ // renames the function call from styled.<tag> to xcss
37
+ if (stylesRef.init && isNodeOfType(stylesRef.init, 'CallExpression')) {
38
+ fixes.push(fixer.replaceText(stylesRef.init.callee, 'xcss'));
39
+ }
40
+
41
+ // converts CSS values to XCSS-compatible tokens
42
+ if (stylesRef.init && isNodeOfType(stylesRef.init, 'CallExpression')) {
43
+ var objectExpression = stylesRef.init.arguments[0];
44
+ if (isNodeOfType(objectExpression, 'ObjectExpression')) {
45
+ fixes.push.apply(fixes, _toConsumableArray(styledObjectToXcssTokens(objectExpression, fixer)));
46
+ }
47
+ }
48
+ return fixes;
49
+ };
50
+ var convertJsxCallSite = function convertJsxCallSite(jsxRef, newStylesVariableName, fixer) {
51
+ var fixes = [];
52
+
53
+ // renames the JSX call site
54
+ if (isNodeOfType(jsxRef.parent, 'JSXElement')) {
55
+ fixes.push.apply(fixes, _toConsumableArray(updateJSXElementName(jsxRef.parent, 'Box', fixer)));
56
+ }
57
+
58
+ // adds xcss prop
59
+ fixes.push(fixer.insertTextAfter(jsxRef.name, " xcss={".concat(newStylesVariableName, "}")));
60
+ return fixes;
61
+ };
@@ -7,6 +7,22 @@ import { isNodeOfType } from 'eslint-codemod-utils';
7
7
  */
8
8
  export var convertASTObjectExpressionToJSObject = function convertASTObjectExpressionToJSObject(styles) {
9
9
  var styleObj = {};
10
+
11
+ // if we see any spread props we stop and return false to indicate this is unsupported
12
+ if (!styles.properties.every(function (prop) {
13
+ return isNodeOfType(prop, 'Property');
14
+ })) {
15
+ return false;
16
+ }
17
+
18
+ // TODO: We need to harden this logic.
19
+ // It currently generates a false positive for:
20
+ // styled.div({
21
+ // marginTop: "0px",
22
+ // marginBottom: token("space.100", "8px"),
23
+ // })
24
+ // as the value for `marginBottom` is not a string, so it is just skipped
25
+ // from the resulting map and this causes the rule to trigger when it shouldn't
10
26
  styles.properties.forEach(function (prop) {
11
27
  if (!isNodeOfType(prop, 'Property')) {
12
28
  return;
@@ -0,0 +1,34 @@
1
+ import { isNodeOfType } from 'eslint-codemod-utils';
2
+
3
+ /**
4
+ * Given a component name finds its JSX usages and performs some
5
+ * additional validations to ensure transformation can be done correctly
6
+ */
7
+ export var findValidJsxUsageToTransform = function findValidJsxUsageToTransform(componentName, scope) {
8
+ var variableDeclaration = scope.variables.find(function (v) {
9
+ return v.name === componentName;
10
+ });
11
+ if (!variableDeclaration) {
12
+ return;
13
+ }
14
+
15
+ // length here should be exactly 2 to indicate only two references:
16
+ // one being the variable declaration itself
17
+ // second being the JSX call site
18
+ // we might consider handling multiple local JSX call sites in the future
19
+ // but "this is good enough for now"™️
20
+ if (variableDeclaration.references.length !== 2) {
21
+ return;
22
+ }
23
+ var jsxUsage = variableDeclaration.references[1].identifier;
24
+ if (!isNodeOfType(jsxUsage, 'JSXIdentifier')) {
25
+ return;
26
+ }
27
+ var jsxOpeningElement = jsxUsage.parent;
28
+ // we could relatively easily support some safe attributes like
29
+ // "id" or "testId" but support will be expanded as we go
30
+ if (!isNodeOfType(jsxOpeningElement, 'JSXOpeningElement') || jsxOpeningElement.attributes.length > 0) {
31
+ return;
32
+ }
33
+ return jsxOpeningElement;
34
+ };
@@ -0,0 +1,47 @@
1
+ import { closestOfType, isNodeOfType } from 'eslint-codemod-utils';
2
+ import { validPrimitiveElements } from './is-valid-tag-name';
3
+
4
+ /**
5
+ * returns a variable reference if preconditions are favourable for
6
+ * the transformation to proceed, undefined otherwise.
7
+ */
8
+
9
+ export var findValidStyledComponentCall = function findValidStyledComponentCall(node) {
10
+ // halts unless we are dealing with a styled component
11
+ if (!isStyledCallExpression(node)) {
12
+ return;
13
+ }
14
+ // halts if the component is being exported directly
15
+ if (closestOfType(node, 'ExportNamedDeclaration')) {
16
+ return;
17
+ }
18
+ var styledComponentVariableRef = node.parent;
19
+ // halts if the styled component is not assigned to a variable immediately
20
+ if (!isNodeOfType(styledComponentVariableRef, 'VariableDeclarator')) {
21
+ return;
22
+ }
23
+ return styledComponentVariableRef;
24
+ };
25
+
26
+ /**
27
+ * Some verbose precondition checks but all it does is check
28
+ * a call expression is of form `styled.div` or `styled2.div`
29
+ *
30
+ * In the future it could be enhanced to double check `styled` and `styled2`
31
+ * are Compiled imports but as is should work for the majority of use cases
32
+ */
33
+ var isStyledCallExpression = function isStyledCallExpression(call) {
34
+ if (!isNodeOfType(call, 'CallExpression')) {
35
+ return false;
36
+ }
37
+ if (!isNodeOfType(call.callee, 'MemberExpression')) {
38
+ return false;
39
+ }
40
+ if (!isNodeOfType(call.callee.object, 'Identifier') || !isNodeOfType(call.callee.property, 'Identifier')) {
41
+ return false;
42
+ }
43
+ if (/^styled2?$/.test(call.callee.object.name) && validPrimitiveElements.has(call.callee.property.name)) {
44
+ return true;
45
+ }
46
+ return false;
47
+ };
@@ -1,11 +1,14 @@
1
1
  export { containsOnlySupportedAttrs } from './contains-only-supported-attrs';
2
2
  export { convertASTObjectExpressionToJSObject } from './convert-ast-object-expression-to-js-object';
3
+ export { findValidJsxUsageToTransform } from './find-valid-jsx-usage-to-transform';
4
+ export { findValidStyledComponentCall } from './find-valid-styled-component-call';
3
5
  export { getAttributeValueIdentifier } from './get-attribute-value-identifier';
4
6
  export { getFunctionArgumentAtPos } from './get-function-argument-at-pos';
5
7
  export { getJSXAttributeByName } from './get-jsx-attribute-by-name';
6
8
  export { getVariableDefinitionValue } from './get-variable-definition-value';
7
9
  export { getVariableUsagesCount } from './get-variable-usage-count';
8
10
  export { isFunctionNamed } from './is-function-named';
11
+ export { isValidCssPropertiesToTransform } from './is-valid-css-properties-to-transform';
9
12
  export { isValidTagName } from './is-valid-tag-name';
10
13
  export { updateJSXAttributeByName } from './update-jsx-attribute-by-name';
11
14
  export { updateJSXElementName } from './update-jsx-element-name';
@@ -0,0 +1,32 @@
1
+ import { isNodeOfType } from 'eslint-codemod-utils';
2
+ import { supportedStylesMap } from '../transformers/css-to-xcss';
3
+ import { convertASTObjectExpressionToJSObject } from './convert-ast-object-expression-to-js-object';
4
+ export var isValidCssPropertiesToTransform = function isValidCssPropertiesToTransform(node) {
5
+ var cssObjectExpression = node.arguments[0];
6
+ // Bail on empty object calls
7
+ if (!cssObjectExpression || !isNodeOfType(cssObjectExpression, 'ObjectExpression')) {
8
+ return false;
9
+ }
10
+ var cssObject = convertASTObjectExpressionToJSObject(cssObjectExpression);
11
+ // Bail if there are less or more than 1 styles defined
12
+ if (!cssObject || Object.keys(cssObject).length !== 1) {
13
+ return false;
14
+ }
15
+
16
+ // NOTE: Our approach with this lint rule is to strictly whitelist css properties we can map.
17
+ // It means we have to provide mappings for everything (e.g. `display: block`).
18
+ // However, from a maker's experience, it's much better that the rule doesn't report (if we miss a mapping)
19
+ // than the rule reporting on things that can't be mapped.
20
+ var containsOnlyValidStyles = Object.keys(cssObject).every(function (styleProperty) {
21
+ var styleValue = cssObject[styleProperty];
22
+ return supportedStylesMap[styleProperty] &&
23
+ // Is the key something we can map
24
+ supportedStylesMap[styleProperty][styleValue] // Is the value something we can map
25
+ ;
26
+ });
27
+
28
+ if (!containsOnlyValidStyles) {
29
+ return false;
30
+ }
31
+ return true;
32
+ };
@@ -1,4 +1,4 @@
1
- var validPrimitiveElements = new Set(['div']);
1
+ export var validPrimitiveElements = new Set(['div']);
2
2
  export var isValidTagName = function isValidTagName(node) {
3
3
  if (node.openingElement.name.type !== 'JSXIdentifier') {
4
4
  return false;
@@ -6,5 +6,5 @@ export var updateJSXElementName = function updateJSXElementName(node, newName, f
6
6
  var newClosingElement = closingElement &&
7
7
  // Self closing tags, like `<div />` don't need to have the closing tag updated
8
8
  fixer.replaceText(closingElement.name, jsxIdentifier(newName).toString());
9
- return [newOpeningElement, newClosingElement];
9
+ return [newOpeningElement, newClosingElement || undefined];
10
10
  };
@@ -1,6 +1,7 @@
1
1
  import type { Rule } from 'eslint';
2
- import { JSXElement } from 'eslint-codemod-utils';
2
+ import { JSXElement, ObjectExpression } from 'eslint-codemod-utils';
3
3
  export declare const cssToXcssTransformer: (node: JSXElement, context: Rule.RuleContext, fixer: Rule.RuleFixer) => (Rule.Fix | undefined)[];
4
+ export declare const styledObjectToXcssTokens: (styles: ObjectExpression & Partial<Rule.NodeParentExtension>, fixer: Rule.RuleFixer) => (Rule.Fix | undefined)[];
4
5
  export declare const spaceTokenMap: {
5
6
  [key: string]: string;
6
7
  };
@@ -1,2 +1,3 @@
1
1
  export { cssToXcssTransformer, supportedStylesMap, spaceTokenMap, } from './css-to-xcss';
2
2
  export { jsxElementToBoxTransformer } from './jsx-element-to-box';
3
+ export { styledComponentToPrimitive } from './styled-component-to-primitive';
@@ -0,0 +1,13 @@
1
+ import type { Rule } from 'eslint';
2
+ import { JSXOpeningElement, VariableDeclarator } from 'eslint-codemod-utils';
3
+ type StylesRef = VariableDeclarator & Rule.NodeParentExtension;
4
+ type JSXRef = JSXOpeningElement & Rule.NodeParentExtension;
5
+ /**
6
+ * All required validation steps have been taken care of before this
7
+ * transformer is called, so it just goes ahead providing all necessary fixes
8
+ */
9
+ export declare const styledComponentToPrimitive: ({ stylesRef, jsxRef, }: {
10
+ stylesRef: StylesRef;
11
+ jsxRef: JSXRef;
12
+ }, context: Rule.RuleContext) => (fixer: Rule.RuleFixer) => Rule.Fix[];
13
+ export {};
@@ -6,4 +6,4 @@ export type CSSPropStyleObject = {
6
6
  /**
7
7
  * Note: Not recursive. Only handles top level key/value pairs
8
8
  */
9
- export declare const convertASTObjectExpressionToJSObject: (styles: ObjectExpression & Partial<Rule.NodeParentExtension>) => CSSPropStyleObject;
9
+ export declare const convertASTObjectExpressionToJSObject: (styles: ObjectExpression & Partial<Rule.NodeParentExtension>) => CSSPropStyleObject | false;
@@ -0,0 +1,7 @@
1
+ import type { Rule, Scope } from 'eslint';
2
+ import { JSXOpeningElement } from 'eslint-codemod-utils';
3
+ /**
4
+ * Given a component name finds its JSX usages and performs some
5
+ * additional validations to ensure transformation can be done correctly
6
+ */
7
+ export declare const findValidJsxUsageToTransform: (componentName: string, scope: Scope.Scope) => (JSXOpeningElement & Rule.NodeParentExtension) | undefined;
@@ -0,0 +1,7 @@
1
+ import type { Rule } from 'eslint';
2
+ import { type VariableDeclarator } from 'eslint-codemod-utils';
3
+ /**
4
+ * returns a variable reference if preconditions are favourable for
5
+ * the transformation to proceed, undefined otherwise.
6
+ */
7
+ export declare const findValidStyledComponentCall: (node: Rule.Node) => (VariableDeclarator & Rule.NodeParentExtension) | undefined;