Skip to content

Commit

Permalink
fix(removeComments): make preserving comments a param (#1812)
Browse files Browse the repository at this point in the history
Converts the hard-coded exception to a param so users can override this
behavior to preserve custom patterns or drop the logic altogether.
  • Loading branch information
SethFalco committed Oct 27, 2023
1 parent bf45a02 commit 7de793c
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 6 deletions.
4 changes: 3 additions & 1 deletion plugins/plugins-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,9 @@ type DefaultPlugins = {

moveElemsAttrsToGroup: void;
moveGroupAttrsToElems: void;
removeComments: void;
removeComments: {
preservePatterns: Array<RegExp|string> | false
};
removeDesc: {
removeAny?: boolean;
};
Expand Down
28 changes: 25 additions & 3 deletions plugins/removeComments.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand All @@ -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);
},
},
};
Expand Down
4 changes: 2 additions & 2 deletions test/plugins/removeComments.02.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
14 changes: 14 additions & 0 deletions test/plugins/removeComments.03.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 7de793c

Please sign in to comment.