-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
87 lines (72 loc) · 2.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
module.exports = function(opts) {
// Added Angular after data. See https://github.com/mdo/code-guide/issues/106
var orderList = (opts && opts.order) || [
'class', 'id', 'name',
'data-.+', 'ng-.+', 'src',
'for', 'type', 'href',
'values', 'title', 'alt',
'role', 'aria-.+',
'$unknown$'
];
// A RegExp's for filtering and sorting
var orderListFilterRegExp = new RegExp('^(' + orderList.join('|') + ')$');
var orderListRegExp = orderList.map(function(item) {
return new RegExp('^' + item + '$');
});
return function(tree) {
tree.walk(function(node) {
if (!node.attrs) {
return node;
}
var attrs = Object.keys(node.attrs);
if (attrs.length === 1 || orderList.length === 0) {
return node;
}
var sortableAttrs = [];
var sortedAttrs = [];
var notSortedAttrs = [];
var notSortedAttrsIndex = orderList.indexOf('$unknown$');
var finalAttrs = {};
if (notSortedAttrsIndex === -1) {
notSortedAttrsIndex = orderList.length;
}
sortableAttrs = attrs
// The separation of the attributes on a sortable and not sortable basis
.filter(function(attr) {
if (orderListFilterRegExp.test(attr)) {
return true;
}
notSortedAttrs.push(attr);
return false;
});
sortedAttrs = orderListRegExp
// match to each position
.map(function(regex) {
return sortableAttrs
// attrs that belong in this regex group
.filter(function(attr) {
return regex.test(attr);
})
// alpha desc sort each group
.sort(function(a, b) {
return typeof a.localeCompare === 'function' ? a.localeCompare(b) : a - b;
});
})
// remove empty groups
.filter(function(group) {
return group.length > 0;
});
sortedAttrs
// put the non-sorted attributes in desired slot
.splice(notSortedAttrsIndex, 0, notSortedAttrs);
sortedAttrs.forEach(function(group) {
group.forEach(function(attr) {
finalAttrs[attr] = (node.attrs[attr]) ? node.attrs[attr] : true;
});
});
node.attrs = finalAttrs;
return node;
});
return tree;
};
};