Skip to content

Support for svelte v3.46 syntax #128

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 12, 2022
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
25 changes: 24 additions & 1 deletion src/ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ export type SvelteNode =
| SvelteLiteral
| SvelteMustacheTag
| SvelteDebugTag
| SvelteConstTag
| SvelteIfBlock
| SvelteElseBlock
| SvelteEachBlock
Expand Down Expand Up @@ -215,6 +216,7 @@ type Child =
| SvelteText
| SvelteMustacheTag
| SvelteDebugTag
| SvelteConstTag
| SvelteIfBlockAlone
| SvelteEachBlock
| SvelteAwaitBlock
Expand All @@ -241,7 +243,7 @@ export interface SvelteText extends BaseNode {
export interface SvelteLiteral extends BaseNode {
type: "SvelteLiteral"
value: string
parent: SvelteAttribute
parent: SvelteAttribute | SvelteStyleDirective
}

/** Node of mustache tag. e.g. `{...}`, `{@html ...}`. Like JSXExpressionContainer */
Expand Down Expand Up @@ -286,6 +288,22 @@ export interface SvelteDebugTag extends BaseNode {
| SvelteKeyBlock
| SvelteAttribute
}
/** Node of const tag. e.g. `{@const}` */
export interface SvelteConstTag extends BaseNode {
type: "SvelteConstTag"
declaration: ESTree.VariableDeclarator
parent:
| SvelteProgram
| SvelteElement
| SvelteIfBlock
| SvelteElseBlockAlone
| SvelteEachBlock
| SvelteAwaitPendingBlock
| SvelteAwaitThenBlock
| SvelteAwaitCatchBlock
| SvelteKeyBlock
| SvelteAttribute
}
/** Node of if block. e.g. `{#if}` */
export type SvelteIfBlock = SvelteIfBlockAlone | SvelteIfBlockElseIf
interface BaseSvelteIfBlock extends BaseNode {
Expand Down Expand Up @@ -511,6 +529,7 @@ export type SvelteDirective =
| SvelteAnimationDirective
| SvelteBindingDirective
| SvelteClassDirective
| SvelteStyleDirective
| SvelteEventHandlerDirective
| SvelteLetDirective
| SvelteRefDirective
Expand Down Expand Up @@ -544,6 +563,10 @@ export interface SvelteClassDirective extends BaseSvelteDirective {
kind: "Class"
expression: null | ESTree.Expression
}
export interface SvelteStyleDirective extends BaseSvelteDirective {
kind: "Style"
expression: null | ESTree.Expression | SvelteLiteral
}
export interface SvelteEventHandlerDirective extends BaseSvelteDirective {
kind: "EventHandler"
expression: null | ESTree.Expression
Expand Down
38 changes: 38 additions & 0 deletions src/context/script-let.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,44 @@ export class ScriptLetContext {
return callbacks
}

public addVariableDeclarator(
expression: ESTree.AssignmentExpression,
parent: SvelteNode,
...callbacks: ScriptLetCallback<ESTree.VariableDeclarator>[]
): ScriptLetCallback<ESTree.VariableDeclarator>[] {
const range = getNodeRange(expression)
const part = this.ctx.code.slice(...range)
this.appendScript(
`const ${part};`,
range[0] - 6,
(st, tokens, _comments, result) => {
const decl = st as ESTree.VariableDeclaration
const node = decl.declarations[0]
// Process for nodes
for (const callback of callbacks) {
callback(node, result)
}
;(node as any).parent = parent

const scope = result.getScope(decl)
for (const variable of scope.variables) {
for (const def of variable.defs) {
if (def.parent === decl) {
;(def as any).parent = parent
}
}
}

tokens.shift() // const
tokens.pop() // ;

// Disconnect the tree structure.
decl.declarations = []
},
)
return callbacks
}

public nestIfBlock(
expression: ESTree.Expression,
ifBlock: SvelteIfBlock,
Expand Down
80 changes: 79 additions & 1 deletion src/parser/converts/attr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,14 @@ import type {
SvelteTransitionDirective,
SvelteStartTag,
SvelteName,
SvelteStyleDirective,
} from "../../ast"
import type ESTree from "estree"
import type { Context } from "../../context"
import type * as SvAST from "../svelte-ast-types"
import { getWithLoc, indexOf } from "./common"
import { convertMustacheTag } from "./mustache"
import { convertTextToLiteral } from "./text"
import { convertTemplateLiteralToLiteral, convertTextToLiteral } from "./text"
import { ParseError } from "../../errors"
import type { ScriptLetCallback } from "../../context/script-let"

Expand Down Expand Up @@ -54,6 +55,10 @@ export function* convertAttributes(
yield convertClassDirective(attr, parent, ctx)
continue
}
if (attr.type === "Style") {
yield convertStyleDirective(attr, parent, ctx)
continue
}
if (attr.type === "Transition") {
yield convertTransitionDirective(attr, parent, ctx)
continue
Expand Down Expand Up @@ -284,6 +289,79 @@ function convertClassDirective(
return directive
}

/** Convert for Style Directive */
function convertStyleDirective(
node: SvAST.DirectiveForExpression,
parent: SvelteDirective["parent"],
ctx: Context,
): SvelteStyleDirective {
const directive: SvelteStyleDirective = {
type: "SvelteDirective",
kind: "Style",
key: null as any,
expression: null,
parent,
...ctx.getConvertLocation(node),
}
if (processStyleDirectiveValue(node, ctx)) {
processDirective(node, directive, ctx, (expression) => {
directive.expression = convertTemplateLiteralToLiteral(
expression,
directive,
ctx,
)
return []
})
} else {
processDirective(node, directive, ctx, (expression) => {
return ctx.scriptLet.addExpression(expression, directive)
})
}

return directive
}

/** Process plain value */
function processStyleDirectiveValue(
node: SvAST.DirectiveForExpression,
ctx: Context,
): node is SvAST.DirectiveForExpression & {
expression: ESTree.TemplateLiteral
} {
const { expression } = node
if (
!expression ||
expression.type !== "TemplateLiteral" ||
expression.expressions.length !== 0
) {
return false
}
const quasi = expression.quasis[0]
if (quasi.value.cooked != null) {
return false
}
const eqIndex = ctx.code.indexOf("=", node.start)
if (eqIndex < 0 || eqIndex >= node.end) {
return false
}
const valueIndex = ctx.code.indexOf(quasi.value.raw, eqIndex + 1)
if (valueIndex < 0 || valueIndex >= node.end) {
return false
}
const maybeEnd = valueIndex + quasi.value.raw.length
const maybeOpenQuote = ctx.code.slice(eqIndex + 1, valueIndex).trimStart()
if (maybeOpenQuote && maybeOpenQuote !== '"' && maybeOpenQuote !== "'") {
return false
}
const maybeCloseQuote = ctx.code.slice(maybeEnd, node.end).trimEnd()
if (maybeCloseQuote !== maybeOpenQuote) {
return false
}
getWithLoc(expression).start = valueIndex
getWithLoc(expression).end = maybeEnd
return true
}

/** Convert for Transition Directive */
function convertTransitionDirective(
node: SvAST.TransitionDirective,
Expand Down
30 changes: 30 additions & 0 deletions src/parser/converts/const.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import type { SvelteConstTag } from "../../ast"
import type { Context } from "../../context"
import type * as SvAST from "../svelte-ast-types"

/** Convert for ConstTag */
export function convertConstTag(
node: SvAST.ConstTag,
parent: SvelteConstTag["parent"],
ctx: Context,
): SvelteConstTag {
const mustache: SvelteConstTag = {
type: "SvelteConstTag",
declaration: null as any,
parent,
...ctx.getConvertLocation(node),
}
ctx.scriptLet.addVariableDeclarator(
node.expression,
mustache,
(declaration) => {
mustache.declaration = declaration
},
)
const atConstStart = ctx.code.indexOf("@const", mustache.range[0])
ctx.addToken("MustacheKeyword", {
start: atConstStart,
end: atConstStart + 6,
})
return mustache
}
25 changes: 22 additions & 3 deletions src/parser/converts/element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
SvelteAwaitPendingBlock,
SvelteAwaitThenBlock,
SvelteComponentElement,
SvelteConstTag,
SvelteDebugTag,
SvelteEachBlock,
SvelteElement,
Expand Down Expand Up @@ -41,6 +42,7 @@ import {
} from "./mustache"
import { convertText } from "./text"
import { convertAttributes } from "./attr"
import { convertConstTag } from "./const"

/* eslint-disable complexity -- X */
/** Convert for Fragment or Element or ... */
Expand All @@ -63,6 +65,7 @@ export function* convertChildren(
| SvelteElement
| SvelteMustacheTag
| SvelteDebugTag
| SvelteConstTag
| SvelteIfBlockAlone
| SvelteEachBlock
| SvelteAwaitBlock
Expand Down Expand Up @@ -150,11 +153,27 @@ export function* convertChildren(
yield convertDebugTag(child, parent, ctx)
continue
}
if (child.type === "ConstTag") {
yield convertConstTag(child, parent, ctx)
continue
}

throw new Error(`Unknown type:${(child as any).type}`)
}
}

/** Check if children needs a scope. */
function needScopeByChildren(fragment: {
children: SvAST.TemplateNode[]
}): boolean {
for (const child of fragment.children) {
if (child.type === "ConstTag") {
return true
}
}
return false
}

/** Convert for HTML Comment */
function convertComment(
node: SvAST.Comment,
Expand Down Expand Up @@ -210,7 +229,7 @@ function convertHTMLElement(
...convertAttributes(node.attributes, element.startTag, ctx),
)
const lets = ctx.letDirCollections.extract()
if (lets.isEmpty()) {
if (lets.isEmpty() && !needScopeByChildren(node)) {
element.children.push(...convertChildren(node, element, ctx))
} else {
ctx.scriptLet.nestBlock(
Expand Down Expand Up @@ -297,7 +316,7 @@ function convertSpecialElement(
...convertAttributes(node.attributes, element.startTag, ctx),
)
const lets = ctx.letDirCollections.extract()
if (lets.isEmpty()) {
if (lets.isEmpty() && !needScopeByChildren(node)) {
element.children.push(...convertChildren(node, element, ctx))
} else {
ctx.scriptLet.nestBlock(
Expand Down Expand Up @@ -406,7 +425,7 @@ function convertComponentElement(
...convertAttributes(node.attributes, element.startTag, ctx),
)
const lets = ctx.letDirCollections.extract()
if (lets.isEmpty()) {
if (lets.isEmpty() && !needScopeByChildren(node)) {
element.children.push(...convertChildren(node, element, ctx))
} else {
ctx.scriptLet.nestBlock(
Expand Down
Loading