diff --git a/CHANGELOG.md b/CHANGELOG.md index 7009ae83..223f64d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ - (feat) support `requirePragma` and `insertPragma` options ([#350](https://github.com/sveltejs/prettier-plugin-svelte/issues/350)) - (feat) support `` +- (feat) trim whitespace in `class` attributes ([#339](https://github.com/sveltejs/prettier-plugin-svelte/issues/339)) ## 2.9.0 diff --git a/src/print/index.ts b/src/print/index.ts index 603a2864..98f8c3a9 100644 --- a/src/print/index.ts +++ b/src/print/index.ts @@ -180,10 +180,38 @@ export function print(path: FastPath, options: ParserOptions, print: PrintFn): D */ return fill(splitTextToDocs(node)); } else { - const rawText = getUnencodedText(node); - if (path.getParentNode().type === 'Attribute') { + let rawText = getUnencodedText(node); + const parent = path.getParentNode(); + if (parent.type === 'Attribute') { // Direct child of attribute value -> add literallines at end of lines // so that other things don't break in unexpected places + if (parent.name === 'class' && path.getParentNode(1).type === 'Element') { + // Special treatment for class attribute on html elements. Prettier + // will force everything into one line, we deviate from that and preserve lines. + rawText = rawText.replace( + /([^ \t\n])(([ \t]+$)|([ \t]+(\r?\n))|[ \t]+)/g, + // Remove trailing whitespace in lines with non-whitespace characters + // except at the end of the string + ( + match, + characterBeforeWhitespace, + _, + isEndOfString, + isEndOfLine, + endOfLine, + ) => + isEndOfString + ? match + : characterBeforeWhitespace + (isEndOfLine ? endOfLine : ' '), + ); + // Shrink trailing whitespace in case it's followed by a mustache tag + // and remove it completely if it's at the end of the string, but not + // if it's on its own line + rawText = rawText.replace( + /([^ \t\n])[ \t]+$/, + parent.value.indexOf(node) === parent.value.length - 1 ? '$1' : '$1 ', + ); + } return concat(replaceEndOfLineWith(rawText, literalline)); } return rawText; diff --git a/test/formatting/samples/attribute-with-linebreaks/output.html b/test/formatting/samples/attribute-with-linebreaks/output.html index 630db446..2993c8b9 100644 --- a/test/formatting/samples/attribute-with-linebreaks/output.html +++ b/test/formatting/samples/attribute-with-linebreaks/output.html @@ -1,5 +1,5 @@
{ diff --git a/test/formatting/samples/attributes-class/input.html b/test/formatting/samples/attributes-class/input.html new file mode 100644 index 00000000..0f9963d2 --- /dev/null +++ b/test/formatting/samples/attributes-class/input.html @@ -0,0 +1,26 @@ + +
+ Copy +
+ + Copy + +

+ Copy +

+ +

diff --git a/test/formatting/samples/attributes-class/output.html b/test/formatting/samples/attributes-class/output.html new file mode 100644 index 00000000..45698515 --- /dev/null +++ b/test/formatting/samples/attributes-class/output.html @@ -0,0 +1,26 @@ + +

+ Copy +
+ + Copy + +

+ Copy +

+ +