UNPKG

@atlaskit/eslint-plugin-design-system

Version:

The essential plugin for use with the Atlassian Design System.

58 lines (53 loc) 2.82 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.upsertCssMapVariable = upsertCssMapVariable; var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray")); var _contextCompat = require("@atlaskit/eslint-utils/context-compat"); var _getCssMapKey = require("./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. */ function upsertCssMapVariable(context, fixer, paddingToken) { var sourceCode = (0, _contextCompat.getSourceCode)(context); var body = sourceCode.ast.body; var key = (0, _getCssMapKey.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 = (0, _toConsumableArray2.default)(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; }