@atlaskit/eslint-plugin-design-system
Version:
The essential plugin for use with the Atlassian Design System.
91 lines (86 loc) • 3.02 kB
JavaScript
/* eslint-disable @repo/internal/react/require-jsdoc */
import { isNodeOfType } from 'eslint-codemod-utils';
import { getSourceCode } from '@atlaskit/eslint-utils/context-compat';
import { Root } from '../../../ast-nodes/root';
import { getNodeSource } from '../../utils/get-node-source';
import { isDecendantOfStyleBlock } from '../../utils/is-decendant-of-style-block';
import { isDecendantOfType } from '../../utils/is-decendant-of-type';
import { findFontFamilyTokenForValue } from '../find-font-family-token-for-value';
import { insertTokensImport } from '../insert-tokens-import';
export const FontFamily = {
lint(node, {
context,
config
}) {
// Check whether all criteria needed to make a transformation are met
const success = FontFamily._check(node, {
context,
config
});
if (success) {
return context.report({
node,
messageId: 'noRawFontFamilyValues',
...(config.enableUnsafeAutofix ? {
fix: FontFamily._fix(node, context)
} : {
suggest: [{
desc: 'Convert to font family token',
fix: FontFamily._fix(node, context)
}]
})
});
}
},
_check(node, {
context,
config
}) {
if (!config.patterns.includes('font-family')) {
return false;
}
if (!isNodeOfType(node, 'Property')) {
return false;
}
if (!isDecendantOfStyleBlock(node) && !isDecendantOfType(node, 'JSXExpressionContainer')) {
return false;
}
const isFontFamilyProperty = isNodeOfType(node.key, 'Identifier') && node.key.name === 'fontFamily';
const valueNodeSource = getNodeSource(getSourceCode(context), node.value);
if (isFontFamilyProperty && valueNodeSource.match(/(font\.family.|inherit)/)) {
return false;
}
return true;
},
_fix(node, context) {
return fixer => {
const fixes = [];
// Type assertions to force the correct node type
if (!isNodeOfType(node.value, 'Literal')) {
return fixes;
}
if (!node.value.raw) {
return fixes;
}
// Replace raw value with token if there is a token match
const matchingToken = findFontFamilyTokenForValue(String(node.value.value));
if (!matchingToken) {
return fixes;
}
const fontWeightValueFix = fixer.replaceText(node.value, `token('${matchingToken}')`);
fixes.push(fontWeightValueFix);
// Add import if it doesn't exist
const body = getSourceCode(context).ast.body;
const tokensImportDeclarations = Root.findImportsByModule(body, '@atlaskit/tokens');
// If there is more than one `@atlaskit/tokens` import, then it becomes difficult to determine which import to transform
if (tokensImportDeclarations.length > 1) {
return fixes;
}
const tokensImportDeclaration = tokensImportDeclarations[0];
if (!tokensImportDeclaration) {
fixes.push(insertTokensImport(body, fixer));
}
return fixes;
};
}
};