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 erroneous template string whitespace formatting in Svelte #332

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mcous
Copy link

@mcous mcous commented Dec 1, 2024

Overview

We've been using prettier-plugin-tailwindcss to great effect in various Svelte projects at work, but after updating to v0.6.x, we noticed that Svelte components with template string classnames using newlines starting printing with invalid syntax, even when no class re-ordering was necessary

<!-- input -->
<div
  class={`flex
          h-7.5`}
></div>
<!-- output, invalid syntax -->
<div class={`flex h-7.5`}
></div>}></div>

Previously reported as #303

Cause

I dug into the code, and noticed that inside the Svelte template string formatter, there is this call:

let sorted = sortTemplateLiteral(node, {
  env,
  removeDuplicates: false,
  collapseWhitespace: false,
})

From this call, and from reading some of the tests, it definitely seemed like the intent was to avoid collapsing whitespace in Svelte template literals. Despite this apparent intent, digging further, I found collapseWhitespace option of sortTemplateLiteral was effectively ignored, because:

{ collapseWhitespace: false }

Was getting turned into:

{ collapseWhitespace: { start: false, end: false } }

Before being passed to sortClasses. This is not equivalent according to the internal logic of sortClasses. From there, there appears to be some sort of re-printing bug in prettier-plugin-svelte, which I did not dig into further

Fix

Inside sortTemplateLiteral, I added extra short-circuits to ensure collapseWhitespace: false is preserved. Preserving whitespace in template strings happily avoids whatever re-printing bug(s) exists in the Svelte plugin, and feels fairly "correct" to me because template strings intentionally preserve newlines etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant