Skip to content

Commit

Permalink
feat: customAttributes, close #36
Browse files Browse the repository at this point in the history
  • Loading branch information
Scrum committed Sep 9, 2021
1 parent 8733373 commit 3e71922
Showing 1 changed file with 24 additions and 1 deletion.
25 changes: 24 additions & 1 deletion lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ const selectorParser = require('postcss-selector-parser');
const nameGenerators = require('./name-generators');

class MinifyClassnames {
constructor({genNameClass, genNameId, filter} = {}) {
constructor({genNameClass, genNameId, filter, customAttributes = []} = {}) {
this.filter = filter || /^.js-/;
// TODO: Pass a seed for emojinamestring, make this better
this.genNameClass = this.getNameGenerator(genNameClass, 7);
this.genNameId = this.getNameGenerator(genNameId, 5);
this.classMap = {};
this.idMap = {};
this.customAttributes = customAttributes;
}

getNameGenerator(value, seed) {
Expand Down Expand Up @@ -60,6 +61,28 @@ class MinifyClassnames {

minifyElements(tree) {
return tree.walk(node => {
if (node.attrs && this.customAttributes.length > 0) {
const attributes = Object.keys(node.attrs);

this.customAttributes
.filter(attribute => attributes.includes(attribute))
.forEach(attributes => {
node.attrs[attributes] = node.attrs[attributes]
.split(/\s+/)
.map(value => {
// NOTE: This removes classes that don't match any in our CSS
if (this.isClassFiltered(value)) {
return value;
}

return this.classMap[value] || '';
})
.filter(Boolean)
.join(' ')
.trim();
});
}

if (node.attrs && node.attrs.class) {
let classes = node.attrs.class;
node.attrs.class = classes
Expand Down

0 comments on commit 3e71922

Please sign in to comment.