Skip to content
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

[fix] check for snipped content in JS expressions #306

Merged
merged 2 commits into from
Sep 19, 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
11 changes: 9 additions & 2 deletions src/embed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,14 @@ export function embed(
embeddedOptions.singleQuote = true;
}

let docs = textToDoc(forceIntoExpression(getText(node, options)), embeddedOptions);
let docs = textToDoc(
forceIntoExpression(
// If we have snipped content, it was done wrongly and we need to unsnip it.
// This happens for example for {@html `<script>{foo}</script>`}
getText(node, options, true),
),
embeddedOptions,
);
if (node.forceSingleLine) {
docs = removeLines(docs);
}
Expand All @@ -45,7 +52,7 @@ export function embed(
}
return docs;
} catch (e) {
return getText(node, options);
return getText(node, options, true);
}
}

Expand Down
18 changes: 12 additions & 6 deletions src/lib/getText.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,21 @@
import { ParserOptions } from 'prettier';
import { Node } from '../print/nodes';
import { hasSnippedContent, unsnipContent } from './snipTagContent';

export function getText(node: Node, options: ParserOptions) {
const leadingComments: Node[] = (node as any).leadingComments

return options.originalText.slice(
export function getText(node: Node, options: ParserOptions, unsnip = false) {
const leadingComments: Node[] = (node as any).leadingComments;
const text = options.originalText.slice(
options.locStart(
// if there are comments before the node they are not included
// if there are comments before the node they are not included
// in the `start` of the node itself
leadingComments && leadingComments[0] || node,
(leadingComments && leadingComments[0]) || node,
),
options.locEnd(node),
);

if (!unsnip || !hasSnippedContent(text)) {
return text;
}

return unsnipContent(text);
}
22 changes: 22 additions & 0 deletions test/printer/samples/no-tag-snippings.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<svelte:head>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "etc..."
}
</script>
{@html `<style>${getCssText()}</style>`}
</svelte:head>

<pre class="p-2">
{`<div>
<span>Hello</span>
<span>World</span>
</div>

<style lang="postcss">
span {
@apply text-red-500;
}
</style>`}
</pre>