Skip to content

Commit

Permalink
fix: classname can contain escaped sequence of not allowed characters
Browse files Browse the repository at this point in the history
  • Loading branch information
theKashey committed Nov 9, 2021
1 parent 0a06da5 commit 894fed6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
26 changes: 26 additions & 0 deletions __tests__/extraction.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,30 @@ describe('extraction stories', () => {
"
`);
});

it('handle exotic styles', async () => {
const styles: StyleDefinition = loadStyleDefinitions(
() => ['test.css'],
() => `
@media screen and (min-width:1350px){.content__L0XJ\\+{color:red}}
.primary__L4\\+dg{ color: blue}
.primary__L4+dg{ color: wrong}
`
);
await styles;

const extracted = getCriticalRules('<div class="content__L0XJ+ primary__L4+dg">', styles);

expect(extracted).toMatchInlineSnapshot(`
"
/* test.css */
@media screen and (min-width:1350px) {
.content__L0XJ\\\\+ { color: red; }
}
.primary__L4\\\\+dg { color: blue; }
"
`);
});
});
8 changes: 4 additions & 4 deletions src/parser/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const classish = (str: string): boolean => !!str && str.indexOf('.') >= 0;

export const mapStyles = (styles: string) =>
export const mapStyles = (styles: string): string[] =>
(
styles
// remove style body
Expand All @@ -13,9 +13,9 @@ export const mapStyles = (styles: string) =>
.map((x) => x.replace(/[\s,.>~+$]+/, ''))
.map((x) => x.replace(/[.\s.:]+/, ''));

export const mapSelector = (selector: string) => {
export const mapSelector = (selector: string): string[] => {
// replace `something:not(.something)` to `something:not`
const cleanSelector = selector.replace(/\(([^)])*\)/, '');
const cleanSelector = selector.replace(/\(([^)])*\)/g, '').replace(/(\\\+)/g, 'PLUS_SYMBOL');
const ruleSelection =
// anything like "style"
cleanSelector.match(/\.([^>~+$:{\[\s]+)?/g) || [];
Expand All @@ -25,5 +25,5 @@ export const mapSelector = (selector: string) => {
const effectiveMatcher: string = ruleSelection.find(classish) || '';
const selectors = effectiveMatcher.match(/(\.[^.>~+,$:{\[\s]+)?/g);

return (selectors || []).map((x) => x.replace(/[.\s.:]+/, '')).filter(Boolean);
return (selectors || []).map((x) => x.replace(/[.\s.:]+/, '').replace(/PLUS_SYMBOL/g, '+')).filter(Boolean);
};

0 comments on commit 894fed6

Please sign in to comment.