Skip to content
Open
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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Fixed

- Restore class sorting in Astro templates when using `prettier-plugin-astro` v1 ([#473](https://github.com/tailwindlabs/prettier-plugin-tailwindcss/pull/473))
- Preserve attached class fragments in Svelte string concatenations.

## [0.8.1] - 2026-07-15

Expand Down
5 changes: 1 addition & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,7 @@ import { cacheForDirs } from './utils.js'

let prettierConfigCache = expiringMap<string, string | null>(10_000)

async function resolvePrettierConfigDir(
filePath: string,
inputDir: string,
): Promise<string> {
async function resolvePrettierConfigDir(filePath: string, inputDir: string): Promise<string> {
// Check cache for this directory
let cached = prettierConfigCache.get(inputDir)
if (cached !== undefined) {
Expand Down
58 changes: 46 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,10 +407,14 @@ function sortStringLiteral(
{
env,
removeDuplicates,
ignoreFirst,
ignoreLast,
collapseWhitespace = { start: true, end: true },
}: {
env: TransformerEnv
removeDuplicates?: false
ignoreFirst?: boolean
ignoreLast?: boolean
collapseWhitespace?: false | { start: boolean; end: boolean }
},
) {
Expand All @@ -428,15 +432,27 @@ function sortStringLiteral(
let quote = raw[0]
let rawContent = raw.slice(1, -1)

let sortedRaw = sortClasses(rawContent, { env, removeDuplicates, collapseWhitespace })
let sortedRaw = sortClasses(rawContent, {
env,
removeDuplicates,
collapseWhitespace,
ignoreFirst: ignoreFirst && !/^[\t\r\f\n ]/.test(rawContent),
ignoreLast: ignoreLast && !/[\t\r\f\n ]$/.test(rawContent),
})
if (sortedRaw === rawContent) return false

// Reuse the raw sort when raw and cooked are byte-identical (no escapes).
// Avoids a second `getClassOrder` pass, the dominant cost in `sortClasses`.
let sortedCooked =
rawContent === node.value
? sortedRaw
: sortClasses(node.value, { env, removeDuplicates, collapseWhitespace })
: sortClasses(node.value, {
env,
removeDuplicates,
collapseWhitespace,
ignoreFirst: ignoreFirst && !/^[\t\r\f\n ]/.test(node.value),
ignoreLast: ignoreLast && !/[\t\r\f\n ]$/.test(node.value),
})
node.value = sortedCooked

let newRaw = quote + sortedRaw + quote
Expand All @@ -460,10 +476,14 @@ function sortTemplateLiteral(
{
env,
removeDuplicates,
ignoreFirst,
ignoreLast,
collapseWhitespace = { start: true, end: true },
}: {
env: TransformerEnv
removeDuplicates?: false
ignoreFirst?: boolean
ignoreLast?: boolean
collapseWhitespace?: false | { start: boolean; end: boolean }
},
) {
Expand All @@ -478,12 +498,9 @@ function sortTemplateLiteral(
quasi.value.raw = sortClasses(quasi.value.raw, {
env,
removeDuplicates,
// Is not the first "item" and does not start with a space
ignoreFirst: i > 0 && !/^\s/.test(quasi.value.raw),

// Is between two expressions
// And does not end with a space
ignoreLast: i < node.expressions.length && !/\s$/.test(quasi.value.raw),
// Interpolations and enclosing concatenations can attach to either edge.
ignoreFirst: (ignoreFirst || i > 0) && !/^\s/.test(quasi.value.raw),
ignoreLast: (ignoreLast || i < node.expressions.length) && !/\s$/.test(quasi.value.raw),

collapseWhitespace: collapseWhitespace && {
start: collapseWhitespace && collapseWhitespace.start && i === 0,
Expand All @@ -495,8 +512,9 @@ function sortTemplateLiteral(
? quasi.value.raw
: sortClasses(quasi.value.cooked, {
env,
ignoreFirst: i > 0 && !/^\s/.test(quasi.value.cooked),
ignoreLast: i < node.expressions.length && !/\s$/.test(quasi.value.cooked),
ignoreFirst: (ignoreFirst || i > 0) && !/^\s/.test(quasi.value.cooked),
ignoreLast:
(ignoreLast || i < node.expressions.length) && !/\s$/.test(quasi.value.cooked),
removeDuplicates,
collapseWhitespace: collapseWhitespace && {
start: collapseWhitespace && collapseWhitespace.start && i === 0,
Expand Down Expand Up @@ -942,6 +960,20 @@ function transformPug(ast: any, env: TransformerEnv) {
function transformSvelte(ast: any, env: TransformerEnv) {
let { matcher, changes } = env

function concatenationEdges(path: Path<{ type: string; operator?: string }, unknown>) {
let ignoreFirst = false
let ignoreLast = false

// An outer concatenation can attach through an intervening conditional.
for (let entry of path) {
if (entry.parent?.type !== 'BinaryExpression' || entry.parent.operator !== '+') continue
ignoreFirst ||= entry.key === 'right'
ignoreLast ||= entry.key === 'left'
}

return { ignoreFirst, ignoreLast }
}

for (let attr of ast.attributes ?? []) {
if (!matcher.hasStaticAttr(attr.name) || attr.type !== 'Attribute') {
continue
Expand Down Expand Up @@ -971,11 +1003,12 @@ function transformSvelte(ast: any, env: TransformerEnv) {
})
} else if (value.type === 'MustacheTag' || value.type === 'ExpressionTag') {
visit(value.expression, {
Literal(node) {
Literal(node, path) {
if (isStringLiteral(node)) {
let before = node.raw
let sorted = sortStringLiteral(node, {
env,
...concatenationEdges(path),
removeDuplicates: false,
collapseWhitespace: false,
})
Expand All @@ -990,10 +1023,11 @@ function transformSvelte(ast: any, env: TransformerEnv) {
}
}
},
TemplateLiteral(node) {
TemplateLiteral(node, path) {
let before = node.quasis.map((quasi: any) => quasi.value.raw)
let sorted = sortTemplateLiteral(node, {
env,
...concatenationEdges(path),
removeDuplicates: false,
collapseWhitespace: false,
})
Expand Down
5 changes: 3 additions & 2 deletions tests/plugins.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,9 +406,10 @@ import Custom from '../components/Custom.astro'
t`<div class="{someVar} ${yes}" />`,
t`<div class="${yes} {someVar} ${yes}" />`,
t`<div class={'${yes}'} />`,
t`<div class={'${yes}' + '${yes}'} />`,
// Adjacent operands share a partial token, so their boundary tokens stay attached.
t`<div class={'${no}' + '${no}'} />`,
t`<div class={\`${yes}\`} />`,
t`<div class={\`${yes} \${'${yes}' + \`${yes}\`} ${yes}\`} />`,
t`<div class={\`${yes} \${'${no}' + \`${no}\`} ${yes}\`} />`,
t`<div class={\`${no}\${someVar}${no}\`} />`,
[
`<Component class={cn('bottom-0 sticky transition-all justify-end', { 'bg-red-500': active })} />`,
Expand Down
18 changes: 18 additions & 0 deletions tests/svelte-concatenation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { test } from 'vitest'
import { format } from './utils.js'

test('preserves attached Svelte class fragments while sorting complete tokens', async ({
expect,
}) => {
const result = await format(
"<div class={'inline-' + (active ? 'underline flex block ' : `underline flex block `) + 'tail'}></div>",
{
parser: 'svelte',
plugins: ['prettier-plugin-svelte'],
},
)

expect(result).toBe(
"<div class={'inline-' + (active ? 'underline block flex ' : `underline block flex `) + 'tail'}></div>",
)
})