UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

51 lines (47 loc) 2.53 kB
import _toConsumableArray from "@babel/runtime/helpers/toConsumableArray"; import { getSourceCode } from '@atlaskit/eslint-utils/context-compat'; import { getCssMapKey } from './get-css-map-key'; var CSSMAP_VARIABLE_NAME = 'iconSpacingStyles'; /** * Inserts or updates `const iconSpacingStyles = cssMap({ spaceXXX: { padding: token('space.XXX') } })` * after the last import statement. * * If `iconSpacingStyles` already exists, adds the new key to the existing cssMap object. * If it doesn't exist, inserts a new declaration after the last import. */ export function upsertCssMapVariable(context, fixer, paddingToken) { var sourceCode = getSourceCode(context); var body = sourceCode.ast.body; var key = getCssMapKey(paddingToken); var keyValuePair = " ".concat(key, ": { paddingBlock: token('").concat(paddingToken, "'), paddingInline: token('").concat(paddingToken, "') }"); // Check if iconSpacingStyles cssMap variable already exists var existingVar = body.find(function (node) { var _node$declarations$, _node$declarations$0$; return node.type === 'VariableDeclaration' && ((_node$declarations$ = node.declarations[0]) === null || _node$declarations$ === void 0 ? void 0 : _node$declarations$.type) === 'VariableDeclarator' && ((_node$declarations$0$ = node.declarations[0].id) === null || _node$declarations$0$ === void 0 ? void 0 : _node$declarations$0$.name) === CSSMAP_VARIABLE_NAME; }); if (existingVar) { // Check if the key already exists in the cssMap var varText = sourceCode.getText(existingVar); if (varText.includes(key + ':') || varText.includes("'".concat(key, "'"))) { return undefined; } // Add the key to the existing cssMap — insert before the closing } var closingBrace = sourceCode.getText(existingVar).lastIndexOf('}'); var existingVarStart = existingVar.range[0]; return fixer.insertTextAfterRange([existingVarStart, existingVarStart + closingBrace], ",\n".concat(keyValuePair, "\n")); } // Find last import to insert after it var lastImport = _toConsumableArray(body).reverse().find(function (n) { return n.type === 'ImportDeclaration'; }); var declaration = "\nconst ".concat(CSSMAP_VARIABLE_NAME, " = cssMap({\n").concat(keyValuePair, ",\n});"); if (lastImport) { return fixer.insertTextAfter(lastImport, declaration); } // No imports — insert at the start of the file var firstNode = body[0]; if (firstNode) { return fixer.insertTextBefore(firstNode, declaration); } return undefined; }