1
1
import objectAssign from 'object-assign' ;
2
+ import specificity from 'specificity' ;
2
3
3
4
4
5
export function extendStyle ( htmlNode , cssNode ) {
@@ -14,6 +15,43 @@ export function extendStyle(htmlNode, cssNode) {
14
15
}
15
16
16
17
18
+ export function sortCSSNodesBySpecificity ( nodes ) {
19
+ // Sort CSS nodes by specificity (ascending): div - .foo - #bar
20
+ return nodes . sort ( ( a , b ) => {
21
+ a = getSpecificity ( a . selector ) ;
22
+ b = getSpecificity ( b . selector ) ;
23
+
24
+ if ( a > b ) {
25
+ return 1 ;
26
+ } else if ( a < b ) {
27
+ return - 1 ;
28
+ } else {
29
+ return 0 ;
30
+ }
31
+ } ) ;
32
+ }
33
+
34
+
35
+ var specificityCache = { } ;
36
+ function getSpecificity ( selector ) {
37
+ if ( specificityCache [ selector ] !== undefined ) {
38
+ return specificityCache [ selector ] ;
39
+ }
40
+
41
+ const specificityResult = specificity . calculate ( selector ) [ 0 ] ;
42
+ const specificityParts = specificityResult . specificity . split ( ',' ) . reverse ( ) ;
43
+ // Convert "0,1,3,2" to 132 (2*1 + 3*10 + 1*100 + 0*1000)
44
+ const totalSpecificity = specificityParts . reduce ( ( totalSpecificity , specificity , i ) => {
45
+ specificity = parseInt ( specificity , 10 ) ;
46
+ return totalSpecificity + ( specificity * Math . pow ( 10 , i ) ) ;
47
+ } , 0 ) ;
48
+
49
+ specificityCache [ selector ] = totalSpecificity ;
50
+
51
+ return totalSpecificity ;
52
+ }
53
+
54
+
17
55
function stringifyCss ( css ) {
18
56
const styles = Object . keys ( css ) . map ( prop => prop + ': ' + css [ prop ] ) ;
19
57
return styles . join ( '; ' ) ;
0 commit comments