@@ -15,6 +15,12 @@ import {
15
15
* @returns An extractor that will exctract `else if` branches
16
16
*/
17
17
export function elseIfExtractor ( ) : SelectionExtractor {
18
+ /**
19
+ * This extractor pulls out `if (foo) {}` from `if (foo) {} else {}`, ie it
20
+ * excludes any child `else` statement if it exists. It will be used as the
21
+ * content range, but the removal range will want to include a leading or
22
+ * trailing `else` keyword if one exists.
23
+ */
18
24
const contentRangeExtractor = childRangeSelector ( [ "else_clause" ] , [ ] , {
19
25
includeUnnamedChildren : true ,
20
26
} ) ;
@@ -24,12 +30,20 @@ export function elseIfExtractor(): SelectionExtractor {
24
30
25
31
const parent = node . parent ;
26
32
if ( parent ?. type !== "else_clause" ) {
33
+ // We have no leading `else` clause; ie we are a standalone `if`
34
+ // statement. We may still have our own `else` child, but we are not
35
+ // ourselves a branch of a bigger `if` statement.
27
36
const alternative = node . childForFieldName ( "alternative" ) ;
28
37
29
38
if ( alternative == null ) {
39
+ // If we have no nested else clause, and are not part of an else clause
40
+ // ourself, then we don't need to remove any leading / trailing `else`
41
+ // keyword
30
42
return contentRange ;
31
43
}
32
44
45
+ // Otherwise, we have no leading `else`, but we do have our own nested
46
+ // `else` clause, so we want to remove the leading `else` keyword
33
47
const { selection } = contentRange ;
34
48
return {
35
49
selection,
@@ -42,6 +56,8 @@ export function elseIfExtractor(): SelectionExtractor {
42
56
} ;
43
57
}
44
58
59
+ // If we get here, we are part of a bigger `if` statement; extend our
60
+ // removal range past our leading `else` keyword.
45
61
const { selection } = contentRange ;
46
62
return {
47
63
selection,
@@ -67,6 +83,9 @@ export function elseExtractor(ifNodeType: string): SelectionExtractor {
67
83
const nestedElseIfExtractor = elseIfExtractor ( ) ;
68
84
69
85
return function ( editor : TextEditor , node : SyntaxNode ) : SelectionWithContext {
86
+ // If we are an `else if` statement, then we just run `elseIfExtractor` on
87
+ // our nested `if` node. Otherwise we are a simple `else` branch and don't
88
+ // need to do anything fancy.
70
89
return node . namedChild ( 0 ) ! . type === ifNodeType
71
90
? nestedElseIfExtractor ( editor , node . namedChild ( 0 ) ! )
72
91
: simpleSelectionExtractor ( editor , node ) ;
0 commit comments