From 7f3ea302743e7855ccef31f858deba6df779eadf Mon Sep 17 00:00:00 2001 From: Vjacheslav Trushkin Date: Mon, 2 Oct 2023 12:20:47 +0300 Subject: [PATCH] chore: skip scripts and css when formatting svg --- packages/utils/src/svg/pretty.ts | 46 +++++++++++++++++++---- packages/utils/tests/prettify-svg-test.ts | 25 ++++++++++++ 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/packages/utils/src/svg/pretty.ts b/packages/utils/src/svg/pretty.ts index b21958b..311b036 100644 --- a/packages/utils/src/svg/pretty.ts +++ b/packages/utils/src/svg/pretty.ts @@ -1,3 +1,8 @@ +/** + * Tags to skip + */ +const skipTags = ['script', 'style']; + /** * Prettify SVG */ @@ -39,22 +44,32 @@ export function prettifySVG( content = content.slice(openIndex); closeIndex -= openIndex; - // Check for bad tag - const nextOpenIndex = content.indexOf('<', 1); - if (nextOpenIndex !== -1 && nextOpenIndex < closeIndex) { - // Fail: unexpected '<' - return null; - } - // Check tag const lastChar = content.slice(closeIndex - 1, closeIndex); const isClosing = content.slice(0, 2) === ']/) + .shift() as string; + const ignoreTagContent = + !isSelfClosing && !isClosing && skipTags.includes(tagName); + + // Check for bad content after tag + if (!ignoreTagContent) { + const nextOpenIndex = content.indexOf('<', 1); + if (nextOpenIndex !== -1 && nextOpenIndex < closeIndex) { + // Fail: unexpected '<' + return null; + } + } + // Add tag if (isClosing && tab.length) { // Remove one level @@ -65,6 +80,21 @@ export function prettifySVG( result += content.slice(0, closeIndex + 1); content = content.slice(closeIndex + 1); + // Add content after tag + if (ignoreTagContent) { + const closingIndex = content.indexOf('', closingIndex); + if (closingIndex < 0 || closingEnd < 0) { + // Failed to find closing tag + return null; + } + result += content.slice(0, closingEnd + 1); + content = content.slice(closingEnd + 1); + + // Mask as self-closing + isSelfClosing = true; + } + // Prepare for next tag if (isClosing) { level--; diff --git a/packages/utils/tests/prettify-svg-test.ts b/packages/utils/tests/prettify-svg-test.ts index 62dea01..2ab6a36 100644 --- a/packages/utils/tests/prettify-svg-test.ts +++ b/packages/utils/tests/prettify-svg-test.ts @@ -47,6 +47,31 @@ describe('Prettify SVG', () => { ); }); + test('Style and script', () => { + // Basic CSS + expect( + prettifySVG('') + ).toBe('\n\t\n\n'); + + // Basic script + expect( + prettifySVG( + '' + ) + ).toBe( + '\n\t\n\n' + ); + + // Selector with '>' and tag after that + expect( + prettifySVG( + '' + ) + ).toBe( + '\n\t\n\t\n\t\n\n' + ); + }); + test('Bad code', () => { expect(prettifySVG('Incomplete SVG')).toBeNull(); expect(