Skip to content

Commit

Permalink
Only re-apply string escaping when necessary (#295)
Browse files Browse the repository at this point in the history
* Simplify test

* Only apply escaping when necessary
  • Loading branch information
thecrypticace authored Jun 17, 2024
1 parent ec92b76 commit a5506a9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
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

0 comments on commit a5506a9

Please sign in to comment.