diff --git a/plugins/plugins-types.ts b/plugins/plugins-types.ts index 7c4132d1a..daf5ff0ad 100644 --- a/plugins/plugins-types.ts +++ b/plugins/plugins-types.ts @@ -119,7 +119,9 @@ type DefaultPlugins = { moveElemsAttrsToGroup: void; moveGroupAttrsToElems: void; - removeComments: void; + removeComments: { + preservePatterns: Array | false + }; removeDesc: { removeAny?: boolean; }; diff --git a/plugins/removeComments.js b/plugins/removeComments.js index 70e462714..67f8efd19 100644 --- a/plugins/removeComments.js +++ b/plugins/removeComments.js @@ -5,6 +5,12 @@ const { detachNodeFromParent } = require('../lib/xast.js'); exports.name = 'removeComments'; exports.description = 'removes comments'; +/** + * If a comment matches one of the following patterns, it will be + * preserved by default. Particularly for copyright/license information. + */ +const DEFAULT_PRESERVE_PATTERNS = [/^!/]; + /** * Remove comments. * @@ -16,13 +22,29 @@ exports.description = 'removes comments'; * * @type {import('./plugins-types').Plugin<'removeComments'>} */ -exports.fn = () => { +exports.fn = (_root, params) => { + const { preservePatterns = DEFAULT_PRESERVE_PATTERNS } = params; + return { comment: { enter: (node, parentNode) => { - if (node.value.charAt(0) !== '!') { - detachNodeFromParent(node, parentNode); + if (preservePatterns) { + if (!Array.isArray(preservePatterns)) { + throw Error( + `Expected array in removeComments preservePatterns parameter but received ${preservePatterns}` + ); + } + + const matches = preservePatterns.some((pattern) => { + return new RegExp(pattern).test(node.value); + }); + + if (matches) { + return; + } } + + detachNodeFromParent(node, parentNode); }, }, }; diff --git a/test/plugins/removeComments.02.svg b/test/plugins/removeComments.02.svg index d62ff2a27..6e6b67aeb 100644 --- a/test/plugins/removeComments.02.svg +++ b/test/plugins/removeComments.02.svg @@ -1,11 +1,11 @@ - + test @@@ - + test diff --git a/test/plugins/removeComments.03.svg b/test/plugins/removeComments.03.svg new file mode 100644 index 000000000..1a2c56b90 --- /dev/null +++ b/test/plugins/removeComments.03.svg @@ -0,0 +1,14 @@ + + + test + + +@@@ + + + test + + +@@@ + +{"preservePatterns":false}