Skip to content

Commit 389e9a8

Browse files
authored
fix: handling of indent inside embedded language (#718)
1 parent 952372d commit 389e9a8

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

src/generation/generate.rs

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3058,9 +3058,22 @@ fn maybe_gen_tagged_tpl_with_external_formatter<'a>(node: &TaggedTpl<'a>, contex
30583058
items.push_signal(Signal::NewLine);
30593059
items.push_signal(Signal::StartIndent);
30603060
let mut index = 0;
3061+
let mut current_indent_level = 0;
3062+
let use_tabs = context.config.use_tabs;
3063+
let indent_width = if use_tabs { 1 } else { context.config.indent_width };
3064+
let indent_char = if use_tabs { '\t' } else { ' ' };
30613065
for line in formatted_tpl.lines() {
3062-
let mut pos = 0;
3063-
let mut parts = line.split(placeholder_text).enumerate().peekable();
3066+
// count indent characters
3067+
let mut pos = line.chars().take_while(|ch| *ch == indent_char).count();
3068+
let indent_level = if indent_width == 0 { 0 } else { pos / indent_width as usize };
3069+
if indent_level > current_indent_level {
3070+
items.push_signal(Signal::StartIndent);
3071+
current_indent_level = indent_level;
3072+
} else if indent_level < current_indent_level {
3073+
items.push_signal(Signal::FinishIndent);
3074+
current_indent_level = indent_level;
3075+
}
3076+
let mut parts = line[pos..].split(placeholder_text).enumerate().peekable();
30643077
while let Some((i, part)) = parts.next() {
30653078
let end = pos + part.len();
30663079
if i > 0 {
@@ -3080,6 +3093,10 @@ fn maybe_gen_tagged_tpl_with_external_formatter<'a>(node: &TaggedTpl<'a>, contex
30803093
}
30813094
items.push_signal(Signal::NewLine);
30823095
}
3096+
while current_indent_level > 0 {
3097+
items.push_signal(Signal::FinishIndent);
3098+
current_indent_level -= 1;
3099+
}
30833100
items.push_signal(Signal::FinishIndent);
30843101
items.push_sc(sc!("`"));
30853102
Some(items)

tests/specs/external_formatter/html.txt

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,3 +19,33 @@ htmlString = html`
1919
<footer>${footer}</footer>
2020
</body>
2121
`;
22+
23+
== should format nested html templates with correct indent level ==
24+
export const Layout = (props: Props) => html`
25+
<html>
26+
<body>
27+
${props.title.endsWith("example")
28+
? html`
29+
<a href="/">Reactive Mastro examples</a>
30+
<h1>${props.title}</h1>
31+
`
32+
: ""}
33+
<main>${props.children}</main>
34+
</body>
35+
</html>
36+
`;
37+
[expect]
38+
export const Layout = (props: Props) =>
39+
html`
40+
<html>
41+
<body>
42+
${props.title.endsWith("example")
43+
? html`
44+
<a href="/">Reactive Mastro examples</a>
45+
<h1>${props.title}</h1>
46+
`
47+
: ""}
48+
<main>${props.children}</main>
49+
</body>
50+
</html>
51+
`;

0 commit comments

Comments
 (0)