|
| 1 | +import { GetConfig } from '../types' |
| 2 | +import { findChildContainingExactPosition } from '../utils' |
| 3 | + |
| 4 | +export default ( |
| 5 | + fileName: string, |
| 6 | + refactorName: string, |
| 7 | + actionName: string, |
| 8 | + languageService: ts.LanguageService, |
| 9 | + c: GetConfig, |
| 10 | + prior: ts.RefactorEditInfo, |
| 11 | +): ts.RefactorEditInfo | undefined => { |
| 12 | + const extractToInterface = actionName === 'Extract to interface' |
| 13 | + if (c('codeActions.extractTypeInferName') && (actionName === 'Extract to type alias' || extractToInterface)) { |
| 14 | + const changeFirstEdit = (oldText: string, newTypeName: string) => { |
| 15 | + const startMarker = extractToInterface ? 'interface ' : 'type ' |
| 16 | + const endMarker = extractToInterface ? ' {' : ' = ' |
| 17 | + return oldText.slice(0, oldText.indexOf(startMarker) + startMarker.length) + newTypeName + oldText.slice(oldText.indexOf(endMarker)) |
| 18 | + } |
| 19 | + |
| 20 | + const fileEdit = prior.edits[0]! |
| 21 | + const { textChanges } = fileEdit |
| 22 | + |
| 23 | + const sourceFile = languageService.getProgram()!.getSourceFile(fileName)! |
| 24 | + let node = findChildContainingExactPosition(sourceFile, textChanges[1]!.span.start - 1) |
| 25 | + if (!node) return |
| 26 | + if (ts.isAsExpression(node) || ts.isSatisfiesExpression(node)) node = node.parent |
| 27 | + if (ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isPropertyAssignment(node) || ts.isPropertySignature(node)) { |
| 28 | + let isWithinType = ts.isPropertySignature(node) |
| 29 | + if (ts.isIdentifier(node.name)) { |
| 30 | + const identifierName = node.name.text |
| 31 | + if (!identifierName) return |
| 32 | + let typeName = identifierName[0]!.toUpperCase() + identifierName.slice(1) |
| 33 | + if (!isWithinType) typeName += 'Type' |
| 34 | + const newFileEdit: ts.FileTextChanges = { |
| 35 | + fileName, |
| 36 | + textChanges: textChanges.map((textChange, i) => { |
| 37 | + if (i === 0) return { ...textChange, newText: changeFirstEdit(textChange.newText, typeName) } |
| 38 | + /* if (i === 1) */ return { ...textChange, newText: typeName } |
| 39 | + }), |
| 40 | + } |
| 41 | + return { |
| 42 | + edits: [newFileEdit], |
| 43 | + } |
| 44 | + } |
| 45 | + } |
| 46 | + return prior |
| 47 | + } |
| 48 | + return |
| 49 | +} |
0 commit comments