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

Only re-apply string escaping when necessary #295

Merged
merged 2 commits into from
Jun 17, 2024
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
23 changes: 21 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,18 +467,37 @@ function sortStringLiteral(
})
let didChange = result !== node.value
node.value = result

// A string literal was escaped if:
// - There are backslashes in the raw value; AND
// - The raw value is not the same as the value (excluding the surrounding quotes)
let wasEscaped = false

if (node.extra) {
// JavaScript (StringLiteral)
wasEscaped =
node.extra?.rawValue.includes('\\') &&
node.extra?.raw.slice(1, -1) !== node.value
} else {
// TypeScript (Literal)
wasEscaped =
node.value.includes('\\') && node.raw.slice(1, -1) !== node.value
}

let escaped = wasEscaped ? result.replace(/\\/g, '\\\\') : result

if (node.extra) {
// JavaScript (StringLiteral)
let raw = node.extra.raw
node.extra = {
...node.extra,
rawValue: result,
raw: raw[0] + result.replace(/\\/g, '\\\\') + raw.slice(-1),
raw: raw[0] + escaped + raw.slice(-1),
}
} else {
// TypeScript (Literal)
let raw = node.raw
node.raw = raw[0] + result.replace(/\\/g, '\\\\') + raw.slice(-1)
node.raw = raw[0] + escaped + raw.slice(-1)
}
return didChange
}
Expand Down
11 changes: 3 additions & 8 deletions tests/format.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -94,15 +94,10 @@ let javascript = [
';<div class={`flex ` + ` ` + `text-red-500`} />',
';<div class={`flex ` + ` ` + `text-red-500`} />',
],
[
`;<div class={"before:content-['\\\\2248']"} />`,
`;<div class={"before:content-['\\\\2248']"} />`,
],

[
`;<div class={\`before:content-['\\\\2248']\`} />`,
`;<div class={\`before:content-['\\\\2248']\`} />`,
],
t`;<div class={"before:content-['\\\\2248']"} />`,
t`;<div class={\`before:content-['\\\\2248']\`} />`,
t`;<div class="before:content-['\\\\2248']" />`,

[
`;<div class={'object-cover' + (standalone ? ' aspect-square w-full' : ' min-h-0 grow basis-0')}></div>`,
Expand Down
Loading