@atlaskit/eslint-plugin-platform 2.0.2 → 2.1.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 (36) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/cjs/index.js +3 -0
  3. package/dist/cjs/rules/compiled/expand-background-shorthand/index.js +2 -17
  4. package/dist/cjs/rules/compiled/expand-spacing-shorthand/index.js +214 -0
  5. package/dist/cjs/rules/util/compiled-utils.js +21 -0
  6. package/dist/cjs/rules/util/context-compat.js +2 -2
  7. package/dist/es2019/index.js +3 -0
  8. package/dist/es2019/rules/compiled/expand-background-shorthand/index.js +1 -15
  9. package/dist/es2019/rules/compiled/expand-spacing-shorthand/index.js +178 -0
  10. package/dist/es2019/rules/util/compiled-utils.js +15 -0
  11. package/dist/es2019/rules/util/context-compat.js +1 -1
  12. package/dist/esm/index.js +3 -0
  13. package/dist/esm/rules/compiled/expand-background-shorthand/index.js +1 -16
  14. package/dist/esm/rules/compiled/expand-spacing-shorthand/index.js +207 -0
  15. package/dist/esm/rules/util/compiled-utils.js +16 -0
  16. package/dist/esm/rules/util/context-compat.js +1 -1
  17. package/dist/types/index.d.ts +3 -0
  18. package/dist/types/rules/compiled/expand-spacing-shorthand/index.d.ts +3 -0
  19. package/dist/types/rules/util/compiled-utils.d.ts +3 -0
  20. package/dist/types/rules/util/context-compat.d.ts +12 -1
  21. package/dist/types-ts4.5/index.d.ts +3 -0
  22. package/dist/types-ts4.5/rules/compiled/expand-spacing-shorthand/index.d.ts +3 -0
  23. package/dist/types-ts4.5/rules/util/compiled-utils.d.ts +3 -0
  24. package/dist/types-ts4.5/rules/util/context-compat.d.ts +12 -1
  25. package/package.json +1 -1
  26. package/src/index.tsx +3 -0
  27. package/src/rules/compiled/expand-background-shorthand/__tests__/rule.test.ts +1 -1
  28. package/src/rules/compiled/expand-background-shorthand/index.tsx +1 -25
  29. package/src/rules/compiled/expand-spacing-shorthand/README.md +38 -0
  30. package/src/rules/compiled/expand-spacing-shorthand/__tests__/rule.test.ts +400 -0
  31. package/src/rules/compiled/expand-spacing-shorthand/index.ts +195 -0
  32. package/src/rules/util/compiled-utils.ts +27 -0
  33. package/src/rules/util/context-compat.ts +1 -1
  34. package/tsconfig.app.json +0 -1
  35. package/tsconfig.dev.json +0 -1
  36. package/tsconfig.json +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # @atlaskit/eslint-plugin-platform
2
2
 
3
+ ## 2.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - [#101753](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/pull-requests/101753)
8
+ [`ab8a4d93399e8`](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/commits/ab8a4d93399e8) -
9
+ AFB-822 Turn of expand-spacing-shorthand rule until all of Jira and Platform rollout is complete
10
+
11
+ ## 2.1.0
12
+
13
+ ### Minor Changes
14
+
15
+ - [#98759](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/pull-requests/98759)
16
+ [`e6f89962ceaba`](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/commits/e6f89962ceaba) -
17
+ ESLint rule for expand-spacing-shorthand (i.e. padding and margin)
18
+
3
19
  ## 2.0.2
4
20
 
5
21
  ### Patch Changes
package/dist/cjs/index.js CHANGED
@@ -31,6 +31,7 @@ var _noAlias = _interopRequireDefault(require("./rules/feature-gating/no-alias")
31
31
  var _useEntrypointsInExamples = _interopRequireDefault(require("./rules/use-entrypoints-in-examples"));
32
32
  var _useRecommendedUtils = _interopRequireDefault(require("./rules/feature-gating/use-recommended-utils"));
33
33
  var _expandBackgroundShorthand = _interopRequireDefault(require("./rules/compiled/expand-background-shorthand"));
34
+ var _expandSpacingShorthand = _interopRequireDefault(require("./rules/compiled/expand-spacing-shorthand"));
34
35
  function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
35
36
  function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } // eslint-disable-next-line import/no-extraneous-dependencies
36
37
  var rules = exports.rules = {
@@ -44,6 +45,7 @@ var rules = exports.rules = {
44
45
  'ensure-valid-bin-values': _ensureValidBinValues.default,
45
46
  'expand-border-shorthand': _expandBorderShorthand.default,
46
47
  'expand-background-shorthand': _expandBackgroundShorthand.default,
48
+ 'expand-spacing-shorthand': _expandSpacingShorthand.default,
47
49
  'no-duplicate-dependencies': _noDuplicateDependencies.default,
48
50
  'no-invalid-feature-flag-usage': _noInvalidFeatureFlagUsage.default,
49
51
  'no-pre-post-install-scripts': _noPrePostInstalls.default,
@@ -70,6 +72,7 @@ var commonConfig = {
70
72
  // Compiled: rules that are not included via `@compiled/recommended
71
73
  '@atlaskit/platform/expand-border-shorthand': 'error',
72
74
  '@atlaskit/platform/expand-background-shorthand': 'error',
75
+ '@atlaskit/platform/expand-spacing-shorthand': 'off',
73
76
  '@compiled/jsx-pragma': ['error', {
74
77
  importSources: ['@atlaskit/css'],
75
78
  onlyRunIfImportingCompiled: true,
@@ -4,22 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.expandBackgroundShorthand = exports.default = void 0;
7
- var _isSupportedImport = require("@atlaskit/eslint-utils/is-supported-import");
8
- var _contextCompat = require("../../util/context-compat");
9
- // Checks if the function that holds the border property is using an import package that this rule is targeting
10
- var isCompiledAPI = function isCompiledAPI(context, node) {
11
- var importSources = (0, _isSupportedImport.getImportSources)(context);
12
- var _getScope = (0, _contextCompat.getScope)(context, node),
13
- references = _getScope.references;
14
- var ancestors = (0, _contextCompat.getAncestors)(context, node);
15
- if (ancestors.some(function (ancestor) {
16
- return ancestor.type === 'CallExpression' && ancestor.callee && ((0, _isSupportedImport.isCompiled)(ancestor.callee, references, importSources) || (0, _isSupportedImport.isAtlasKitCSS)(ancestor.callee, references, importSources));
17
- })) {
18
- return true;
19
- }
20
- return false;
21
- };
22
-
7
+ var _compiledUtils = require("../../util/compiled-utils");
23
8
  // Checks if node is a call expression with identifier 'token'
24
9
  var isTokenCallExpression = function isTokenCallExpression(node) {
25
10
  if (node.type === 'CallExpression') {
@@ -43,7 +28,7 @@ var expandBackgroundShorthand = exports.expandBackgroundShorthand = {
43
28
  create: function create(context) {
44
29
  return {
45
30
  'Property[key.name="background"]': function PropertyKeyNameBackground(node) {
46
- if (isCompiledAPI(context, node) && isTokenCallExpression(node.value)) {
31
+ if ((0, _compiledUtils.isCompiledAPI)(context, node) && isTokenCallExpression(node.value)) {
47
32
  context.report({
48
33
  node: node,
49
34
  messageId: 'expandBackgroundShorthand',
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.expandSpacingShorthand = exports.default = void 0;
8
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
9
+ var _contextCompat = require("../../util/context-compat");
10
+ var _compiledUtils = require("../../util/compiled-utils");
11
+ function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: !0 } : { done: !1, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = !0, u = !1; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = !0, o = r; }, f: function f() { try { a || null == t.return || t.return(); } finally { if (u) throw o; } } }; }
12
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
13
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
14
+ var spacingPos = ['Top', 'Right', 'Bottom', 'Left'];
15
+ // Checks if node is a call expression with identifier 'token'
16
+ var isTokenCallExpression = function isTokenCallExpression(node) {
17
+ if (node.callee.type === 'Identifier' && node.callee.name === 'token') {
18
+ return true;
19
+ }
20
+ return false;
21
+ };
22
+
23
+ // Given a TemplateLiteral node, returns the value of the spacing property as an array of strings
24
+ // e.g. `0 ${token('a')} ${token('b')}` -> ['0', 'token('a')', 'token('b')']
25
+ var parseTemplateLiteral = function parseTemplateLiteral(templateLiteral, context) {
26
+ var expressions = templateLiteral.expressions;
27
+ var quasis = templateLiteral.quasis;
28
+ var propertyValues = [];
29
+ for (var i = 0; i < expressions.length || i < quasis.length; i++) {
30
+ if (i < quasis.length) {
31
+ var cookedQuasi = quasis[i].value.cooked;
32
+ if (cookedQuasi) {
33
+ var splitQuasi = cookedQuasi.split(' ').filter(function (str) {
34
+ return str.trim().length > 0;
35
+ });
36
+ splitQuasi.forEach(function (str) {
37
+ propertyValues.push(isNaN(Number(str)) ? "'".concat(str, "'") : str);
38
+ });
39
+ }
40
+ }
41
+ if (i < expressions.length) {
42
+ var expr = (0, _contextCompat.getSourceCode)(context).getText(expressions[i]);
43
+ propertyValues.push(expr);
44
+ }
45
+ }
46
+ return propertyValues;
47
+ };
48
+ var checkValidPropertyValues = function checkValidPropertyValues(propertyValues) {
49
+ if (!propertyValues.some(function (str) {
50
+ return str.includes('token(');
51
+ })) {
52
+ return false;
53
+ }
54
+ if (propertyValues.length < 1 || propertyValues.length > 4) {
55
+ return false;
56
+ }
57
+ if (propertyValues.some(function (str) {
58
+ return str.includes('calc(');
59
+ })) {
60
+ return false;
61
+ }
62
+ return true;
63
+ };
64
+
65
+ // Check that all expressions in TemplateLiteral are token expressions
66
+ // If true: create an autofix
67
+ // If false: report violation without autofix
68
+ var hasOnlyTokens = function hasOnlyTokens(templateLiteral) {
69
+ var expressions = templateLiteral.expressions;
70
+ return expressions.every(function (expr) {
71
+ return expr.type === 'CallExpression' && isTokenCallExpression(expr);
72
+ });
73
+ };
74
+
75
+ // To fix spacing shorthands, given a list of spacing property values, expands the spacing property and adds autofix fixes
76
+ var expandSpacingProperties = function expandSpacingProperties(_ref) {
77
+ var context = _ref.context,
78
+ node = _ref.node,
79
+ propertyValues = _ref.propertyValues,
80
+ fixer = _ref.fixer,
81
+ propertyShorthand = _ref.propertyShorthand;
82
+ var _propertyValues = (0, _slicedToArray2.default)(propertyValues, 4),
83
+ top = _propertyValues[0],
84
+ _propertyValues$ = _propertyValues[1],
85
+ right = _propertyValues$ === void 0 ? top : _propertyValues$,
86
+ _propertyValues$2 = _propertyValues[2],
87
+ bottom = _propertyValues$2 === void 0 ? top : _propertyValues$2,
88
+ _propertyValues$3 = _propertyValues[3],
89
+ left = _propertyValues$3 === void 0 ? right : _propertyValues$3;
90
+ var spacing = [top, right, bottom, left];
91
+ var fixes = [];
92
+ var parentNode = node.parent;
93
+ if (parentNode && parentNode.type === 'ObjectExpression') {
94
+ var _iterator = _createForOfIteratorHelper(parentNode.properties),
95
+ _step;
96
+ try {
97
+ for (_iterator.s(); !(_step = _iterator.n()).done;) {
98
+ var prop = _step.value;
99
+ if (prop.type !== 'Property') {
100
+ continue;
101
+ }
102
+ if (prop.key.type === 'Identifier' && prop.range && prop.key.name !== "".concat(propertyShorthand)) {
103
+ for (var i = 0; i < spacing.length; i++) {
104
+ if (prop.key.name === "".concat(propertyShorthand).concat(spacingPos[i])) {
105
+ var _prop$range = (0, _slicedToArray2.default)(prop.range, 2),
106
+ start = _prop$range[0],
107
+ end = _prop$range[1];
108
+ // Remove the entire line for the duplicate property
109
+ while ((0, _contextCompat.getSourceCode)(context).text[end] !== '\n') {
110
+ end += 1;
111
+ }
112
+ while ((0, _contextCompat.getSourceCode)(context).text[start] !== '\n') {
113
+ start -= 1;
114
+ }
115
+ spacing[i] = (0, _contextCompat.getSourceCode)(context).getText(prop.value);
116
+ fixes.push(fixer.removeRange([start, end]));
117
+ break;
118
+ }
119
+ }
120
+ }
121
+ }
122
+ } catch (err) {
123
+ _iterator.e(err);
124
+ } finally {
125
+ _iterator.f();
126
+ }
127
+ }
128
+ fixes.push(fixer.insertTextAfter(node, "".concat(propertyShorthand, "Top: ").concat(spacing[0], ",\n")));
129
+ fixes.push(fixer.insertTextAfter(node, "\t".concat(propertyShorthand, "Right: ").concat(spacing[1], ",\n")));
130
+ fixes.push(fixer.insertTextAfter(node, "\t".concat(propertyShorthand, "Bottom: ").concat(spacing[2], ",\n")));
131
+ fixes.push(fixer.insertTextAfter(node, "\t".concat(propertyShorthand, "Left: ").concat(spacing[3])));
132
+ fixes.push(fixer.remove(node));
133
+ return fixes;
134
+ };
135
+ var executeExpandSpacingRule = function executeExpandSpacingRule(context, node, propertyShorthand) {
136
+ if (!(0, _compiledUtils.isCompiledAPI)(context, node)) {
137
+ return;
138
+ }
139
+ if (node.value.type === 'TemplateLiteral') {
140
+ // Value of spacing property is a TemplateLiteral type that contains a token, e.g. padding: `0 token('a')`
141
+ if (!hasOnlyTokens(node.value)) {
142
+ context.report({
143
+ node: node,
144
+ messageId: 'expandSpacingShorthand',
145
+ data: {
146
+ property: propertyShorthand
147
+ }
148
+ });
149
+ return;
150
+ }
151
+ var propertyValues = parseTemplateLiteral(node.value, context);
152
+ if (!checkValidPropertyValues(propertyValues)) {
153
+ return;
154
+ }
155
+ context.report({
156
+ node: node,
157
+ messageId: 'expandSpacingShorthand',
158
+ data: {
159
+ property: propertyShorthand
160
+ },
161
+ fix: function fix(fixer) {
162
+ return expandSpacingProperties({
163
+ context: context,
164
+ node: node,
165
+ propertyValues: propertyValues,
166
+ fixer: fixer,
167
+ propertyShorthand: propertyShorthand
168
+ });
169
+ }
170
+ });
171
+ } else if (node.value.type === 'CallExpression' && isTokenCallExpression(node.value)) {
172
+ // Value of spacing property is a token CallExpression type, e.g. margin: token('space.100', '8px')
173
+ var _propertyValues2 = [(0, _contextCompat.getSourceCode)(context).getText(node.value)];
174
+ context.report({
175
+ node: node,
176
+ messageId: 'expandSpacingShorthand',
177
+ data: {
178
+ property: propertyShorthand
179
+ },
180
+ fix: function fix(fixer) {
181
+ return expandSpacingProperties({
182
+ context: context,
183
+ node: node,
184
+ propertyValues: _propertyValues2,
185
+ fixer: fixer,
186
+ propertyShorthand: propertyShorthand
187
+ });
188
+ }
189
+ });
190
+ }
191
+ };
192
+ var expandSpacingShorthand = exports.expandSpacingShorthand = {
193
+ meta: {
194
+ docs: {
195
+ url: 'https://bitbucket.org/atlassian/atlassian-frontend-monorepo/src/master/platform/packages/platform/eslint-plugin/src/rules/compiled/expand-spacing-shorthand/'
196
+ },
197
+ messages: {
198
+ expandSpacingShorthand: 'Use {{ property }}Top, {{ property }}Right, {{ property }}Bottom and {{ property }}Left instead of {{ property }} shorthand'
199
+ },
200
+ type: 'problem',
201
+ fixable: 'code'
202
+ },
203
+ create: function create(context) {
204
+ return {
205
+ 'Property[key.name="padding"]': function PropertyKeyNamePadding(node) {
206
+ executeExpandSpacingRule(context, node, 'padding');
207
+ },
208
+ 'Property[key.name="margin"]': function PropertyKeyNameMargin(node) {
209
+ executeExpandSpacingRule(context, node, 'margin');
210
+ }
211
+ };
212
+ }
213
+ };
214
+ var _default = exports.default = expandSpacingShorthand;
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.isCompiledAPI = void 0;
7
+ var _contextCompat = require("./context-compat");
8
+ var _isSupportedImport = require("@atlaskit/eslint-utils/is-supported-import");
9
+ // Checks if the function that holds the property is using a Compiled import package that this rule is targeting
10
+ var isCompiledAPI = exports.isCompiledAPI = function isCompiledAPI(context, node) {
11
+ var importSources = (0, _isSupportedImport.getImportSources)(context);
12
+ var _getScope = (0, _contextCompat.getScope)(context, node),
13
+ references = _getScope.references;
14
+ var ancestors = (0, _contextCompat.getAncestors)(context, node);
15
+ if (ancestors.some(function (ancestor) {
16
+ return ancestor.type === 'CallExpression' && ancestor.callee && ((0, _isSupportedImport.isCompiled)(ancestor.callee, references, importSources) || (0, _isSupportedImport.isAtlasKitCSS)(ancestor.callee, references, importSources));
17
+ })) {
18
+ return true;
19
+ }
20
+ return false;
21
+ };
@@ -3,7 +3,7 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
- exports.getScope = exports.getAncestors = void 0;
6
+ exports.getSourceCode = exports.getScope = exports.getAncestors = void 0;
7
7
  /**
8
8
  * TODO: Consider whether this should be replaced by ESLint's compat library.
9
9
  * Either way, this should be removed once we no longer need to support ESLint versions less than 8.40.
@@ -15,7 +15,7 @@ exports.getScope = exports.getAncestors = void 0;
15
15
  * `context.getSourceCode()` is deprecated in v8 and removed in v9.
16
16
  * @param context - The ESLint rule context
17
17
  */
18
- var getSourceCode = function getSourceCode(context) {
18
+ var getSourceCode = exports.getSourceCode = function getSourceCode(context) {
19
19
  var _context$sourceCode;
20
20
  return (_context$sourceCode = context.sourceCode) !== null && _context$sourceCode !== void 0 ? _context$sourceCode : context.getSourceCode();
21
21
  };
@@ -25,6 +25,7 @@ import noAlias from './rules/feature-gating/no-alias';
25
25
  import useEntrypointsInExamples from './rules/use-entrypoints-in-examples';
26
26
  import useRecommendedUtils from './rules/feature-gating/use-recommended-utils';
27
27
  import expandBackgroundShorthand from './rules/compiled/expand-background-shorthand';
28
+ import expandSpacingShorthand from './rules/compiled/expand-spacing-shorthand';
28
29
  export const rules = {
29
30
  'ensure-feature-flag-registration': ensureFeatureFlagRegistration,
30
31
  'ensure-feature-flag-prefix': ensureFeatureFlagPrefix,
@@ -36,6 +37,7 @@ export const rules = {
36
37
  'ensure-valid-bin-values': ensureValidBinValues,
37
38
  'expand-border-shorthand': expandBorderShorthand,
38
39
  'expand-background-shorthand': expandBackgroundShorthand,
40
+ 'expand-spacing-shorthand': expandSpacingShorthand,
39
41
  'no-duplicate-dependencies': noDuplicateDependencies,
40
42
  'no-invalid-feature-flag-usage': noInvalidFeatureFlagUsage,
41
43
  'no-pre-post-install-scripts': noPreAndPostInstallScripts,
@@ -62,6 +64,7 @@ const commonConfig = {
62
64
  // Compiled: rules that are not included via `@compiled/recommended
63
65
  '@atlaskit/platform/expand-border-shorthand': 'error',
64
66
  '@atlaskit/platform/expand-background-shorthand': 'error',
67
+ '@atlaskit/platform/expand-spacing-shorthand': 'off',
65
68
  '@compiled/jsx-pragma': ['error', {
66
69
  importSources: ['@atlaskit/css'],
67
70
  onlyRunIfImportingCompiled: true,
@@ -1,18 +1,4 @@
1
- import { getImportSources, isCompiled, isAtlasKitCSS } from '@atlaskit/eslint-utils/is-supported-import';
2
- import { getAncestors, getScope } from '../../util/context-compat';
3
-
4
- // Checks if the function that holds the border property is using an import package that this rule is targeting
5
- const isCompiledAPI = (context, node) => {
6
- const importSources = getImportSources(context);
7
- const {
8
- references
9
- } = getScope(context, node);
10
- const ancestors = getAncestors(context, node);
11
- if (ancestors.some(ancestor => ancestor.type === 'CallExpression' && ancestor.callee && (isCompiled(ancestor.callee, references, importSources) || isAtlasKitCSS(ancestor.callee, references, importSources)))) {
12
- return true;
13
- }
14
- return false;
15
- };
1
+ import { isCompiledAPI } from '../../util/compiled-utils';
16
2
 
17
3
  // Checks if node is a call expression with identifier 'token'
18
4
  const isTokenCallExpression = node => {
@@ -0,0 +1,178 @@
1
+ import { getSourceCode } from '../../util/context-compat';
2
+ import { isCompiledAPI } from '../../util/compiled-utils';
3
+ const spacingPos = ['Top', 'Right', 'Bottom', 'Left'];
4
+ // Checks if node is a call expression with identifier 'token'
5
+ const isTokenCallExpression = node => {
6
+ if (node.callee.type === 'Identifier' && node.callee.name === 'token') {
7
+ return true;
8
+ }
9
+ return false;
10
+ };
11
+
12
+ // Given a TemplateLiteral node, returns the value of the spacing property as an array of strings
13
+ // e.g. `0 ${token('a')} ${token('b')}` -> ['0', 'token('a')', 'token('b')']
14
+ const parseTemplateLiteral = (templateLiteral, context) => {
15
+ const expressions = templateLiteral.expressions;
16
+ const quasis = templateLiteral.quasis;
17
+ let propertyValues = [];
18
+ for (let i = 0; i < expressions.length || i < quasis.length; i++) {
19
+ if (i < quasis.length) {
20
+ const cookedQuasi = quasis[i].value.cooked;
21
+ if (cookedQuasi) {
22
+ const splitQuasi = cookedQuasi.split(' ').filter(str => str.trim().length > 0);
23
+ splitQuasi.forEach(str => {
24
+ propertyValues.push(isNaN(Number(str)) ? `'${str}'` : str);
25
+ });
26
+ }
27
+ }
28
+ if (i < expressions.length) {
29
+ const expr = getSourceCode(context).getText(expressions[i]);
30
+ propertyValues.push(expr);
31
+ }
32
+ }
33
+ return propertyValues;
34
+ };
35
+ const checkValidPropertyValues = propertyValues => {
36
+ if (!propertyValues.some(str => str.includes('token('))) {
37
+ return false;
38
+ }
39
+ if (propertyValues.length < 1 || propertyValues.length > 4) {
40
+ return false;
41
+ }
42
+ if (propertyValues.some(str => str.includes('calc('))) {
43
+ return false;
44
+ }
45
+ return true;
46
+ };
47
+
48
+ // Check that all expressions in TemplateLiteral are token expressions
49
+ // If true: create an autofix
50
+ // If false: report violation without autofix
51
+ const hasOnlyTokens = templateLiteral => {
52
+ const expressions = templateLiteral.expressions;
53
+ return expressions.every(expr => expr.type === 'CallExpression' && isTokenCallExpression(expr));
54
+ };
55
+
56
+ // To fix spacing shorthands, given a list of spacing property values, expands the spacing property and adds autofix fixes
57
+ const expandSpacingProperties = ({
58
+ context,
59
+ node,
60
+ propertyValues,
61
+ fixer,
62
+ propertyShorthand
63
+ }) => {
64
+ const [top, right = top, bottom = top, left = right] = propertyValues;
65
+ const spacing = [top, right, bottom, left];
66
+ const fixes = [];
67
+ const parentNode = node.parent;
68
+ if (parentNode && parentNode.type === 'ObjectExpression') {
69
+ for (var prop of parentNode.properties) {
70
+ if (prop.type !== 'Property') {
71
+ continue;
72
+ }
73
+ if (prop.key.type === 'Identifier' && prop.range && prop.key.name !== `${propertyShorthand}`) {
74
+ for (let i = 0; i < spacing.length; i++) {
75
+ if (prop.key.name === `${propertyShorthand}${spacingPos[i]}`) {
76
+ let [start, end] = prop.range;
77
+ // Remove the entire line for the duplicate property
78
+ while (getSourceCode(context).text[end] !== '\n') {
79
+ end += 1;
80
+ }
81
+ while (getSourceCode(context).text[start] !== '\n') {
82
+ start -= 1;
83
+ }
84
+ spacing[i] = getSourceCode(context).getText(prop.value);
85
+ fixes.push(fixer.removeRange([start, end]));
86
+ break;
87
+ }
88
+ }
89
+ }
90
+ }
91
+ }
92
+ fixes.push(fixer.insertTextAfter(node, `${propertyShorthand}Top: ${spacing[0]},\n`));
93
+ fixes.push(fixer.insertTextAfter(node, `\t${propertyShorthand}Right: ${spacing[1]},\n`));
94
+ fixes.push(fixer.insertTextAfter(node, `\t${propertyShorthand}Bottom: ${spacing[2]},\n`));
95
+ fixes.push(fixer.insertTextAfter(node, `\t${propertyShorthand}Left: ${spacing[3]}`));
96
+ fixes.push(fixer.remove(node));
97
+ return fixes;
98
+ };
99
+ const executeExpandSpacingRule = (context, node, propertyShorthand) => {
100
+ if (!isCompiledAPI(context, node)) {
101
+ return;
102
+ }
103
+ if (node.value.type === 'TemplateLiteral') {
104
+ // Value of spacing property is a TemplateLiteral type that contains a token, e.g. padding: `0 token('a')`
105
+ if (!hasOnlyTokens(node.value)) {
106
+ context.report({
107
+ node,
108
+ messageId: 'expandSpacingShorthand',
109
+ data: {
110
+ property: propertyShorthand
111
+ }
112
+ });
113
+ return;
114
+ }
115
+ const propertyValues = parseTemplateLiteral(node.value, context);
116
+ if (!checkValidPropertyValues(propertyValues)) {
117
+ return;
118
+ }
119
+ context.report({
120
+ node,
121
+ messageId: 'expandSpacingShorthand',
122
+ data: {
123
+ property: propertyShorthand
124
+ },
125
+ fix(fixer) {
126
+ return expandSpacingProperties({
127
+ context,
128
+ node,
129
+ propertyValues,
130
+ fixer,
131
+ propertyShorthand
132
+ });
133
+ }
134
+ });
135
+ } else if (node.value.type === 'CallExpression' && isTokenCallExpression(node.value)) {
136
+ // Value of spacing property is a token CallExpression type, e.g. margin: token('space.100', '8px')
137
+ const propertyValues = [getSourceCode(context).getText(node.value)];
138
+ context.report({
139
+ node,
140
+ messageId: 'expandSpacingShorthand',
141
+ data: {
142
+ property: propertyShorthand
143
+ },
144
+ fix(fixer) {
145
+ return expandSpacingProperties({
146
+ context,
147
+ node,
148
+ propertyValues,
149
+ fixer,
150
+ propertyShorthand
151
+ });
152
+ }
153
+ });
154
+ }
155
+ };
156
+ export const expandSpacingShorthand = {
157
+ meta: {
158
+ docs: {
159
+ url: 'https://bitbucket.org/atlassian/atlassian-frontend-monorepo/src/master/platform/packages/platform/eslint-plugin/src/rules/compiled/expand-spacing-shorthand/'
160
+ },
161
+ messages: {
162
+ expandSpacingShorthand: 'Use {{ property }}Top, {{ property }}Right, {{ property }}Bottom and {{ property }}Left instead of {{ property }} shorthand'
163
+ },
164
+ type: 'problem',
165
+ fixable: 'code'
166
+ },
167
+ create(context) {
168
+ return {
169
+ 'Property[key.name="padding"]': function (node) {
170
+ executeExpandSpacingRule(context, node, 'padding');
171
+ },
172
+ 'Property[key.name="margin"]': function (node) {
173
+ executeExpandSpacingRule(context, node, 'margin');
174
+ }
175
+ };
176
+ }
177
+ };
178
+ export default expandSpacingShorthand;
@@ -0,0 +1,15 @@
1
+ import { getAncestors, getScope } from './context-compat';
2
+ import { getImportSources, isCompiled, isAtlasKitCSS } from '@atlaskit/eslint-utils/is-supported-import';
3
+
4
+ // Checks if the function that holds the property is using a Compiled import package that this rule is targeting
5
+ export const isCompiledAPI = (context, node) => {
6
+ const importSources = getImportSources(context);
7
+ const {
8
+ references
9
+ } = getScope(context, node);
10
+ const ancestors = getAncestors(context, node);
11
+ if (ancestors.some(ancestor => ancestor.type === 'CallExpression' && ancestor.callee && (isCompiled(ancestor.callee, references, importSources) || isAtlasKitCSS(ancestor.callee, references, importSources)))) {
12
+ return true;
13
+ }
14
+ return false;
15
+ };
@@ -9,7 +9,7 @@
9
9
  * `context.getSourceCode()` is deprecated in v8 and removed in v9.
10
10
  * @param context - The ESLint rule context
11
11
  */
12
- const getSourceCode = context => {
12
+ export const getSourceCode = context => {
13
13
  var _context$sourceCode;
14
14
  return (_context$sourceCode = context.sourceCode) !== null && _context$sourceCode !== void 0 ? _context$sourceCode : context.getSourceCode();
15
15
  };
package/dist/esm/index.js CHANGED
@@ -28,6 +28,7 @@ import noAlias from './rules/feature-gating/no-alias';
28
28
  import useEntrypointsInExamples from './rules/use-entrypoints-in-examples';
29
29
  import useRecommendedUtils from './rules/feature-gating/use-recommended-utils';
30
30
  import expandBackgroundShorthand from './rules/compiled/expand-background-shorthand';
31
+ import expandSpacingShorthand from './rules/compiled/expand-spacing-shorthand';
31
32
  export var rules = {
32
33
  'ensure-feature-flag-registration': ensureFeatureFlagRegistration,
33
34
  'ensure-feature-flag-prefix': ensureFeatureFlagPrefix,
@@ -39,6 +40,7 @@ export var rules = {
39
40
  'ensure-valid-bin-values': ensureValidBinValues,
40
41
  'expand-border-shorthand': expandBorderShorthand,
41
42
  'expand-background-shorthand': expandBackgroundShorthand,
43
+ 'expand-spacing-shorthand': expandSpacingShorthand,
42
44
  'no-duplicate-dependencies': noDuplicateDependencies,
43
45
  'no-invalid-feature-flag-usage': noInvalidFeatureFlagUsage,
44
46
  'no-pre-post-install-scripts': noPreAndPostInstallScripts,
@@ -65,6 +67,7 @@ var commonConfig = {
65
67
  // Compiled: rules that are not included via `@compiled/recommended
66
68
  '@atlaskit/platform/expand-border-shorthand': 'error',
67
69
  '@atlaskit/platform/expand-background-shorthand': 'error',
70
+ '@atlaskit/platform/expand-spacing-shorthand': 'off',
68
71
  '@compiled/jsx-pragma': ['error', {
69
72
  importSources: ['@atlaskit/css'],
70
73
  onlyRunIfImportingCompiled: true,
@@ -1,19 +1,4 @@
1
- import { getImportSources, isCompiled, isAtlasKitCSS } from '@atlaskit/eslint-utils/is-supported-import';
2
- import { getAncestors, getScope } from '../../util/context-compat';
3
-
4
- // Checks if the function that holds the border property is using an import package that this rule is targeting
5
- var isCompiledAPI = function isCompiledAPI(context, node) {
6
- var importSources = getImportSources(context);
7
- var _getScope = getScope(context, node),
8
- references = _getScope.references;
9
- var ancestors = getAncestors(context, node);
10
- if (ancestors.some(function (ancestor) {
11
- return ancestor.type === 'CallExpression' && ancestor.callee && (isCompiled(ancestor.callee, references, importSources) || isAtlasKitCSS(ancestor.callee, references, importSources));
12
- })) {
13
- return true;
14
- }
15
- return false;
16
- };
1
+ import { isCompiledAPI } from '../../util/compiled-utils';
17
2
 
18
3
  // Checks if node is a call expression with identifier 'token'
19
4
  var isTokenCallExpression = function isTokenCallExpression(node) {