@atlaskit/eslint-plugin-ui-styling-standard
Version:
The eslint plugin to enforce and educate on Atlassian's UI Styling Standard
223 lines (215 loc) • 9.24 kB
JavaScript
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; }
import esquery from 'esquery';
import estraverse from 'estraverse';
import { getAllowedDynamicKeys, getAllowedFunctionCalls, isAllowListedVariable } from '@atlaskit/eslint-utils/allowed-function-calls';
import { getScope, getSourceCode } from '@atlaskit/eslint-utils/context-compat';
import { findVariable } from '@atlaskit/eslint-utils/find-variable';
import { getImportSources, hasStyleObjectArguments, isCxFunction } from '@atlaskit/eslint-utils/is-supported-import';
import { createLintRule } from '../utils/create-rule';
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 = findVariable({
identifier: identifier,
sourceCode: 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 && !isAllowListedVariable({
allowList: functionAllowList,
variable: variable
}) && !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 = 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 = getImportSources(context);
var functionAllowList = getAllowedFunctionCalls(context.options);
var keysAllowList = getAllowedDynamicKeys(context.options);
var checkForIdentifiers = function checkForIdentifiers(node) {
var matches = esquery(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 isCxFunction(identifier, getScope(context, identifier).references, importSources);
};
return {
// Checking css/cssMap/keyframes/styled/xcss calls
CallExpression: function CallExpression(node) {
var _getScope = getScope(context, node),
references = _getScope.references;
if (!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.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.VisitorOption.Skip;
}
// Ignore conditions of ternary expressions
if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'ConditionalExpression' && node === parent.test) {
return estraverse.VisitorOption.Skip;
}
// Ignore LHS of logical expressions (&&, ||)
if ((parent === null || parent === void 0 ? void 0 : parent.type) === 'LogicalExpression' && node === parent.left) {
return estraverse.VisitorOption.Skip;
}
if (node.type !== 'Identifier') {
return;
}
if (isValidCx(jsxAttribute, node)) {
return;
}
checkIdentifier(node, context, functionAllowList, keysAllowList);
}
});
}
};
}
});
export default rule;