Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
ota-meshi committed Jul 18, 2024
1 parent 48cf781 commit 91e4961
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 14 deletions.
37 changes: 24 additions & 13 deletions src/parser/converts/attr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -150,14 +150,10 @@ function convertAttribute(
ctx.addToken("HTMLIdentifier", keyRange);
return attribute;
}
const value = Array.isArray(node.value) ? node.value : [node.value];
const value = node.value;
const shorthand =
value.some((v) => v.type === "AttributeShorthand") ||
// for Svelte v5
(value.length === 1 &&
value[0].type === "ExpressionTag" &&
ctx.code[node.start] === "{" &&
ctx.code[node.end - 1] === "}");
isAttributeShorthandForSvelteV4(value) ||
isAttributeShorthandForSvelteV5(value);
if (shorthand) {
const key: ESTree.Identifier = {
...attribute.key,
Expand Down Expand Up @@ -187,14 +183,29 @@ function convertAttribute(
// Not required for shorthands. Therefore, register the token here.
ctx.addToken("HTMLIdentifier", keyRange);

processAttributeValue(
value as Exclude<(typeof value)[number], SvAST.AttributeShorthand>[],
attribute,
parent,
ctx,
);
processAttributeValue(value, attribute, parent, ctx);

return attribute;

function isAttributeShorthandForSvelteV4(
value: Exclude<(SvAST.Attribute | Compiler.Attribute)["value"], boolean>,
): value is [SvAST.AttributeShorthand] {
return Array.isArray(value) && value[0]?.type === "AttributeShorthand";
}

function isAttributeShorthandForSvelteV5(
value: Exclude<
(SvAST.Attribute | Compiler.Attribute)["value"],
boolean | [SvAST.AttributeShorthand]
>,
): boolean {
return (
!Array.isArray(value) &&
value.type === "ExpressionTag" &&
ctx.code[node.start] === "{" &&
ctx.code[node.end - 1] === "}"
);
}
}

/** Common process attribute value */
Expand Down
2 changes: 1 addition & 1 deletion src/parser/svelte-ast-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export interface Comment extends BaseNode {
export interface Attribute extends BaseNode {
type: "Attribute";
name: string;
value: (Text | AttributeShorthand | MustacheTag)[] | true;
value: (Text | MustacheTag)[] | [AttributeShorthand] | true;
}
export interface Spread extends BaseNode {
type: "Spread";
Expand Down

0 comments on commit 91e4961

Please sign in to comment.