UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

116 lines (111 loc) 3.29 kB
/* eslint-disable @repo/internal/react/require-jsdoc */ import { isNodeOfType } from 'eslint-codemod-utils'; import { getSourceCode } from '@atlaskit/eslint-utils/context-compat'; import { JSXElementHelper } from '../../../ast-nodes/jsx-element-helper'; import { Root } from '../../../ast-nodes/root'; import { addColorInheritAttributeFix } from './add-color-inherit-attribute-fix'; import { allowedAttrs } from './allowed-attrs'; import { hasTextChildrenOnly } from './has-text-children-only'; import { updateTestIdAttributeFix } from './update-test-id-attribute-fix'; export const SpanElements = { lint(node, { context, config }) { if (!isNodeOfType(node, 'JSXElement')) { return; } // Check whether all criteria needed to make a transformation are met const { success, autoFixable } = SpanElements._check(node, { context, config }); if (success && autoFixable) { const fix = SpanElements._fix(node, { context, config }); context.report({ node: node.openingElement, messageId: 'preferPrimitivesText', ...(config.enableUnsafeAutofix ? { fix } : { suggest: [{ desc: `Convert to Text`, fix }] }) }); } else if (success && config.enableUnsafeReport) { context.report({ node: node.openingElement, messageId: 'preferPrimitivesText' }); } }, _check(node, { context, config }) { if (!config.patterns.includes('span-elements')) { return { success: false }; } const elementName = JSXElementHelper.getName(node); if (elementName !== 'span') { return { success: false }; } if (!node.children.length) { return { success: false }; } // Only allow elements with strings as children if (!hasTextChildrenOnly(node)) { return { success: false }; } // Element has no unallowed props if (!JSXElementHelper.hasAllowedAttrsOnly(node, allowedAttrs)) { return { success: true, autoFixable: false }; } // If there is more than one `@atlaskit/primitives` import, then it becomes difficult to determine which import to transform const importDeclaration = Root.findImportsByModule(getSourceCode(context).ast.body, '@atlaskit/primitives'); if (importDeclaration.length > 1) { return { success: true, autoFixable: false }; } return { success: true, autoFixable: true }; }, _fix(node, { context, config }) { return fixer => { const importFix = Root.upsertNamedImportDeclaration({ module: '@atlaskit/primitives', specifiers: ['Text'] }, context, fixer); const elementNameFixes = JSXElementHelper.updateName(node, 'Text', fixer); const colorAttributeFix = addColorInheritAttributeFix(node, config, fixer); const testAttributeFix = updateTestIdAttributeFix(node, fixer); return [importFix, ...elementNameFixes, colorAttributeFix, testAttributeFix].filter(fix => Boolean(fix)); // Some of the transformers can return arrays with undefined, so filter them out }; } };