-
-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathjs-assign.ts
73 lines (65 loc) · 1.65 KB
/
js-assign.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import traverse from '@babel/traverse'
import { Range, Selection } from 'vscode'
// import { log } from '../log'
import type { Handler } from '../types'
const supportedNodeType = [
'TSTypeAliasDeclaration',
'VariableDeclaration',
'AssignmentExpression',
'ClassProperty',
]
/**
* `=` to assignment.
*
* ```js
* ▽
* const a = []
* └──────────┘
*
* class B {
* ▽
* b = 1;
* └────┘
* ▽
* ba = () => {};
* └────────────┘
* }
* ```
*
* @name js-assign
* @category js
*/
export const jsAssignHandler: Handler = {
name: 'js-assign',
handle({ doc, getAst, chars, anchorIndex, withOffset, anchor }) {
if (!chars.includes('='))
return
const asts = getAst('js')
if (!asts.length)
return
if (doc.getText(new Range(anchor, withOffset(anchor, 2))).includes('=>'))
return
for (const ast of getAst('js')) {
const relativeIndex = anchorIndex - ast.start
let result: Selection | undefined
traverse(ast.root, {
enter(path) {
if (path.node.start == null || path.node.end == null)
return
if (relativeIndex > path.node.end || path.node.start > relativeIndex)
return path.skip()
if (!supportedNodeType.includes(path.node.type)) {
// log.debug('[js-assign] Unknown type:', path.node.type)
return
}
result = new Selection(
doc.positionAt(ast.start + path.node.start),
doc.positionAt(ast.start + path.node.end),
)
},
})
if (result)
return result
}
},
}