Skip to content

Commit 4c23ba4

Browse files
authored
[fix] check for snipped content in JS expressions (#306)
Fixes #290
1 parent ccccee3 commit 4c23ba4

File tree

3 files changed

+43
-8
lines changed

3 files changed

+43
-8
lines changed

src/embed.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,14 @@ export function embed(
3636
embeddedOptions.singleQuote = true;
3737
}
3838

39-
let docs = textToDoc(forceIntoExpression(getText(node, options)), embeddedOptions);
39+
let docs = textToDoc(
40+
forceIntoExpression(
41+
// If we have snipped content, it was done wrongly and we need to unsnip it.
42+
// This happens for example for {@html `<script>{foo}</script>`}
43+
getText(node, options, true),
44+
),
45+
embeddedOptions,
46+
);
4047
if (node.forceSingleLine) {
4148
docs = removeLines(docs);
4249
}
@@ -45,7 +52,7 @@ export function embed(
4552
}
4653
return docs;
4754
} catch (e) {
48-
return getText(node, options);
55+
return getText(node, options, true);
4956
}
5057
}
5158

src/lib/getText.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,21 @@
11
import { ParserOptions } from 'prettier';
22
import { Node } from '../print/nodes';
3+
import { hasSnippedContent, unsnipContent } from './snipTagContent';
34

4-
export function getText(node: Node, options: ParserOptions) {
5-
const leadingComments: Node[] = (node as any).leadingComments
6-
7-
return options.originalText.slice(
5+
export function getText(node: Node, options: ParserOptions, unsnip = false) {
6+
const leadingComments: Node[] = (node as any).leadingComments;
7+
const text = options.originalText.slice(
88
options.locStart(
9-
// if there are comments before the node they are not included
9+
// if there are comments before the node they are not included
1010
// in the `start` of the node itself
11-
leadingComments && leadingComments[0] || node,
11+
(leadingComments && leadingComments[0]) || node,
1212
),
1313
options.locEnd(node),
1414
);
15+
16+
if (!unsnip || !hasSnippedContent(text)) {
17+
return text;
18+
}
19+
20+
return unsnipContent(text);
1521
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<svelte:head>
2+
<script type="application/ld+json">
3+
{
4+
"@context": "https://schema.org",
5+
"@type": "etc..."
6+
}
7+
</script>
8+
{@html `<style>${getCssText()}</style>`}
9+
</svelte:head>
10+
11+
<pre class="p-2">
12+
{`<div>
13+
<span>Hello</span>
14+
<span>World</span>
15+
</div>
16+
17+
<style lang="postcss">
18+
span {
19+
@apply text-red-500;
20+
}
21+
</style>`}
22+
</pre>

0 commit comments

Comments
 (0)