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
12 changes: 11 additions & 1 deletion src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,27 @@ function memoize(fn) {
* Reduce a CSS selector to be without any pseudo class parts.
* For example, from `a:hover` return `a`. And from `input::-moz-focus-inner`
* to `input`.
*
* Also, more advanced ones like `a[href^="javascript:"]:after` to
* `a[href^="javascript:"]`.
*
* The last example works too if the input was `a[href^='javascript:']:after`
* instead (using ' instead of ").
*
* As per CSS spec [1], special characters can be escaped by using a backslash.
* For a <h1 class="md:title">Title</h1> element, the corresponding CSS selector
* would be .md\:title { font-size: 32px; }. If the negative lookbehind founds the
* escape char, this function returns the selector as is. Special thanks to valtzu
* for helping to solve the issue.
*
* [1]: https://www.w3.org/TR/CSS2/syndata.html
*
* @param {string} selector
* @return {string}
*/
const reduceCSSSelector = memoize((selector) => {
return selector.split(
/:(?=([^"'\\]*(\\.|["']([^"'\\]*\\.)*[^"'\\]*['"]))*[^"']*$)/g
/(?<!\\):(?=([^"'\\]*(\\.|["']([^"'\\]*\\.)*[^"'\\]*['"]))*[^"']*$)/g
)[0];
});

Expand Down
2 changes: 2 additions & 0 deletions tests/utils.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ test('Test reduceCSSSelector', async () => {
expect(f('a[href^="javascript:"]:after')).toEqual('a[href^="javascript:"]');
// Should work with ' instead of " too.
expect(f("a[href^='javascript:']:after")).toEqual("a[href^='javascript:']");
// Should leave the selector as is if escape char is found
expect(f(`.md\\:title`)).toEqual(".md\\:title");
});

test('Test parentSelectors', async () => {
Expand Down