Skip to content

Commit e9b249f

Browse files
authored
Fix else block location (#112)
* Fix else block location * fix
1 parent 6f66a88 commit e9b249f

File tree

6 files changed

+645
-5
lines changed

6 files changed

+645
-5
lines changed

src/parser/converts/block.ts

+27-3
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,30 @@ import type { Context } from "../../context"
1313
import { convertChildren } from "./element"
1414
import { getWithLoc, indexOf, lastIndexOf } from "./common"
1515

16+
/** Get start index of block */
17+
function startBlockIndex(code: string, endIndex: number): number {
18+
return lastIndexOf(
19+
code,
20+
(c, index) => {
21+
if (c !== "{") {
22+
return false
23+
}
24+
for (let next = index + 1; next < code.length; next++) {
25+
const nextC = code[next]
26+
if (!nextC.trim()) {
27+
continue
28+
}
29+
return (
30+
code.startsWith("#if", next) ||
31+
code.startsWith(":else", next)
32+
)
33+
}
34+
return false
35+
},
36+
endIndex,
37+
)
38+
}
39+
1640
/** Convert for IfBlock */
1741
export function convertIfBlock(
1842
node: SvAST.IfBlock,
@@ -22,7 +46,7 @@ export function convertIfBlock(
2246
// {#if expr} {:else} {/if}
2347
// {:else if expr} {/if}
2448
const nodeStart = node.elseif
25-
? ctx.code.lastIndexOf("{", node.start)
49+
? startBlockIndex(ctx.code, node.start - 1)
2650
: node.start
2751
const ifBlock: SvelteIfBlock = {
2852
type: "SvelteIfBlock",
@@ -49,7 +73,7 @@ export function convertIfBlock(
4973
return ifBlock
5074
}
5175

52-
const elseStart = ctx.code.lastIndexOf("{", node.else.start)
76+
const elseStart = startBlockIndex(ctx.code, node.else.start - 1)
5377

5478
const elseBlock: SvelteElseBlock = {
5579
type: "SvelteElseBlock",
@@ -149,7 +173,7 @@ export function convertEachBlock(
149173
return eachBlock
150174
}
151175

152-
const elseStart = ctx.code.lastIndexOf("{", node.else.start)
176+
const elseStart = startBlockIndex(ctx.code, node.else.start - 1)
153177

154178
const elseBlock: SvelteElseBlock = {
155179
type: "SvelteElseBlock",

src/parser/converts/common.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,12 @@ export function indexOf(
1717
/** lastIndexOf */
1818
export function lastIndexOf(
1919
str: string,
20-
search: (c: string) => boolean,
20+
search: (c: string, index: number) => boolean,
2121
end: number,
2222
): number {
2323
for (let index = end; index >= 0; index--) {
2424
const c = str[index]
25-
if (search(c)) {
25+
if (search(c, index)) {
2626
return index
2727
}
2828
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{#if expression}{:else if expression}{:else}{/if}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
[
2+
{
3+
"ruleId": "no-undef",
4+
"code": "expression",
5+
"line": 1,
6+
"column": 6
7+
},
8+
{
9+
"ruleId": "no-undef",
10+
"code": "expression",
11+
"line": 1,
12+
"column": 27
13+
}
14+
]

0 commit comments

Comments
 (0)