From 1783c550db0a8736c8fe27036f0cd1a8be3fa77a Mon Sep 17 00:00:00 2001 From: illright Date: Sat, 6 Jun 2020 17:49:35 +0300 Subject: [PATCH] fix: teach the globalifySelector to determine combinators --- src/modules/globalifySelector.ts | 18 ++++++++++++++---- test/modules.test.ts | 21 +++++++++++++++++++++ 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/src/modules/globalifySelector.ts b/src/modules/globalifySelector.ts index 37742cbb..ff853d55 100644 --- a/src/modules/globalifySelector.ts +++ b/src/modules/globalifySelector.ts @@ -1,9 +1,19 @@ +const combinatorPattern = /(\s*[ >+~]\s*)(?![^[]+\])/g; + export function globalifySelector(selector: string) { return selector .trim() - .split(' ') - .filter(Boolean) - .map((selectorPart) => { + .split(combinatorPattern) + .map((selectorPart: string, index: number) => { + // if this is the separator + if (index % 2 !== 0) { + return selectorPart; + } + + if (selectorPart === '') { + return selectorPart; + } + if (selectorPart.startsWith(':local')) { return selectorPart.replace(/:local\((.+?)\)/g, '$1'); } @@ -13,5 +23,5 @@ export function globalifySelector(selector: string) { return `:global(${selectorPart})`; }) - .join(' '); + .join(''); } diff --git a/test/modules.test.ts b/test/modules.test.ts index d873985c..637aa12b 100644 --- a/test/modules.test.ts +++ b/test/modules.test.ts @@ -2,6 +2,7 @@ import { resolve } from 'path'; import { importAny } from '../src/modules/importAny'; import { getIncludePaths } from '../src/modules/getIncludePaths'; +import { globalifySelector } from '../src/modules/globalifySelector'; describe('importAny', () => { it('should throw error when none exist', () => { @@ -49,3 +50,23 @@ describe('getIncludePaths', () => { expect(paths).toEqual(['src', 'node_modules', process.cwd(), dummyDir]); }); }); + +describe('globalifySelector', () => { + it('correctly treats CSS selectors with legal spaces', async () => { + const selector = '[attr="with spaces"]'; + + expect(globalifySelector(selector)).toEqual( + ':global([attr="with spaces"])', + ); + }); + + it('correctly treats CSS combinators', async () => { + const selector = 'div > span'; + + expect(globalifySelector(selector)).toMatch( + // either be :global(div > span) + // or :global(div) > :global(span) + /(:global\(div> span\)|:global\(div\) > :global\(span\))/, + ); + }); +});