UNPKG

@atlaskit/eslint-plugin-ui-styling-standard

Version:

The eslint plugin to enforce and educate on Atlassian's UI Styling Standard

230 lines (221 loc) • 9.73 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _esquery = _interopRequireDefault(require("esquery")); var _estraverse = _interopRequireDefault(require("estraverse")); var _allowedFunctionCalls = require("@atlaskit/eslint-utils/allowed-function-calls"); var _contextCompat = require("@atlaskit/eslint-utils/context-compat"); var _findVariable = require("@atlaskit/eslint-utils/find-variable"); var _isSupportedImport = require("@atlaskit/eslint-utils/is-supported-import"); var _createRule = require("../utils/create-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; } var schema = [{ type: 'object', properties: { importSources: { type: 'array', items: { type: 'string' }, uniqueItems: true }, allowedFunctionCalls: { type: 'array', items: { type: 'array', minItems: 2, maxItems: 2, items: [{ type: 'string' }, { type: 'string' }] }, uniqueItems: true }, allowedDynamicKeys: { type: 'array', items: { type: 'array', minItems: 2, maxItems: 2, items: [{ type: 'string' }, { type: 'string' }] }, uniqueItems: true } } }]; var isIdentifierImported = function isIdentifierImported(identifier, context, functionAllowList, keysAllowList) { var variable = (0, _findVariable.findVariable)({ identifier: identifier, sourceCode: (0, _contextCompat.getSourceCode)(context) }); if (!variable) { return false; } var isImported = variable.defs.some(function (definition) { return definition.type === 'ImportBinding'; }); // check if imported variable is allowed return isImported && !(0, _allowedFunctionCalls.isAllowListedVariable)({ allowList: functionAllowList, variable: variable }) && !(0, _allowedFunctionCalls.isAllowListedVariable)({ allowList: keysAllowList, variable: variable }); }; var checkIdentifier = function checkIdentifier(identifier, context, functionAllowList, keysAllowList) { var _ref = identifier, parent = _ref.parent; // Type references and `typeof` queries are erased at runtime and are not // imported style values. Runtime expressions wrapped by `as` or `satisfies` // must still be checked. // Qualified names (e.g. `typeof Tokens.COLOR_TEXT` or `Theme.Colors`) nest the // identifier inside one or more `TSQualifiedName` nodes, so walk up through them // to find the enclosing type node. var typeContext = parent; while (typeContext && typeContext.type === 'TSQualifiedName') { typeContext = typeContext.parent; } if (typeContext && (typeContext.type === 'TSTypeReference' || typeContext.type === 'TSTypeQuery')) { return; } // Even though `member` in `object.member` is syntactically an identifier, // it should be ignored as `.member` is syntax sugar for `['member']` here. // We should still lint `object[member]` (when `parent.computed` === true) if (parent.type === 'MemberExpression' && identifier === parent.property && !parent.computed) { return; } // Even though `key` in `{ key: 'value' }` is syntactically an identifier, // it should be ignored as `key` is syntax sugar for `'key'` here. // We should still lint `[key]` (when `parent.computed` === true) if (parent && parent.type === 'Property' && identifier === parent.key && !parent.computed) { return; } if (isIdentifierImported(identifier, context, functionAllowList, keysAllowList)) { context.report({ node: identifier, messageId: 'no-imported-style-values' }); } }; var rule = (0, _createRule.createLintRule)({ meta: { name: 'no-imported-style-values', docs: { description: 'Disallows imports of style values', recommended: true, severity: 'error' }, messages: { 'no-imported-style-values': "Declare and use these styles in the same file. Share a component across files instead of importing css, cssMap, styled, keyframes or xcss values." }, type: 'problem', schema: schema }, create: function create(context) { var importSources = (0, _isSupportedImport.getImportSources)(context); var functionAllowList = (0, _allowedFunctionCalls.getAllowedFunctionCalls)(context.options); var keysAllowList = (0, _allowedFunctionCalls.getAllowedDynamicKeys)(context.options); var checkForIdentifiers = function checkForIdentifiers(node) { var matches = (0, _esquery.default)(node, 'Identifier'); var _iterator = _createForOfIteratorHelper(matches), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var match = _step.value; if (match.type === 'Identifier') { checkIdentifier(match, context, functionAllowList, keysAllowList); } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } }; var isValidCx = function isValidCx(jsxAttribute, identifier) { /** * We don't want to allow `cx` for `css` (or `style`) */ if (jsxAttribute.name.name !== 'xcss') { return false; } /** * Check we have the exact form of `xcss={cx(...)}` otherwise it isn't valid. */ var jsxExpression = jsxAttribute.value; if ((jsxExpression === null || jsxExpression === void 0 ? void 0 : jsxExpression.type) !== 'JSXExpressionContainer') { return false; } var callExpression = jsxExpression.expression; if ((callExpression === null || callExpression === void 0 ? void 0 : callExpression.type) !== 'CallExpression') { return false; } if (callExpression.callee !== identifier) { return false; } return (0, _isSupportedImport.isCxFunction)(identifier, (0, _contextCompat.getScope)(context, identifier).references, importSources); }; return { // Checking css/cssMap/keyframes/styled/xcss calls CallExpression: function CallExpression(node) { var _getScope = (0, _contextCompat.getScope)(context, node), references = _getScope.references; if (!(0, _isSupportedImport.hasStyleObjectArguments)(node.callee, references, importSources)) { return; } node.arguments.forEach(checkForIdentifiers); }, 'JSXAttribute[name.name=/^(style|css|xcss)$/]': function JSXAttributeNameName_StyleCssXcss$_(jsxAttribute) { if (jsxAttribute.type !== 'JSXAttribute') { return; } _estraverse.default.traverse(jsxAttribute, { fallback: function fallback(node) { // estraverse does not know about nodes not in the ESTree standard. // This includes JSX nodes, so we must provide a fallback method to handle them. // Using `fallback: 'iteration'` can cause cycles because it will iterate // over the `parent` attribute on JSX nodes. return Object.keys(node).filter(function (key) { return key !== 'parent'; }); }, enter: function enter(node, parent) { // Ignore type contexts // Cast required because ESTree is not aware of TypeScript nodes if (node.type === 'TSTypeReference') { return _estraverse.default.VisitorOption.Skip; } // Ignore conditions of ternary expressions if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'ConditionalExpression' && node === parent.test) { return _estraverse.default.VisitorOption.Skip; } // Ignore LHS of logical expressions (&&, ||) if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'LogicalExpression' && node === parent.left) { return _estraverse.default.VisitorOption.Skip; } if (node.type !== 'Identifier') { return; } if (isValidCx(jsxAttribute, node)) { return; } checkIdentifier(node, context, functionAllowList, keysAllowList); } }); } }; } }); var _default = exports.default = rule;