From 36de66a75145057b7ae0ac7cfbfc0af70cbbced1 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 | 6 ++++++ 2 files changed, 29 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..c50c7624577 100644 --- a/src/parser/getCSSRules.ts +++ b/src/parser/getCSSRules.ts @@ -30,6 +30,12 @@ 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 bracket, it is likely a nested CSS at-rule + // like @media, @supports, @scope, etc. Ignore these. + if ((rule.match(/{/g) || []).length > 1) { + return; + } + const match = rule.split('{'), ruleObj: Record = {}, declaration = match[1].trim(),