From 17b4ec150d93efa81da5f7bb2ccb4c8bc323d27a Mon Sep 17 00:00:00 2001 From: silverwind Date: Sun, 3 Mar 2024 18:36:55 +0100 Subject: [PATCH] fix(SVGParser): Don't crash on nested CSS at-rules Fixes: https://github.com/fabricjs/fabric.js/issues/9679 --- src/parser/getCSSRules.spec.ts | 29 +++++++++++++++++++++++------ src/parser/getCSSRules.ts | 7 +++++++ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/src/parser/getCSSRules.spec.ts b/src/parser/getCSSRules.spec.ts index 057bbada010..ee4f46648dd 100644 --- a/src/parser/getCSSRules.spec.ts +++ b/src/parser/getCSSRules.spec.ts @@ -1,13 +1,30 @@ import { loadSVGFromString } from './loadSVGFromString'; -const testSvg = ``; - describe('getCSSRules', () => { test('can load svgs with style tags with import statement', async () => { - const loaded = await loadSVGFromString(testSvg); + const loaded = await loadSVGFromString(``); expect(loaded.objects).toHaveLength(2); }); + + test('can load svgs with style tags with media query', async () => { + const loaded = await loadSVGFromString(` + + + + + `); + expect(loaded.objects).toHaveLength(1); + }); }); diff --git a/src/parser/getCSSRules.ts b/src/parser/getCSSRules.ts index 875ddebb438..43f73e8c491 100644 --- a/src/parser/getCSSRules.ts +++ b/src/parser/getCSSRules.ts @@ -30,6 +30,13 @@ export function getCSSRules(doc: Document) { .filter((rule, index, array) => array.length > 1 && rule.trim()) // at this point we have hopefully an array of rules `body { style code... ` .forEach((rule) => { + // if there is more than one opening, it is likely not a nested CSS at-rule + // like @media or @supports, ignore these. + const numOpeningBrackets = (rule.match(/{/g) || []).length; + if (numOpeningBrackets > 1) { + return; + } + const match = rule.split('{'), ruleObj: Record = {}, declaration = match[1].trim(),