UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

382 lines (368 loc) • 17.1 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray")); var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty")); var _contextCompat = require("@atlaskit/eslint-utils/context-compat"); var _findVariable = require("@atlaskit/eslint-utils/find-variable"); var _createLintRule = require("../utils/create-lint-rule"); 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; } } }; } 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; } } 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; } 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; } 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; } /** * Values at or below this are local ordering within a component (a badge over an avatar, * a sticky header cell). Values above it are reaching for a global win. */ var MAX_LOCAL_Z_INDEX = 10; /** * Stops runaway resolution of `const a = b; const b = a;` style chains. */ var MAX_RESOLVE_DEPTH = 5; var NUMERIC_STRING = /^\s*([+-]?\d+)\s*(!important)?\s*$/; var CALC_INFINITY = /^\s*calc\(\s*infinity\s*\)\s*(!important)?\s*$/i; /** * Matches `z-index: <value>` inside a CSS string. The value stops at `;`, `}`, or a new line. * The lookbehind keeps the match index on `z-index`, so reports can point at it. */ var CSS_Z_INDEX = /(?<=^|[\s;{])z-index\s*:\s*([^;}\n]*)/gi; /** * The static name of a key or string argument: `zIndex`, `'zIndex'`, or `` `zIndex` ``. */ var getStaticName = function getStaticName(node) { if (node.type === 'Identifier') { return node.name; } if (node.type === 'Literal' && typeof node.value === 'string') { return node.value; } if (node.type === 'TemplateLiteral' && node.expressions.length === 0) { var _node$quasis$0$value$; return (_node$quasis$0$value$ = node.quasis[0].value.cooked) !== null && _node$quasis$0$value$ !== void 0 ? _node$quasis$0$value$ : null; } return null; }; var isZIndexName = function isZIndexName(name) { return name === 'zIndex' || name === 'z-index'; }; var parseCssValue = function parseCssValue(text) { if (CALC_INFINITY.test(text)) { return { value: Infinity, label: 'calc(infinity)' }; } var match = NUMERIC_STRING.exec(text); if (!match) { return null; } var value = Number(match[1]); return { value: value, label: String(value) }; }; var getRange = function getRange(node) { var _withRange$range, _withRange$start, _withRange$end; var withRange = node; return (_withRange$range = withRange.range) !== null && _withRange$range !== void 0 ? _withRange$range : [(_withRange$start = withRange.start) !== null && _withRange$start !== void 0 ? _withRange$start : 0, (_withRange$end = withRange.end) !== null && _withRange$end !== void 0 ? _withRange$end : 0]; }; /** * `expect(el).toHaveStyle({ zIndex: 700 })` asserts on a value, it doesn't set one. */ var isInExpectCall = function isInExpectCall(node) { var outermost = node; while (((_outermost$parent = outermost.parent) === null || _outermost$parent === void 0 ? void 0 : _outermost$parent.type) === 'Property' && ((_outermost$parent$par = outermost.parent.parent) === null || _outermost$parent$par === void 0 ? void 0 : _outermost$parent$par.type) === 'ObjectExpression' || ((_outermost$parent2 = outermost.parent) === null || _outermost$parent2 === void 0 ? void 0 : _outermost$parent2.type) === 'ObjectExpression') { var _outermost$parent, _outermost$parent$par, _outermost$parent2; outermost = outermost.parent; } var call = outermost.parent; if ((call === null || call === void 0 ? void 0 : call.type) !== 'CallExpression' || !call.arguments.includes(outermost)) { return false; } var callee = call.callee; while (callee.type === 'MemberExpression' || callee.type === 'CallExpression') { if (callee.type === 'CallExpression' && callee.callee.type === 'Identifier' && callee.callee.name === 'expect') { return true; } callee = callee.type === 'MemberExpression' ? callee.object : callee.callee; } // `expect.objectContaining({ zIndex: 700 })` return callee.type === 'Identifier' && callee.name === 'expect'; }; /** * Resolves a node to the numbers it can be, where that is knowable from the file alone. * Anything that can't be resolved (imports, function calls, `calc()`) is skipped. */ var _resolveValues = function resolveValues(node, context) { var depth = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; if (depth > MAX_RESOLVE_DEPTH) { return []; } switch (node.type) { case 'Literal': { var _ref = node, value = _ref.value; if (typeof value === 'number') { return [{ node: node, value: value, label: String(value) }]; } if (typeof value === 'string') { var parsed = parseCssValue(value); return parsed ? [_objectSpread({ node: node }, parsed)] : []; } return []; } case 'TemplateLiteral': { var _template$quasis$0$va; var template = node; if (template.expressions.length > 0) { return []; } var _parsed = parseCssValue((_template$quasis$0$va = template.quasis[0].value.cooked) !== null && _template$quasis$0$va !== void 0 ? _template$quasis$0$va : ''); return _parsed ? [_objectSpread({ node: node }, _parsed)] : []; } case 'UnaryExpression': { var unary = node; if (unary.operator !== '-' && unary.operator !== '+') { return []; } var sign = unary.operator === '-' ? -1 : 1; return _resolveValues(unary.argument, context, depth + 1).map(function (found) { var value = sign * found.value; return { node: node, value: value, label: Number.isFinite(value) ? String(value) : found.label }; }); } case 'ConditionalExpression': { var conditional = node; return [].concat((0, _toConsumableArray2.default)(_resolveValues(conditional.consequent, context, depth + 1)), (0, _toConsumableArray2.default)(_resolveValues(conditional.alternate, context, depth + 1))); } case 'LogicalExpression': { var logical = node; // `a && 500` can only be 500 (or a falsy `a`, which isn't a z-index) if (logical.operator === '&&') { return _resolveValues(logical.right, context, depth + 1); } // `options.zIndex ?? 1000` and `options.zIndex || 200` can be either side return [].concat((0, _toConsumableArray2.default)(_resolveValues(logical.left, context, depth + 1)), (0, _toConsumableArray2.default)(_resolveValues(logical.right, context, depth + 1))); } case 'TSAsExpression': case 'TSSatisfiesExpression': case 'TSNonNullExpression': case 'TSTypeAssertion': return _resolveValues(node.expression, context, depth); case 'Identifier': { var _definition$parent; var variable = (0, _findVariable.findVariable)({ identifier: node, sourceCode: (0, _contextCompat.getSourceCode)(context) }); var definition = (variable === null || variable === void 0 ? void 0 : variable.defs.length) === 1 ? variable.defs[0] : undefined; if (!definition || definition.type !== 'Variable' || ((_definition$parent = definition.parent) === null || _definition$parent === void 0 ? void 0 : _definition$parent.kind) !== 'const' || definition.node.id.type !== 'Identifier' || !definition.node.init) { return []; } // Report on the usage, not the declaration, so the message lands where z-index is set return _resolveValues(definition.node.init, context, depth + 1).map(function (found) { return _objectSpread(_objectSpread({}, found), {}, { node: node }); }); } default: return []; } }; var rule = (0, _createLintRule.createLintRule)({ meta: { name: 'no-global-z-index', type: 'problem', docs: { description: 'Disallow `z-index` values above 10. Global layer ordering is handled by the browser top layer.', recommended: false, severity: 'warn' }, messages: { noGlobalZIndex: "`z-index: {{value}}` looks like it competes in the global stack. Top layer surfaces ignore `z-index`, so this ordering won't hold against them. Use a Design System layering component or `@atlaskit/top-layer`. Values of 10 or less are fine for local ordering." } }, create: function create(context) { var sourceCode = (0, _contextCompat.getSourceCode)(context); var reportValues = function reportValues(node) { var _iterator = _createForOfIteratorHelper(_resolveValues(node, context)), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var found = _step.value; if (found.value > MAX_LOCAL_Z_INDEX) { context.report({ node: found.node, messageId: 'noGlobalZIndex', data: { value: found.label } }); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; return { // css({ zIndex: 500 }), styled.div({ zIndex: 500 }), style={{ zIndex: 500 }}, // react-select `styles` overrides, and any other object style Property: function Property(node) { if (node.type !== 'Property' || node.parent.type !== 'ObjectExpression') { return; } // Getters and methods named `zIndex` compute a value we can't know if (node.kind !== 'init' || node.method) { return; } // `{ [key]: 500 }` is a variable lookup, not a `zIndex` property if (node.computed && node.key.type === 'Identifier') { return; } if (!isZIndexName(getStaticName(node.key))) { return; } if (isInExpectCall(node.parent)) { return; } reportValues(node.value); }, // <Portal zIndex={500} /> JSXAttribute: function JSXAttribute(node) { var attribute = node; if (attribute.name.type !== 'JSXIdentifier' || attribute.name.name !== 'zIndex') { return; } if (!attribute.value) { return; } if (attribute.value.type === 'JSXExpressionContainer') { reportValues(attribute.value.expression); return; } reportValues(attribute.value); }, // element.style.zIndex = '9999' AssignmentExpression: function AssignmentExpression(node) { if (node.type !== 'AssignmentExpression' || node.operator !== '=' || node.left.type !== 'MemberExpression') { return; } var _node$left = node.left, object = _node$left.object, property = _node$left.property, computed = _node$left.computed; // `style[key]` is a variable lookup, not a `zIndex` property if (computed && property.type === 'Identifier') { return; } if (!isZIndexName(getStaticName(property))) { return; } // Only `<something>.style.zIndex`. Other `.zIndex` writes are not CSS. if (object.type !== 'MemberExpression' || object.computed && object.property.type === 'Identifier' || getStaticName(object.property) !== 'style') { return; } reportValues(node.right); }, // element.style.setProperty('z-index', '9999') CallExpression: function CallExpression(node) { if (node.type !== 'CallExpression' || node.callee.type !== 'MemberExpression' || node.callee.property.type !== 'Identifier' || node.callee.property.name !== 'setProperty') { return; } var _node$arguments = (0, _slicedToArray2.default)(node.arguments, 2), name = _node$arguments[0], value = _node$arguments[1]; if (!name || !value || name.type === 'SpreadElement' || value.type === 'SpreadElement' || getStaticName(name) !== 'z-index') { return; } reportValues(value); }, // css`z-index: 500;`, styled.div`z-index: ${Z};`, createGlobalStyle`...` TaggedTemplateExpression: function TaggedTemplateExpression(node) { if (node.type !== 'TaggedTemplateExpression') { return; } var _node$quasi = node.quasi, quasis = _node$quasi.quasis, expressions = _node$quasi.expressions; quasis.forEach(function (quasi, index) { var text = quasi.value.raw; var isLastQuasi = index === quasis.length - 1; // Where `text` starts in the file. Parsers differ on whether the quasi's range // includes the `` ` ``, `${` and `}` delimiters, so find it in the quasi's own text. var _getRange = getRange(quasi), _getRange2 = (0, _slicedToArray2.default)(_getRange, 1), quasiStart = _getRange2[0]; var textStart = quasiStart + sourceCode.getText(quasi).indexOf(text); var _iterator2 = _createForOfIteratorHelper(text.matchAll(CSS_Z_INDEX)), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var _match$index; var match = _step2.value; var valueText = match[1]; var matchIndex = (_match$index = match.index) !== null && _match$index !== void 0 ? _match$index : 0; var endsQuasi = matchIndex + match[0].length === text.length; // `z-index: ${value}` — the value is the next expression if (endsQuasi && !isLastQuasi && valueText.trim() === '') { reportValues(expressions[index]); continue; } // `z-index: 1${x}` — the value runs into an expression, so we can't know it if (endsQuasi && !isLastQuasi) { continue; } var parsed = parseCssValue(valueText); if (parsed && parsed.value > MAX_LOCAL_Z_INDEX) { var start = textStart + matchIndex; var end = start + match[0].trimEnd().length; context.report({ loc: { start: sourceCode.getLocFromIndex(start), end: sourceCode.getLocFromIndex(end) }, messageId: 'noGlobalZIndex', data: { value: parsed.label } }); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } }); } }; } }); var _default = exports.default = rule;