@@ -12,24 +12,64 @@ select.ruleSet = function (selector, ast) {
12
12
select . rule = function ( selector , ast ) {
13
13
var result = [ ] ;
14
14
15
- ( function walk ( node ) {
15
+ switch ( selector . nestingOperator ) {
16
+ case null :
17
+ case undefined :
18
+ case '>' :
19
+ walk ( ast ) ;
20
+ break ;
21
+
22
+ case '+' :
23
+ if ( ast . children && ast . children . length ) {
24
+ walk ( ast . children [ 0 ] , ast ) ;
25
+ }
26
+ break ;
27
+
28
+ case '~' :
29
+ ( ast . children || [ ] ) . forEach ( function ( node ) {
30
+ walk ( node , ast ) ;
31
+ } ) ;
32
+ break ;
33
+
34
+ default :
35
+ throw Error ( 'Unexpected nesting operator: ' + selector . nestingOperator ) ;
36
+ }
37
+
38
+ return result ;
39
+
40
+ function walk ( node , parent ) {
16
41
if ( node . type == selector . tagName ) {
17
42
if ( ! selector . rule ) {
18
- return result . push ( node ) ;
19
- }
20
- if ( ! node . children ) {
21
- return ;
43
+ return append ( result , [ node ] ) ;
22
44
}
23
45
24
- node . children . forEach ( function ( childNode ) {
25
- [ ] . push . apply ( result , select . rule ( selector . rule , childNode ) ) ;
26
- } ) ;
46
+ if ( ! selector . rule . nestingOperator || selector . rule . nestingOperator == '>' ) {
47
+ if ( ! node . children ) return ;
48
+ node . children . forEach ( function ( childNode ) {
49
+ [ ] . push . apply ( result , select . rule ( selector . rule , childNode ) ) ;
50
+ } ) ;
51
+ }
52
+ else {
53
+ if ( ! parent ) return ;
54
+ append ( result , select . rule ( selector . rule , {
55
+ children : parent . children . slice ( parent . children . indexOf ( node ) + 1 )
56
+ } ) ) ;
57
+ }
27
58
}
28
59
29
60
if ( ! selector . nestingOperator && node . children ) {
30
- node . children . forEach ( walk ) ;
61
+ node . children . forEach ( function ( child ) {
62
+ walk ( child , node ) ;
63
+ } ) ;
31
64
}
32
- } ( ast ) ) ;
33
-
34
- return result ;
65
+ }
35
66
} ;
67
+
68
+
69
+ function append ( array , elements ) {
70
+ elements . forEach ( function ( el ) {
71
+ if ( array . indexOf ( el ) < 0 ) {
72
+ array . push ( el ) ;
73
+ }
74
+ } ) ;
75
+ }
0 commit comments