From e25cf30fcbb7b6de7651d4bf9cc43431ea638051 Mon Sep 17 00:00:00 2001 From: strarsis Date: Thu, 2 Nov 2017 16:44:35 +0100 Subject: [PATCH] Add tests and fix for onlyMatchedOnce option cleaning classes/IDs that matched more than once. Improve code. --- plugins/inlineStyles.js | 50 ++++++++++++++++------------ test/plugins/inlineStyles.18.svg | 38 ++++++++++++++++++++++ test/plugins/inlineStyles.19.svg | 56 ++++++++++++++++++++++++++++++++ 3 files changed, 123 insertions(+), 21 deletions(-) create mode 100644 test/plugins/inlineStyles.18.svg create mode 100644 test/plugins/inlineStyles.19.svg diff --git a/plugins/inlineStyles.js b/plugins/inlineStyles.js index d3fe62fd..25e8dd9e 100644 --- a/plugins/inlineStyles.js +++ b/plugins/inlineStyles.js @@ -164,34 +164,42 @@ exports.fn = function(document, opts) { } - if (opts.removeMatchedSelectors) { - // clean up matched class + ID attribute values - for (selector of sortedSelectors) { - if(!selector.selectedEls) { - continue; + if (!opts.removeMatchedSelectors) { + return document; // no further processing required + } + + + // clean up matched class + ID attribute values + for (selector of sortedSelectors) { + if(!selector.selectedEls) { + continue; + } + + if (opts.onlyMatchedOnce && selector.selectedEls !== null && selector.selectedEls.length > 1) { + // skip selectors that match more than once if option onlyMatchedOnce is enabled + continue; + } + + for (selectedEl of selector.selectedEls) { + // class + var firstSubSelector = selector.item.data.children.first(); + if(firstSubSelector.type === 'ClassSelector') { + selectedEl.class.remove(firstSubSelector.name); + } + // clean up now empty class attributes + if(typeof selectedEl.class.item(0) === 'undefined') { + selectedEl.removeAttr('class'); } - for (selectedEl of selector.selectedEls) { - // class - var firstSubSelector = selector.item.data.children.first(); - if(firstSubSelector.type === 'ClassSelector') { - selectedEl.class.remove(firstSubSelector.name); - } - // clean up now empty class attributes - if(typeof selectedEl.class.item(0) === 'undefined') { - selectedEl.removeAttr('class'); - } - - // ID - if(firstSubSelector.type === 'IdSelector') { - selectedEl.removeAttr('id', firstSubSelector.name); - } + // ID + if(firstSubSelector.type === 'IdSelector') { + selectedEl.removeAttr('id', firstSubSelector.name); } } } - // clean up elements + // clean up now empty elements for (var style of styles) { csstree.walkRules(style.cssAst, function(node, item, list) { // clean up + + + + + + +@@@ + + + + + +@@@ + +{"onlyMatchedOnce":true} diff --git a/test/plugins/inlineStyles.19.svg b/test/plugins/inlineStyles.19.svg new file mode 100644 index 00000000..2d7e429b --- /dev/null +++ b/test/plugins/inlineStyles.19.svg @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + +@@@ + + + + + + + + + + + + + + + + + +@@@ + +{"onlyMatchedOnce":true}