Skip to content

Commit

Permalink
(fix) adjust snipping spans
Browse files Browse the repository at this point in the history
When snipping the tag contents, after replacing a match, we need to adjust the matching spans as the content length now differs. Else "is within other span" might give wrong results.
Fixes sveltejs#255
  • Loading branch information
Simon Holthausen committed Oct 20, 2021
1 parent 21a9a54 commit 1d8c64c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 2 deletions.
20 changes: 18 additions & 2 deletions src/lib/snipTagContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ export function snipScriptAndStyleTagContent(source: string): string {
const indexes: [number, number][] = [];
let match = null;
while ((match = regex.exec(source)) != null) {
indexes.push([match.index, regex.lastIndex]);
if (!source.substr(match.index, 10).startsWith('<!--')) {
indexes.push([match.index, regex.lastIndex]);
}
}
return indexes;
}
Expand All @@ -27,18 +29,32 @@ export function snipScriptAndStyleTagContent(source: string): string {
placeholder: string,
otherSpans: [number, number][],
) {
// Replace valid matches
const regex = getRegexp(tagName);
return _source.replace(regex, (match, attributes, content, index) => {
const newSource = _source.replace(regex, (match, attributes, content, index) => {
if (match.startsWith('<!--') || withinOtherSpan(index)) {
return match;
}
const encodedContent = Buffer.from(content).toString('base64');
return `<${tagName}${attributes} ${snippedTagContentAttribute}="${encodedContent}">${placeholder}</${tagName}>`;
});

// Adjust the spans because the source now has a different content length
adjustSpans(scriptMatchSpans);
adjustSpans(styleMatchSpans);

return newSource;

function withinOtherSpan(idx: number) {
return otherSpans.some((otherSpan) => idx > otherSpan[0] && idx < otherSpan[1]);
}
function adjustSpans(spans: [number, number][]) {
const lengthDiff = _source.length - newSource.length;
spans.forEach((span) => {
span[0] -= lengthDiff;
span[1] -= lengthDiff;
});
}
}

function getRegexp(tagName: string) {
Expand Down
13 changes: 13 additions & 0 deletions test/printer/samples/style-scripts-snipping-spans.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script lang="ts" context="module">
// we need a certain length here
</script>

<script lang="ts">
// we need a certain length here
</script>

<style type="scss">
/* we need a certain length here */
</style>

<!-- this test checks that the matching spans are adjusted after replacing the code, as otherwise it would mess up the snipping -->
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"svelteSortOrder": "options-scripts-styles-markup"
}

0 comments on commit 1d8c64c

Please sign in to comment.