Lots of improvements. Added support for .not( jQuery("...") ) and support for multi...
[jquery.git] / src / selector / selector.js
1 jQuery.extend({
2         expr: {
3                 "": "m[2]== '*'||a.nodeName.toUpperCase()==m[2].toUpperCase()",
4                 "#": "a.getAttribute('id')==m[2]",
5                 ":": {
6                         // Position Checks
7                         lt: "i<m[3]-0",
8                         gt: "i>m[3]-0",
9                         nth: "m[3]-0==i",
10                         eq: "m[3]-0==i",
11                         first: "i==0",
12                         last: "i==r.length-1",
13                         even: "i%2==0",
14                         odd: "i%2",
15
16                         // Child Checks
17                         "nth-child": "jQuery.nth(a.parentNode.firstChild,m[3],'nextSibling')==a",
18                         "first-child": "jQuery.nth(a.parentNode.firstChild,1,'nextSibling')==a",
19                         "last-child": "jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a",
20                         "only-child": "jQuery.sibling(a.parentNode.firstChild).length==1",
21
22                         // Parent Checks
23                         parent: "a.firstChild",
24                         empty: "!a.firstChild",
25
26                         // Text Check
27                         contains: "jQuery.fn.text.apply([a]).indexOf(m[3])>=0",
28
29                         // Visibility
30                         visible: "a.type!='hidden'&&jQuery.css(a,'display')!='none'&&jQuery.css(a,'visibility')!='hidden'",
31                         hidden: "a.type=='hidden'||jQuery.css(a,'display')=='none'||jQuery.css(a,'visibility')=='hidden'",
32
33                         // Form attributes
34                         enabled: "!a.disabled",
35                         disabled: "a.disabled",
36                         checked: "a.checked",
37                         selected: "a.selected || jQuery.attr(a, 'selected')",
38
39                         // Form elements
40                         text: "a.type=='text'",
41                         radio: "a.type=='radio'",
42                         checkbox: "a.type=='checkbox'",
43                         file: "a.type=='file'",
44                         password: "a.type=='password'",
45                         submit: "a.type=='submit'",
46                         image: "a.type=='image'",
47                         reset: "a.type=='reset'",
48                         button: "a.type=='button'||a.nodeName=='BUTTON'",
49                         input: "/input|select|textarea|button/i.test(a.nodeName)"
50                 },
51                 ".": "jQuery.className.has(a,m[2])",
52                 "@": {
53                         "=": "z==m[4]",
54                         "!=": "z!=m[4]",
55                         "^=": "z && !z.indexOf(m[4])",
56                         "$=": "z && z.substr(z.length - m[4].length,m[4].length)==m[4]",
57                         "*=": "z && z.indexOf(m[4])>=0",
58                         "": "z",
59                         _resort: function(m){
60                                 return ["", m[1], m[3], m[2], m[5]];
61                         },
62                         _prefix: "z=a[m[3]]||jQuery.attr(a,m[3]);"
63                 },
64                 "[": "jQuery.find(m[2],a).length"
65         },
66         
67         // The regular expressions that power the parsing engine
68         parse: [
69                 // Match: [@value='test'], [@foo]
70                 "\\[ *(@)S *([!*$^=]*) *('?\"?)(.*?)\\4 *\\]",
71
72                 // Match: [div], [div p]
73                 "(\\[)\\s*(.*?(\\[.*?\\])?[^[]*?)\\s*\\]",
74
75                 // Match: :contains('foo')
76                 "(:)S\\(\"?'?(.*?(\\(.*?\\))?[^(]*?)\"?'?\\)",
77
78                 // Match: :even, :last-chlid
79                 "([:.#]*)S"
80         ],
81
82         token: [
83                 "\\.\\.|/\\.\\.", "a.parentNode",
84                 ">|/", "jQuery.sibling(a.firstChild)",
85                 "\\+", "jQuery.nth(a,2,'nextSibling')",
86                 "~", function(a){
87                         var s = jQuery.sibling(a.parentNode.firstChild);
88                         return s.slice(0, jQuery.inArray(a,s));
89                 }
90         ],
91
92         multiFilter: function( expr, elems, not ) {
93                 var old, cur = [];
94
95                 while ( expr && expr != old ) {
96 console.log( cur, expr, elems, not );
97                         var f = jQuery.filter( expr, elems, not );
98                         expr = f.t.replace(/^\s*,\s*/, "" );
99
100                         if ( not )
101                                 cur = elems = f.r;
102                         else
103                                 cur = jQuery.merge( cur, f.r );
104                 }
105 console.log( "DONE", cur, expr, elems, not );
106
107                 return cur;
108         },
109
110         /**
111          * @name $.find
112          * @type Array<Element>
113          * @private
114          * @cat Core
115          */
116         find: function( t, context ) {
117                 // Quickly handle non-string expressions
118                 if ( typeof t != "string" )
119                         return [ t ];
120
121                 // Make sure that the context is a DOM Element
122                 if ( context && !context.nodeType )
123                         context = null;
124
125                 // Set the correct context (if none is provided)
126                 context = context || document;
127
128                 // Handle the common XPath // expression
129                 if ( !t.indexOf("//") ) {
130                         context = context.documentElement;
131                         t = t.substr(2,t.length);
132
133                 // And the / root expression
134                 } else if ( !t.indexOf("/") ) {
135                         context = context.documentElement;
136                         t = t.substr(1,t.length);
137                         if ( t.indexOf("/") >= 1 )
138                                 t = t.substr(t.indexOf("/"),t.length);
139                 }
140
141                 // Initialize the search
142                 var ret = [context], done = [], last = null;
143
144                 // Continue while a selector expression exists, and while
145                 // we're no longer looping upon ourselves
146                 while ( t && last != t ) {
147                         var r = [];
148                         last = t;
149
150                         t = jQuery.trim(t).replace( /^\/\//i, "" );
151
152                         var foundToken = false;
153
154                         // An attempt at speeding up child selectors that
155                         // point to a specific element tag
156                         var re = /^[\/>]\s*([a-z0-9*-]+)/i;
157                         var m = re.exec(t);
158
159                         if ( m ) {
160                                 // Perform our own iteration and filter
161                                 for ( var i = 0, rl = ret.length; i < rl; i++ )
162                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
163                                                 if ( c.nodeType == 1 && ( c.nodeName == m[1].toUpperCase() || m[1] == "*" ) )
164                                                         r.push( c );
165
166                                 ret = r;
167                                 t = jQuery.trim( t.replace( re, "" ) );
168                                 foundToken = true;
169                         } else {
170                                 // Look for pre-defined expression tokens
171                                 for ( var i = 0; i < jQuery.token.length; i += 2 ) {
172                                         // Attempt to match each, individual, token in
173                                         // the specified order
174                                         var re = new RegExp("^(" + jQuery.token[i] + ")");
175                                         var m = re.exec(t);
176
177                                         // If the token match was found
178                                         if ( m ) {
179                                                 // Map it against the token's handler
180                                                 r = ret = jQuery.map( ret, jQuery.token[i+1].constructor == Function ?
181                                                         jQuery.token[i+1] :
182                                                         function(a){ return eval(jQuery.token[i+1]); });
183
184                                                 // And remove the token
185                                                 t = jQuery.trim( t.replace( re, "" ) );
186                                                 foundToken = true;
187                                                 break;
188                                         }
189                                 }
190                         }
191
192                         // See if there's still an expression, and that we haven't already
193                         // matched a token
194                         if ( t && !foundToken ) {
195                                 // Handle multiple expressions
196                                 if ( !t.indexOf(",") || !t.indexOf("|") ) {
197                                         // Clean teh result set
198                                         if ( ret[0] == context ) ret.shift();
199
200                                         // Merge the result sets
201                                         jQuery.merge( done, ret );
202
203                                         // Reset the context
204                                         r = ret = [context];
205
206                                         // Touch up the selector string
207                                         t = " " + t.substr(1,t.length);
208
209                                 } else {
210                                         // Optomize for the case nodeName#idName
211                                         var re2 = /^([a-z0-9_-]+)(#)([a-z0-9\\*_-]*)/i;
212                                         var m = re2.exec(t);
213                                         
214                                         // Re-organize the results, so that they're consistent
215                                         if ( m ) {
216                                            m = [ 0, m[2], m[3], m[1] ];
217
218                                         } else {
219                                                 // Otherwise, do a traditional filter check for
220                                                 // ID, class, and element selectors
221                                                 re2 = /^([#.]?)([a-z0-9\\*_-]*)/i;
222                                                 m = re2.exec(t);
223                                         }
224
225                                         // Try to do a global search by ID, where we can
226                                         if ( m[1] == "#" && ret[ret.length-1].getElementById ) {
227                                                 // Optimization for HTML document case
228                                                 var oid = ret[ret.length-1].getElementById(m[2]);
229
230                                                 // Do a quick check for node name (where applicable) so
231                                                 // that div#foo searches will be really fast
232                                                 ret = r = oid && 
233                                                   (!m[3] || oid.nodeName == m[3].toUpperCase()) ? [oid] : [];
234
235                                         } else {
236                                                 // Pre-compile a regular expression to handle class searches
237                                                 if ( m[1] == "." )
238                                                         var rec = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
239
240                                                 // We need to find all descendant elements, it is more
241                                                 // efficient to use getAll() when we are already further down
242                                                 // the tree - we try to recognize that here
243                                                 for ( var i = 0, rl = ret.length; i < rl; i++ )
244                                                         jQuery.merge( r,
245                                                                 m[1] != "" && ret.length != 1 ?
246                                                                         jQuery.getAll( ret[i], [], m[1], m[2], rec ) :
247                                                                         ret[i].getElementsByTagName( m[1] != "" || m[0] == "" ? "*" : m[2] )
248                                                         );
249
250                                                 // It's faster to filter by class and be done with it
251                                                 if ( m[1] == "." && ret.length == 1 )
252                                                         r = jQuery.grep( r, function(e) {
253                                                                 return rec.test(e.className);
254                                                         });
255
256                                                 // Same with ID filtering
257                                                 if ( m[1] == "#" && ret.length == 1 ) {
258                                                         // Remember, then wipe out, the result set
259                                                         var tmp = r;
260                                                         r = [];
261
262                                                         // Then try to find the element with the ID
263                                                         for ( var i = 0, tl = tmp.length; i < tl; i++ )
264                                                                 if ( tmp[i].getAttribute("id") == m[2] ) {
265                                                                         r = [ tmp[i] ];
266                                                                         break;
267                                                                 }
268                                                 }
269
270                                                 ret = r;
271                                         }
272
273                                         t = t.replace( re2, "" );
274                                 }
275
276                         }
277
278                         // If a selector string still exists
279                         if ( t ) {
280                                 // Attempt to filter it
281                                 var val = jQuery.filter(t,r);
282                                 ret = r = val.r;
283                                 t = jQuery.trim(val.t);
284                         }
285                 }
286
287                 // Remove the root context
288                 if ( ret && ret[0] == context ) ret.shift();
289
290                 // And combine the results
291                 jQuery.merge( done, ret );
292
293                 return done;
294         },
295
296         filter: function(t,r,not) {
297                 // Look for common filter expressions
298                 while ( t && /^[a-z[({<*:.#]/i.test(t) ) {
299
300                         var p = jQuery.parse;
301
302                         for ( var i = 0, pl = p.length; i < pl; i++ ) {
303                 
304                                 // Look for, and replace, string-like sequences
305                                 // and finally build a regexp out of it
306                                 var re = new RegExp(
307                                         "^" + p[i].replace("S", "([a-z*_-][a-z0-9_-]*)"), "i" );
308
309                                 var m = re.exec( t );
310
311                                 if ( m ) {
312                                         // Re-organize the first match
313                                         if ( jQuery.expr[ m[1] ]._resort )
314                                                 m = jQuery.expr[ m[1] ]._resort( m );
315
316                                         // Remove what we just matched
317                                         t = t.replace( re, "" );
318
319                                         break;
320                                 }
321                         }
322
323                         // :not() is a special case that can be optimized by
324                         // keeping it out of the expression list
325                         if ( m[1] == ":" && m[2] == "not" )
326                                 r = jQuery.filter(m[3], r, true).r;
327
328                         // Handle classes as a special case (this will help to
329                         // improve the speed, as the regexp will only be compiled once)
330                         else if ( m[1] == "." ) {
331
332                                 var re = new RegExp("(^|\\s)" + m[2] + "(\\s|$)");
333                                 r = jQuery.grep( r, function(e){
334                                         return re.test(e.className || '');
335                                 }, not);
336
337                         // Otherwise, find the expression to execute
338                         } else {
339                                 var f = jQuery.expr[m[1]];
340                                 if ( typeof f != "string" )
341                                         f = jQuery.expr[m[1]][m[2]];
342
343                                 // Build a custom macro to enclose it
344                                 eval("f = function(a,i){" +
345                                         ( jQuery.expr[ m[1] ]._prefix || "" ) +
346                                         "return " + f + "}");
347
348                                 // Execute it against the current filter
349                                 r = jQuery.grep( r, f, not );
350                         }
351                 }
352
353                 // Return an array of filtered elements (r)
354                 // and the modified expression string (t)
355                 return { r: r, t: t };
356         },
357         
358         getAll: function( o, r, token, name, re ) {
359                 for ( var s = o.firstChild; s; s = s.nextSibling )
360                         if ( s.nodeType == 1 ) {
361                                 var add = true;
362
363                                 if ( token == "." )
364                                         add = s.className && re.test(s.className);
365                                 else if ( token == "#" )
366                                         add = s.getAttribute('id') == name;
367         
368                                 if ( add )
369                                         r.push( s );
370
371                                 if ( token == "#" && r.length ) break;
372
373                                 if ( s.firstChild )
374                                         jQuery.getAll( s, r, token, name, re );
375                         }
376
377                 return r;
378         },
379
380         /**
381          * All ancestors of a given element.
382          *
383          * @private
384          * @name $.parents
385          * @type Array<Element>
386          * @param Element elem The element to find the ancestors of.
387          * @cat DOM/Traversing
388          */
389         parents: function( elem ){
390                 var matched = [];
391                 var cur = elem.parentNode;
392                 while ( cur && cur != document ) {
393                         matched.push( cur );
394                         cur = cur.parentNode;
395                 }
396                 return matched;
397         },
398         
399         /**
400          * A handy, and fast, way to traverse in a particular direction and find
401          * a specific element.
402          *
403          * @private
404          * @name $.nth
405          * @type DOMElement
406          * @param DOMElement cur The element to search from.
407          * @param Number|String num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
408          * @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
409          * @cat DOM/Traversing
410          */
411         nth: function(cur,result,dir){
412                 result = result || 1;
413                 var num = 0;
414                 for ( ; cur; cur = cur[dir] ) {
415                         if ( cur.nodeType == 1 ) num++;
416                         if ( num == result || result == "even" && num % 2 == 0 && num > 1 ||
417                                 result == "odd" && num % 2 == 1 ) return cur;
418                 }
419         },
420         
421         /**
422          * All elements on a specified axis.
423          *
424          * @private
425          * @name $.sibling
426          * @type Array
427          * @param Element elem The element to find all the siblings of (including itself).
428          * @cat DOM/Traversing
429          */
430         sibling: function( n, elem ) {
431                 var r = [];
432
433                 for ( ; n; n = n.nextSibling ) {
434                         if ( n.nodeType == 1 && (!elem || n != elem) )
435                                 r.push( n );
436                 }
437
438                 return r;
439         }
440 });