Skip to content

Commit

Permalink
feat: Print ConstTag (#66)
Browse files Browse the repository at this point in the history
  • Loading branch information
xeho91 committed Jun 30, 2024
1 parent 956acc7 commit 4c6eb02
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 1 deletion.
54 changes: 54 additions & 0 deletions src/node/tag/const.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Related to Svelte AST node {@link ConstTag}.
* @see {@link https://svelte.dev/docs/special-tags#const}
* @module
*/

import { print } from "esrap";

import { define_printer } from "#printer";
import type { ConstTag } from "#types";
import { insert } from "#util";

/**
* Print Svelte AST node {@link ConstTag} as string.
* @see {@link https://svelte.dev/docs/special-tags#const}
*
* @example pattern
* ```svelte
* {@const assignment}
* ```
*/
export const print_const_tag = define_printer((node: ConstTag, _options) => {
const { declaration } = node;

return insert(
"{@",
// NOTE: It removes the semicolon
print(declaration).code.slice(0, -1),
"}",
);
});

if (import.meta.vitest) {
const { describe, it } = import.meta.vitest;
const [{ parse_and_extract_svelte_node }, { DEFAULT_OPTIONS }] = await Promise.all([
import("#test/mod"),
import("#options"),
]);

describe("ConstTag", () => {
it("prints correctly when used as direct child of allowed tags ", ({ expect }) => {
const code = `
{#each boxes as box}
{@const area = box.width * box.height}
{box.width} * {box.height} = {area}
{/each}
`;
const node = parse_and_extract_svelte_node<ConstTag>(code, "ConstTag");
expect(print_const_tag(node, DEFAULT_OPTIONS)).toMatchInlineSnapshot(
`"{@const area = box.width * box.height}"`,
);
});
});
}
3 changes: 2 additions & 1 deletion src/node/tag/mod.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { print_const_tag } from "#node/tag/const";
import { print_expression_tag } from "#node/tag/expression";
import { define_printer } from "#printer";
import type { Tag } from "#types";

export const print_tag = define_printer((node: Tag, options) => {
// biome-ignore format: Prettier
switch (node.type) {
case "ConstTag": return "";
case "ConstTag": return print_const_tag(node, options);
case "DebugTag": return "";
case "ExpressionTag": return print_expression_tag(node, options);
case "HtmlTag": return ""
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
ClassDirective,
Comment,
Component,
ConstTag,
Css,
Directive,
EachBlock,
Expand All @@ -34,6 +35,7 @@ export type {
ClassDirective,
Comment,
Component,
ConstTag,
Css,
Directive,
EachBlock,
Expand Down

0 comments on commit 4c6eb02

Please sign in to comment.