Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions src/parser/converts/block.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,30 @@ import type { Context } from "../../context"
import { convertChildren } from "./element"
import { getWithLoc, indexOf, lastIndexOf } from "./common"

/** Get start index of block */
function startBlockIndex(code: string, endIndex: number): number {
return lastIndexOf(
code,
(c, index) => {
if (c !== "{") {
return false
}
for (let next = index + 1; next < code.length; next++) {
const nextC = code[next]
if (!nextC.trim()) {
continue
}
return (
code.startsWith("#if", next) ||
code.startsWith(":else", next)
)
}
return false
},
endIndex,
)
}

/** Convert for IfBlock */
export function convertIfBlock(
node: SvAST.IfBlock,
Expand All @@ -22,7 +46,7 @@ export function convertIfBlock(
// {#if expr} {:else} {/if}
// {:else if expr} {/if}
const nodeStart = node.elseif
? ctx.code.lastIndexOf("{", node.start)
? startBlockIndex(ctx.code, node.start - 1)
: node.start
const ifBlock: SvelteIfBlock = {
type: "SvelteIfBlock",
Expand All @@ -49,7 +73,7 @@ export function convertIfBlock(
return ifBlock
}

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

const elseBlock: SvelteElseBlock = {
type: "SvelteElseBlock",
Expand Down Expand Up @@ -149,7 +173,7 @@ export function convertEachBlock(
return eachBlock
}

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

const elseBlock: SvelteElseBlock = {
type: "SvelteElseBlock",
Expand Down
4 changes: 2 additions & 2 deletions src/parser/converts/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ export function indexOf(
/** lastIndexOf */
export function lastIndexOf(
str: string,
search: (c: string) => boolean,
search: (c: string, index: number) => boolean,
end: number,
): number {
for (let index = end; index >= 0; index--) {
const c = str[index]
if (search(c)) {
if (search(c, index)) {
return index
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/fixtures/parser/ast/if-block01-input.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{#if expression}{:else if expression}{:else}{/if}
14 changes: 14 additions & 0 deletions tests/fixtures/parser/ast/if-block01-no-undef-result.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[
{
"ruleId": "no-undef",
"code": "expression",
"line": 1,
"column": 6
},
{
"ruleId": "no-undef",
"code": "expression",
"line": 1,
"column": 27
}
]
Loading