UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

639 lines (610 loc) • 29 kB
import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; } function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; } 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 { isNodeOfType } from 'eslint-codemod-utils'; import { createLintRule } from '../utils/create-lint-rule'; import { isImportFromPackage } from '../utils/is-import-from-package'; var LOZENGE_IMPORT_SOURCES = new Set(['@atlaskit/lozenge', '@atlaskit/lozenge/lozenge']); var BADGE_IMPORT_SOURCES = new Set(['@atlaskit/badge', '@atlaskit/badge/badge']); var SIMPLE_TAG_IMPORT_SOURCES = new Set(['@atlaskit/tag/simple-tag']); var REMOVABLE_TAG_IMPORT_SOURCES = new Set(['@atlaskit/tag', '@atlaskit/tag/removable-tag']); var AVATAR_IMPORT_SOURCES = new Set(['@atlaskit/avatar', '@atlaskit/avatar/avatar', '@atlaskit/avatar/Avatar']); var rule = createLintRule({ meta: { name: 'lozenge-badge-tag-labelling-system-migration', fixable: 'code', type: 'suggestion', docs: { description: 'Migrates legacy Lozenge and Badge appearance values and guides SimpleTag/RemovableTag migrations to the supported Tag APIs.', recommended: false, severity: 'warn' }, messages: { updateAppearance: 'Replace Lozenge appearance="{{oldValue}}" with appearance="{{newValue}}"; apply the autofix.', migrateTag: '{{remedy}} {{reason}} See the lozenge-badge-tag-labelling-system-migration README in @atlaskit/eslint-plugin-design-system for examples.', updateBadgeAppearance: 'Update Badge appearance value "{{oldValue}}" to new semantic value "{{newValue}}".', dynamicBadgeAppearance: 'Dynamic appearance prop values require manual review to ensure they use the new semantic values: neutral, information, inverse, danger, success.' } }, create: function create(context) { /** * Contains a map of imported Lozenge components. */ var lozengeImports = {}; // local name -> import source /** * Contains a map of imported Badge components. */ var badgeImports = {}; // local name -> import source /** * Contains a map of imported Tag components (SimpleTag, RemovableTag, or default Tag imports). * Maps local name to { type: 'SimpleTag' | 'RemovableTag' | 'Tag', source: string, node: ImportNode } */ var tagImports = {}; /** * Contains a map of imported Avatar components from @atlaskit/avatar. * Maps local name to import source */ var avatarImports = {}; /** * Contains a map of imported Tag and AvatarTag components from @atlaskit/tag. * These are the new components that should not be migrated. * Maps local name to import source */ var newTagImports = {}; /** * Check if a JSX attribute value is dynamic (not a static literal value) * Can be used for any prop type (boolean, string, etc.) */ function isDynamicExpression(node) { if (!node) { return false; } // If it's a plain literal (e.g., appearance="value"), it's not dynamic if (node.type === 'Literal') { return false; } // If it's an expression container with a non-literal expression, it's dynamic if (node.type === 'JSXExpressionContainer') { var expr = node.expression; return expr && expr.type !== 'Literal'; } return false; } /** * Get all attributes as an object for easier manipulation */ function getAttributesMap(attributes) { var map = {}; attributes.forEach(function (attr) { if (attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier') { map[attr.name.name] = attr; } }); return map; } /** * Map old Lozenge appearance values to new semantic appearance values. * The new Lozenge no longer uses legacy values — it uses semantic color names * that align with the new labelling system. */ function mapToNewAppearanceValue(oldValue) { var mapping = { default: 'neutral', inprogress: 'information', moved: 'warning', removed: 'danger', new: 'discovery', success: 'success' }; return mapping[oldValue] || oldValue; } /** * Map Badge old appearance values to new semantic appearance values */ function mapBadgeToNewAppearanceValue(oldValue) { var mapping = { added: 'success', removed: 'danger', default: 'neutral', primary: 'information', primaryInverted: 'inverse', important: 'danger' }; return mapping[oldValue] || oldValue; } /** * Map Tag color light variants to semantic color values */ function mapTagColorValue(oldValue) { var mapping = { limeLight: 'lime', orangeLight: 'orange', magentaLight: 'magenta', greenLight: 'green', blueLight: 'blue', redLight: 'red', purpleLight: 'purple', greyLight: 'gray', tealLight: 'teal', yellowLight: 'yellow', grey: 'gray' }; return mapping[oldValue] || oldValue; } /** * Check if elemBefore prop contains only an Avatar component from @atlaskit/avatar * Returns the Avatar component name if it's from the avatar package, null otherwise */ function getAvatarComponentName(elemBeforeProp) { var getJsxIdentifierName = function getJsxIdentifierName(node) { return (node === null || node === void 0 ? void 0 : node.type) === 'JSXIdentifier' ? node.name : null; }; if (!elemBeforeProp || !elemBeforeProp.value) { return null; } var value = elemBeforeProp.value; // Check for JSX element: <Avatar ... /> if (value.type === 'JSXElement') { var avatarName = getJsxIdentifierName(value.openingElement.name); if (!avatarName) { return null; } if (avatarImports[avatarName]) { return avatarName; } } // Check for JSX expression container: {<Avatar ... />} if (value.type === 'JSXExpressionContainer' && value.expression) { // Direct JSX element: {<Avatar ... />} if (value.expression.type === 'JSXElement' && getJsxIdentifierName(value.expression.openingElement.name)) { var _avatarName = getJsxIdentifierName(value.expression.openingElement.name); if (!_avatarName) { return null; } if (avatarImports[_avatarName]) { return _avatarName; } } // Arrow function: {() => <Avatar ... />} if (value.expression.type === 'ArrowFunctionExpression') { var body = value.expression.body; if (body.type === 'JSXElement') { var _avatarName2 = getJsxIdentifierName(body.openingElement.name); if (!_avatarName2) { return null; } if (avatarImports[_avatarName2]) { return _avatarName2; } } } } return null; } /** * Check if color prop value needs mapping */ function colorNeedsMapping(colorProp) { if (!(colorProp !== null && colorProp !== void 0 && colorProp.value)) { return false; } var stringValue = extractStringValue(colorProp.value); return stringValue !== null && typeof stringValue === 'string' && mapTagColorValue(stringValue) !== stringValue; } /** * Extract the string value from a JSX attribute value */ function extractStringValue(attrValue) { if (!attrValue) { return null; } if (attrValue.type === 'Literal') { return attrValue.value; } if (attrValue.type === 'JSXExpressionContainer' && attrValue.expression && attrValue.expression.type === 'Literal') { return attrValue.expression.value; } return null; } /** * Create a fixer function to replace an appearance prop value * Handles both Literal and JSXExpressionContainer with Literal */ function createAppearanceFixer(attrValue, newValue) { return function (fixer) { if (!attrValue) { return null; } if (attrValue.type === 'Literal') { return fixer.replaceText(attrValue, "\"".concat(newValue, "\"")); } if (attrValue.type === 'JSXExpressionContainer' && 'expression' in attrValue && attrValue.expression && attrValue.expression.type === 'Literal') { return fixer.replaceText(attrValue.expression, "\"".concat(newValue, "\"")); } return null; }; } // Only rewrite an isolated, statically understood plain Tag. Other uses retain // diagnostics so the migration can account for their bindings and behavior. function getPlainTagFix(node, info) { var _context$sourceCode, _info$node; // @ts-ignore - Jira's ESLint v10 types expose sourceCode, platform still checks with ESLint v9. var sourceCode = (_context$sourceCode = context.sourceCode) !== null && _context$sourceCode !== void 0 ? _context$sourceCode : context.getSourceCode(); var declaration = (_info$node = info.node) === null || _info$node === void 0 ? void 0 : _info$node.parent; if (!declaration || declaration.specifiers.length !== 1) { return { reason: 'Migrate the mixed import manually, preserving every remaining binding.' }; } if (sourceCode.getCommentsInside(node).length > 0) { return { reason: 'Preserve component comments while migrating manually.' }; } if (sourceCode.getCommentsInside(declaration).length > 0) { return { reason: 'Preserve the import comments while migrating manually.' }; } if (sourceCode.ast.body.some(function (statement) { return statement.type === 'ImportDeclaration' && statement.source.value === '@atlaskit/tag/tag-new'; })) { return { reason: 'Reuse the existing tag-new import after checking its local binding.' }; } var attrs = node.openingElement.attributes; var supported = new Set(['text', 'color', 'elemBefore', 'testId', 'href', 'removeButtonLabel', 'isRemovable']); var seen = new Set(); var text; var _iterator = _createForOfIteratorHelper(attrs), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var attr = _step.value; if (attr.type !== 'JSXAttribute' || attr.name.type !== 'JSXIdentifier' || !supported.has(attr.name.name) || seen.has(attr.name.name)) { return { reason: 'Review spread, duplicate, and unsupported props against TagNewProps before migrating.' }; } seen.add(attr.name.name); var value = extractStringValue(attr.value); if (attr.name.name === 'elemBefore') { var _attr$value; var elemBefore = ((_attr$value = attr.value) === null || _attr$value === void 0 ? void 0 : _attr$value.type) === 'JSXExpressionContainer' ? attr.value.expression : attr.value; if ((elemBefore === null || elemBefore === void 0 ? void 0 : elemBefore.type) !== 'JSXElement' && (elemBefore === null || elemBefore === void 0 ? void 0 : elemBefore.type) !== 'JSXFragment' && !((elemBefore === null || elemBefore === void 0 ? void 0 : elemBefore.type) === 'Literal' && typeof elemBefore.value === 'string')) { return { reason: 'Pass through only a static ReactNode elemBefore; review callbacks and dynamic values manually.' }; } } if (attr.name.name === 'text' && typeof value === 'string') { text = value; } if (attr.name.name === 'isRemovable') { var _attr$value2; var expression = ((_attr$value2 = attr.value) === null || _attr$value2 === void 0 ? void 0 : _attr$value2.type) === 'JSXExpressionContainer' ? attr.value.expression : attr.value; if (info.type === 'SimpleTag' || attr.value && !((expression === null || expression === void 0 ? void 0 : expression.type) === 'Literal' && typeof expression.value === 'boolean')) { return { reason: 'Set removability explicitly after reviewing the legacy component behavior.' }; } } else if (attr.name.name !== 'elemBefore' && typeof value !== 'string') { return { reason: 'Check dynamic prop values against TagNewProps before migrating.' }; } if (attr.name.name === 'color' && !new Set(['gray', 'blue', 'red', 'yellow', 'green', 'teal', 'purple', 'lime', 'orange', 'magenta']).has(mapTagColorValue(value))) { return { reason: 'Choose a supported NewTagColor before migrating.' }; } } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } if (node.children.length > 0) { if (seen.has('text')) { return { reason: 'Compare the text prop with its children before migrating.' }; } var _node$children = _slicedToArray(node.children, 1), child = _node$children[0]; if (node.children.length !== 1 || child.type !== 'JSXText' || typeof child.value !== 'string' || child.value.length === 0 || child.value.trim() !== child.value) { return { reason: 'Review children manually; only one plain text child can be copied to the new Tag text prop safely.' }; } text = child.value; } else if (!seen.has('text')) { return { reason: 'Supply the required text prop before migrating.' }; } var names = new Set(); var otherUse = false; var _visit = function visit(current) { var _sourceCode$visitorKe; if (current.type === 'Identifier' || current.type === 'JSXIdentifier') { var _node$closingElement; names.add(current.name); if (current.name === node.openingElement.name.name && !(current.range[0] >= declaration.range[0] && current.range[1] <= declaration.range[1]) && current !== node.openingElement.name && current !== ((_node$closingElement = node.closingElement) === null || _node$closingElement === void 0 ? void 0 : _node$closingElement.name)) { otherUse = true; } } var _iterator2 = _createForOfIteratorHelper((_sourceCode$visitorKe = sourceCode.visitorKeys[current.type]) !== null && _sourceCode$visitorKe !== void 0 ? _sourceCode$visitorKe : []), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var key = _step2.value; var _child = current[key]; if (Array.isArray(_child)) { _child.forEach(function (item) { return item && _visit(item); }); } else if (_child) { _visit(_child); } } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } }; _visit(sourceCode.ast); if (otherUse) { return { reason: 'Migrate every use of this binding together; a single-site fix would break other references.' }; } names.delete(node.openingElement.name.name); var name = 'Tag'; var suffix = 1; while (names.has(name)) { name = suffix === 1 ? 'MigratedTag' : "MigratedTag".concat(suffix); suffix++; } return { reason: 'Apply the autofix for this isolated plain Tag.', name: name, text: text, hasTextProp: seen.has('text') }; } return { ImportDeclaration: function ImportDeclaration(node) { var moduleSource = node.source.value; if (typeof moduleSource === 'string') { // Track Lozenge imports if (LOZENGE_IMPORT_SOURCES.has(moduleSource)) { node.specifiers.forEach(function (spec) { if (spec.type === 'ImportDefaultSpecifier') { lozengeImports[spec.local.name] = moduleSource; } else if (spec.type === 'ImportSpecifier' && spec.imported.type === 'Identifier') { if (spec.imported.name === 'Lozenge') { lozengeImports[spec.local.name] = moduleSource; } } }); } // Track Badge imports if (BADGE_IMPORT_SOURCES.has(moduleSource)) { node.specifiers.forEach(function (spec) { if (spec.type === 'ImportDefaultSpecifier') { badgeImports[spec.local.name] = moduleSource; } else if (spec.type === 'ImportSpecifier' && spec.imported.type === 'Identifier') { if (spec.imported.name === 'Badge' || spec.imported.name === 'default') { badgeImports[spec.local.name] = moduleSource; } } }); } // Track legacy Tag imports. The root default remains RemovableTag. if (isImportFromPackage(moduleSource, '@atlaskit/tag')) { node.specifiers.forEach(function (spec) { if (spec.type === 'ImportDefaultSpecifier') { // Check for default imports from subpaths and main package if (SIMPLE_TAG_IMPORT_SOURCES.has(moduleSource)) { // Default import from @atlaskit/tag/simple-tag is a SimpleTag tagImports[spec.local.name] = { type: 'SimpleTag', source: moduleSource, node: _objectSpread(_objectSpread({}, spec), {}, { parent: node }) }; } else if (REMOVABLE_TAG_IMPORT_SOURCES.has(moduleSource)) { // Default import from @atlaskit/tag/removable-tag or @atlaskit/tag is a RemovableTag tagImports[spec.local.name] = { type: 'RemovableTag', source: moduleSource, node: _objectSpread(_objectSpread({}, spec), {}, { parent: node }) }; } } else if (spec.type === 'ImportSpecifier' && spec.imported.type === 'Identifier') { var importName = spec.imported.name; if (importName === 'SimpleTag' || importName === 'RemovableTag') { tagImports[spec.local.name] = { type: importName, source: moduleSource, node: _objectSpread(_objectSpread({}, spec), {}, { parent: node }) }; } else if (importName === 'AvatarTag') { // Track new AvatarTag component - it should not be migrated newTagImports[spec.local.name] = moduleSource; } // Note: Tag from named imports is not skipped - it may still need migration // (e.g., if it has appearance prop or other old props) } }); } // Track Avatar imports if (AVATAR_IMPORT_SOURCES.has(moduleSource)) { node.specifiers.forEach(function (spec) { if (spec.type === 'ImportDefaultSpecifier') { avatarImports[spec.local.name] = moduleSource; } else if (spec.type === 'ImportSpecifier' && spec.imported.type === 'Identifier') { if (spec.imported.name === 'Avatar') { avatarImports[spec.local.name] = moduleSource; } } }); } } }, JSXElement: function JSXElement(node) { if (!isNodeOfType(node, 'JSXElement')) { return; } if (!isNodeOfType(node.openingElement.name, 'JSXIdentifier')) { return; } var elementName = node.openingElement.name.name; // Skip new AvatarTag component - it should not be migrated if (newTagImports[elementName]) { return; } // Handle SimpleTag, RemovableTag, and Tag migrations if (tagImports[elementName]) { var tagImportInfo = tagImports[elementName]; var _attributesMap = getAttributesMap(node.openingElement.attributes); var elemBeforeProp = _attributesMap.elemBefore, avatarProp = _attributesMap.avatar, _appearanceProp = _attributesMap.appearance, colorProp = _attributesMap.color; // Preserve the existing detection scope for root default imports. if (tagImportInfo.type === 'RemovableTag' && tagImportInfo.source === '@atlaskit/tag') { // Root avatar-prop consumers are outside this rule's existing migration scope. if (avatarProp) { return; } // Check if component name is already correct and nothing needs migration if (elementName === 'Tag' || elementName === 'AvatarTag') { var needsNameChange = false; var needsMigration = needsNameChange || _appearanceProp || colorNeedsMapping(colorProp); if (!needsMigration) { // Still need to check elemBefore for Avatar if (elemBeforeProp) { var _hasAvatarInElemBefore = getAvatarComponentName(elemBeforeProp) !== null; if (_hasAvatarInElemBefore) { // Has Avatar in elemBefore, needs migration to AvatarTag } else { // No Avatar, nothing to migrate return; } } else { // No elemBefore, nothing to migrate return; } } // If we get here, something needs migration } } // Determine migration target based on elemBefore containing Avatar var hasAvatarInElemBefore = elemBeforeProp ? getAvatarComponentName(elemBeforeProp) !== null : false; var migration = hasAvatarInElemBefore ? { reason: 'Choose type="user", "other", or "agent" from the represented entity; automatic inference is unsafe.' } : getPlainTagFix(node, tagImportInfo); context.report({ node: node, messageId: 'migrateTag', data: { remedy: hasAvatarInElemBefore ? "Import AvatarTag from '@atlaskit/tag/avatar-tag'; pass text, type, and avatar={(props) => <Avatar {...props} />}. Preserve non-removability for SimpleTag." : "Import Tag from '@atlaskit/tag/tag-new'; pass text (string or string[]) and use isRemovable={false} for SimpleTag.", reason: migration.reason }, fix: 'name' in migration && migration.name ? function (fixer) { var _context$sourceCode2; // @ts-ignore - Jira's ESLint v10 types expose sourceCode, platform still checks with ESLint v9. var sourceCode = (_context$sourceCode2 = context.sourceCode) !== null && _context$sourceCode2 !== void 0 ? _context$sourceCode2 : context.getSourceCode(); var attributes = node.openingElement.attributes.map(function (attr) { return attr.name.name === 'color' ? "color=\"".concat(mapTagColorValue(extractStringValue(attr.value)), "\"") : sourceCode.getText(attr); }); if (tagImportInfo.type === 'SimpleTag') { attributes.push('isRemovable={false}'); } if (!migration.hasTextProp && migration.text !== undefined) { attributes.push("text=".concat(JSON.stringify(migration.text))); } return [fixer.replaceText(tagImportInfo.node.parent, "import ".concat(migration.name, " from '@atlaskit/tag/tag-new';")), fixer.replaceText(node, "<".concat(migration.name, " ").concat(attributes.join(' '), " />"))]; } : undefined }); return; } // Handle Badge components if (badgeImports[elementName]) { // Find the appearance prop var _appearanceProp2 = node.openingElement.attributes.find(function (attr) { return attr.type === 'JSXAttribute' && attr.name.type === 'JSXIdentifier' && attr.name.name === 'appearance'; }); if (!_appearanceProp2 || _appearanceProp2.type !== 'JSXAttribute') { // No appearance prop or it's a spread attribute, nothing to migrate return; } // Check if it's a dynamic expression if (isDynamicExpression(_appearanceProp2.value)) { context.report({ node: _appearanceProp2, messageId: 'dynamicBadgeAppearance' }); return; } // Extract the string value var stringValue = extractStringValue(_appearanceProp2.value); if (stringValue && typeof stringValue === 'string') { var mappedValue = mapBadgeToNewAppearanceValue(stringValue); if (mappedValue !== stringValue) { context.report({ node: _appearanceProp2, messageId: 'updateBadgeAppearance', data: { oldValue: stringValue, newValue: mappedValue }, fix: createAppearanceFixer(_appearanceProp2.value, mappedValue) }); } } return; } // Only process if this is a Lozenge component we've imported if (!lozengeImports[elementName]) { return; } var attributesMap = getAttributesMap(node.openingElement.attributes); var appearanceProp = attributesMap.appearance; // Handle appearance prop value migration — always update to new semantic values. // isBold cleanup is outside this rule; check the installed Lozenge API separately. if (appearanceProp) { var _stringValue = extractStringValue(appearanceProp.value); if (_stringValue && typeof _stringValue === 'string') { var _mappedValue = mapToNewAppearanceValue(_stringValue); if (_mappedValue !== _stringValue) { context.report({ node: appearanceProp, messageId: 'updateAppearance', data: { oldValue: _stringValue, newValue: _mappedValue }, fix: createAppearanceFixer(appearanceProp.value, _mappedValue) }); } } } } }; } }); export default rule;