UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

92 lines (87 loc) 3.17 kB
/* 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 { findFontWeightTokenForValue } from '../find-font-weight-token-for-value'; import { insertTokensImport } from '../insert-tokens-import'; export const FontWeight = { lint(node, { context, config }) { // Check whether all criteria needed to make a transformation are met const success = FontWeight._check(node, { context, config }); if (success) { return context.report({ node, messageId: 'noRawFontWeightValues', ...(config.enableUnsafeAutofix ? { fix: FontWeight._fix(node, context) } : { suggest: [{ desc: 'Convert to font weight token', fix: FontWeight._fix(node, context) }] }) }); } }, _check(node, { context, config }) { if (!config.patterns.includes('font-weight')) { return false; } if (!isNodeOfType(node, 'Property')) { return false; } if (!isDecendantOfStyleBlock(node) && !isDecendantOfType(node, 'JSXExpressionContainer')) { return false; } const isFontWeightProperty = isNodeOfType(node.key, 'Identifier') && node.key.name === 'fontWeight'; const valueNodeSource = getNodeSource(getSourceCode(context), node.value); if (isFontWeightProperty && valueNodeSource.match(/(font\.weight.|inherit)/)) { return false; } return true; }, _fix(node, context) { return fixer => { var _findFontWeightTokenF; 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 = (_findFontWeightTokenF = findFontWeightTokenForValue(String(node.value.value))) === null || _findFontWeightTokenF === void 0 ? void 0 : _findFontWeightTokenF.tokenName; 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; }; } };