Skip to content

Commit

Permalink
Clean up code
Browse files Browse the repository at this point in the history
  • Loading branch information
ai committed Sep 3, 2022
1 parent 9c6e25e commit 505b5ff
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 21 deletions.
24 changes: 9 additions & 15 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,22 +37,16 @@ function variable (variables, node, str, name, opts, result) {
return str
}

function transformBackslashSequences (value) {
if (typeof value !== 'string') return value
const UNICODE_8_CODE = /(?<=[^\\]|^)\\U([0-9abcdefABCDEF]{8})/g
const UNICODE_4_CODE = /(?<=[^\\]|^)\\u([0-9abcdefABCDEF]{4})/g

return (
value
// Unicode 8-digit code support (\Uxxxxxxxx)
.replace(/(?<=[^\\]|^)\\U([0-9abcdefABCDEF]{8})/g, (_, cp) =>
String.fromCodePoint(`0x${cp}`)
)
// Unicode 4-digit code support (\uxxxx)
.replace(/(?<=[^\\]|^)\\u([0-9abcdefABCDEF]{4})/g, (_, cp) =>
String.fromCodePoint(`0x${cp}`)
)
// Backslash
.replace(/\\\\/g, '\\')
)
function transformBackslashSequences(value) {
if (typeof value !== 'string') return value
if (!value.includes('\\')) return value
return value
.replace(UNICODE_8_CODE, (_, cp) => String.fromCodePoint(`0x${cp}`))
.replace(UNICODE_4_CODE, (_, cp) => String.fromCodePoint(`0x${cp}`))
.replace(/\\\\/g, '\\')
}

function simpleSyntax (variables, node, str, opts, result) {
Expand Down
12 changes: 6 additions & 6 deletions index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,19 +81,19 @@ test('allows to use in negative numbers', () => {

test('transforms unicode escapes', () => {
run(
String.raw`$selector: .my-component[data-emoji="\U0001F389"]\u003Adisabled\u003Ahover; $selector { width: 1px }`,
'.my-component[data-emoji="🎉"]:disabled:hover { width: 1px }'
String.raw`$a: b[c="\U0001F389"]\u003Afocus\u003Ahover; $a { width: 1px }`,
'b[c="🎉"]:focus:hover { width: 1px }'
)
})

test('does not transform escaped backslashes', () => {
run(
String.raw`$selector: .my-component[data-emoji="\\U0001F389"]\\u003Adisabled\\u003Ahover; $selector { width: 1px }`,
String.raw`.my-component[data-emoji="\U0001F389"]\u003Adisabled\u003Ahover { width: 1px }`
String.raw`$a: b[c="\\U0001F389"]\\u003Afocus\\u003Ahover; $a { d:1 }`,
String.raw`b[c="\U0001F389"]\u003Afocus\u003Ahover { d:1 }`
)
run(
String.raw`$selector: .my-component[data-emoji="\\\\U0001F389"]\\\\u003Adisabled\\\\u003Ahover; $selector { width: 1px }`,
String.raw`.my-component[data-emoji="\\U0001F389"]\\u003Adisabled\\u003Ahover { width: 1px }`
String.raw`$a: b[c="\\\\U0001F389"]\\\\u003Afocus\\\\u003Ahover; $a{ d:1 }`,
String.raw`b[c="\\U0001F389"]\\u003Afocus\\u003Ahover{ d:1 }`
)
})

Expand Down

0 comments on commit 505b5ff

Please sign in to comment.