astx
Version:
super powerful structural search and replace for JavaScript and TypeScript to automate your refactoring
108 lines (81 loc) • 3.18 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = convertToJSXIdentifierName;
function isValidJSXIdentifier(s) {
return /^[_$a-z][-_$a-z0-9]*$/i.test(s);
}
function convertToJSXIdentifierName(node) {
var _node$local, _node$imported, _node$imported2, _node$local2, _node$local3;
switch (node.type) {
case 'ObjectProperty':
if (node.shorthand) return convertToJSXIdentifierName(node.key);
break;
case 'TSPropertySignature':
if (!node.typeAnnotation) return convertToJSXIdentifierName(node.key);
break;
case 'ObjectTypeSpreadProperty':
case 'SpreadElement':
return convertToJSXIdentifierName(node.argument);
case 'ExpressionStatement':
return convertToJSXIdentifierName(node.expression);
case 'Identifier':
case 'JSXIdentifier':
return node.name;
case 'JSXExpressionContainer':
return convertToJSXIdentifierName(node.expression);
case 'JSXAttribute':
if (!node.value) return convertToJSXIdentifierName(node.name);
break;
case 'JSXText':
case 'StringLiteral':
case 'Literal':
if (isValidJSXIdentifier(String(node.value))) return String(node.value);
break;
case 'TemplateLiteral':
if (node.quasis.length === 1 && node.quasis[0].value.cooked && isValidJSXIdentifier(node.quasis[0].value.cooked)) {
return node.quasis[0].value.cooked;
}
break;
case 'TypeAnnotation':
case 'TSTypeAnnotation':
case 'TSRestType':
return convertToJSXIdentifierName(node.typeAnnotation);
case 'GenericTypeAnnotation':
if (node.id.type !== 'Identifier' || node.typeParameters) return;
return node.id.name;
case 'TSTypeReference':
if (node.typeName.type !== 'Identifier' || node.typeParameters) return;
return node.typeName.name;
case 'ImportDefaultSpecifier':
return (_node$local = node.local) === null || _node$local === void 0 ? void 0 : _node$local.name;
case 'ImportSpecifier':
if (((_node$imported = node.imported) === null || _node$imported === void 0 ? void 0 : _node$imported.type) !== 'Identifier' || ((_node$imported2 = node.imported) === null || _node$imported2 === void 0 ? void 0 : _node$imported2.name) !== ((_node$local2 = node.local) === null || _node$local2 === void 0 ? void 0 : _node$local2.name)) return;
return (_node$local3 = node.local) === null || _node$local3 === void 0 ? void 0 : _node$local3.name;
case 'TypeParameter':
case 'TSTypeParameter':
return node.name;
case 'ClassImplements':
case 'InterfaceExtends':
return convertToJSXIdentifierName(node.id);
case 'MixedTypeAnnotation':
return 'mixed';
case 'TSUnknownKeyword':
return 'unknown';
case 'AnyTypeAnnotation':
case 'TSAnyKeyword':
return 'any';
case 'StringTypeAnnotation':
case 'TSStringKeyword':
return 'string';
case 'NumberTypeAnnotation':
case 'TSNumberKeyword':
return 'number';
case 'BooleanTypeAnnotation':
case 'TSBooleanKeyword':
return 'boolean';
case 'TSSymbolKeyword':
return 'symbol';
}
}