|
1 | 1 | import { CodeAction } from '../getCodeActions' |
2 | 2 | import escapeStringRegexp from 'escape-string-regexp' |
3 | | - |
4 | | -const nodeToSpan = (node: ts.Node): ts.TextSpan => { |
5 | | - const start = node.pos + (node.getLeadingTriviaWidth() ?? 0) |
6 | | - return { start, length: node.end - start } |
7 | | -} |
| 3 | +import { getChangesTracker } from '../../utils' |
8 | 4 |
|
9 | 5 | export default { |
10 | 6 | id: 'changeStringReplaceToRegex', |
11 | 7 | name: 'Change to Regex', |
12 | 8 | kind: 'refactor.rewrite.stringToRegex', |
13 | | - tryToApply(sourceFile, position, _range, node) { |
| 9 | + tryToApply(sourceFile, position, _range, node, formatOptions) { |
14 | 10 | if (!node || !position) return |
15 | 11 | // requires full explicit object selection (be aware of comma) to not be annoying with suggestion |
16 | 12 | if (!ts.isStringLiteral(node)) return |
17 | 13 | if (!ts.isCallExpression(node.parent) || node.parent.arguments[0] !== node) return |
18 | 14 | if (!ts.isPropertyAccessExpression(node.parent.expression)) return |
19 | 15 | if (node.parent.expression.name.text !== 'replace') return |
20 | | - // though it does to much escaping and ideally should be simplified |
21 | | - const edits: ts.TextChange[] = [ |
22 | | - { |
23 | | - span: nodeToSpan(node), |
24 | | - newText: `/${escapeStringRegexp(node.text).replaceAll('\n', '\\n').replaceAll('\t', '\\t').replaceAll('\r', '\\r')}/`, |
25 | | - }, |
26 | | - ] |
| 16 | + if (!formatOptions) return true |
| 17 | + const changesTracker = getChangesTracker({}) |
| 18 | + const { factory } = ts |
| 19 | + const replaceNode = factory.createRegularExpressionLiteral( |
| 20 | + // though it does to much escaping and ideally should be simplified |
| 21 | + `/${escapeStringRegexp(node.text).replaceAll('\n', '\\n').replaceAll('\t', '\\t').replaceAll('\r', '\\r')}/`, |
| 22 | + ) |
| 23 | + |
| 24 | + changesTracker.replaceNode(sourceFile, node, replaceNode) |
27 | 25 | return { |
28 | 26 | edits: [ |
29 | 27 | { |
30 | 28 | fileName: sourceFile.fileName, |
31 | | - textChanges: edits, |
| 29 | + textChanges: changesTracker.getChanges()[0]!.textChanges, |
32 | 30 | }, |
33 | 31 | ], |
34 | 32 | } |
|
0 commit comments