From a2673b17937f69b2ac704e2ed64c3192cee9855e Mon Sep 17 00:00:00 2001 From: Adam Wathan Date: Sun, 27 Aug 2017 17:35:09 -0400 Subject: [PATCH] Automatically escape non-standard characters in class selectors Prevents end user from having to worry about escaping crap in their config. --- __tests__/defineClass.test.js | 5 +++++ src/defaultConfig.js | 22 +++++++++++----------- src/util/defineClass.js | 6 +++++- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/__tests__/defineClass.test.js b/__tests__/defineClass.test.js index 49c7930be..9d14286d5 100644 --- a/__tests__/defineClass.test.js +++ b/__tests__/defineClass.test.js @@ -21,3 +21,8 @@ it('does not modify the case of property names', () => { let output = defineClass('smooth', {'-webkit-font-smoothing': 'antialiased'}) expect(c(output.toString())).toEqual(`.smooth { -webkit-font-smoothing: antialiased }`) }) + +it('escapes non-standard characters in selectors', () => { + let output = defineClass('w-1/4', {'width': '25%'}) + expect(c(output.toString())).toEqual(`.w-1\\/4 { width: 25% }`) +}) diff --git a/src/defaultConfig.js b/src/defaultConfig.js index 92294524f..891e99ffa 100644 --- a/src/defaultConfig.js +++ b/src/defaultConfig.js @@ -277,17 +277,17 @@ export default { 'full': '100%', }, width: { - '1\\/2': '50%', - '1\\/3': 'calc(100% / 3)', - '2\\/3': 'calc(100% / 3 * 2)', - '1\\/4': '25%', - '3\\/4': '75%', - '1\\/5': '20%', - '2\\/5': '40%', - '3\\/5': '60%', - '4\\/5': '80%', - '1\\/6': 'calc(100% / 6)', - '5\\/6': 'calc(100% / 6 * 5)', + '1/2': '50%', + '1/3': 'calc(100% / 3)', + '2/3': 'calc(100% / 3 * 2)', + '1/4': '25%', + '3/4': '75%', + '1/5': '20%', + '2/5': '40%', + '3/5': '60%', + '4/5': '80%', + '1/6': 'calc(100% / 6)', + '5/6': 'calc(100% / 6 * 5)', 'screen': '100vw' }, height: { diff --git a/src/util/defineClass.js b/src/util/defineClass.js index 58b39dbed..4f1e4dfac 100644 --- a/src/util/defineClass.js +++ b/src/util/defineClass.js @@ -1,6 +1,10 @@ import _ from 'lodash' import postcss from 'postcss' +function escapeSelector(selector) { + return selector.replace(/([^A-Za-z0-9\-])/g, "\\$1") +} + export default function(className, properties) { const decls = _.map(properties, (value, property) => { return postcss.decl({ @@ -10,6 +14,6 @@ export default function(className, properties) { }) return postcss.rule({ - selector: `.${className}`, + selector: `.${escapeSelector(className)}`, }).append(decls) }