Clean up in jQuery.event.fix (#1171)
[jquery.git] / src / selector / selector.js
1 jQuery.extend({
2         expr: {
3                 "": "m[2]=='*'||jQuery.nodeName(a,m[2])",
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)==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: '"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',
31                         hidden: '"hidden"==a.type||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: "'text'==a.type",
41                         radio: "'radio'==a.type",
42                         checkbox: "'checkbox'==a.type",
43                         file: "'file'==a.type",
44                         password: "'password'==a.type",
45                         submit: "'submit'==a.type",
46                         image: "'image'==a.type",
47                         reset: "'reset'==a.type",
48                         button: '"button"==a.type||jQuery.nodeName(a,"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: "var z=a[m[3]];if(!z||/href|src/.test(m[3]))z=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                 /^\[ *(@)([\w-]+) *([!*$^=]*) *('?"?)(.*?)\4 *\]/,
71
72                 // Match: [div], [div p]
73                 /^(\[)\s*(.*?(\[.*?\])?[^[]*?)\s*\]/,
74
75                 // Match: :contains('foo')
76                 /^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,
77
78                 // Match: :even, :last-chlid, #id, .class
79                 new RegExp("^([:.#]*)(" + 
80                         ( jQuery.chars = "(?:[\\w\u0128-\uFFFF*_-]|\\\\.)" ) + "+)")
81         ],
82
83         token: [
84                 /^(\/?\.\.)/, "a.parentNode",
85                 /^(>|\/)/, "jQuery.sibling(a.firstChild)",
86                 /^(\+)/, "jQuery.nth(a,2,'nextSibling')",
87                 /^(~)/, function(a){
88                         var s = jQuery.sibling(a.parentNode.firstChild);
89                         return s.slice(jQuery.inArray(a,s) + 1);
90                 }
91         ],
92
93         multiFilter: function( expr, elems, not ) {
94                 var old, cur = [];
95
96                 while ( expr && expr != old ) {
97                         old = expr;
98                         var f = jQuery.filter( expr, elems, not );
99                         expr = f.t.replace(/^\s*,\s*/, "" );
100                         cur = not ? elems = f.r : jQuery.merge( cur, f.r );
101                 }
102
103                 return cur;
104         },
105
106         /**
107          * @name $.find
108          * @type Array<Element>
109          * @private
110          * @cat Core
111          */
112         find: function( t, context ) {
113                 // Quickly handle non-string expressions
114                 if ( typeof t != "string" )
115                         return [ t ];
116
117                 // Make sure that the context is a DOM Element
118                 if ( context && !context.nodeType )
119                         context = null;
120
121                 // Set the correct context (if none is provided)
122                 context = context || document;
123
124                 // Handle the common XPath // expression
125                 if ( !t.indexOf("//") ) {
126                         context = context.documentElement;
127                         t = t.substr(2,t.length);
128
129                 // And the / root expression
130                 } else if ( !t.indexOf("/") && !context.ownerDocument ) {
131                         context = context.documentElement;
132                         t = t.substr(1,t.length);
133                         if ( t.indexOf("/") >= 1 )
134                                 t = t.substr(t.indexOf("/"),t.length);
135                 }
136
137                 // Initialize the search
138                 var ret = [context], done = [], last;
139
140                 // Continue while a selector expression exists, and while
141                 // we're no longer looping upon ourselves
142                 while ( t && last != t ) {
143                         var r = [];
144                         last = t;
145
146                         t = jQuery.trim(t).replace( /^\/\//, "" );
147
148                         var foundToken = false;
149
150                         // An attempt at speeding up child selectors that
151                         // point to a specific element tag
152                         var re = new RegExp("^[/>]\\s*(" + jQuery.chars + "+)");
153                         var m = re.exec(t);
154
155                         if ( m ) {
156                                 // Perform our own iteration and filter
157                                 for ( var i = 0; ret[i]; i++ )
158                                         for ( var c = ret[i].firstChild; c; c = c.nextSibling )
159                                                 if ( c.nodeType == 1 && ( m[1] == "*" || jQuery.nodeName(c, m[1]) ) )
160                                                         r.push( c );
161
162                                 ret = r;
163                                 t = t.replace( re, "" );
164                                 if ( t.indexOf(" ") == 0 ) continue;
165                                 foundToken = true;
166                         } else {
167                                 // Look for pre-defined expression tokens
168                                 for ( var i = 0, tl = jQuery.token.length; i < tl; i += 2 ) {
169                                         // Attempt to match each, individual, token in
170                                         // the specified order
171                                         var re = jQuery.token[i], fn = jQuery.token[i+1];
172                                         var m = re.exec(t);
173
174                                         // If the token match was found
175                                         if ( m ) {
176                                                 // Map it against the token's handler
177                                                 r = ret = jQuery.map( ret, jQuery.isFunction( fn ) ?
178                                                         fn : new Function( "a", "return " + fn ) );
179
180                                                 // And remove the token
181                                                 t = jQuery.trim( t.replace( re, "" ) );
182                                                 foundToken = true;
183                                                 break;
184                                         }
185                                 }
186                         }
187
188                         // See if there's still an expression, and that we haven't already
189                         // matched a token
190                         if ( t && !foundToken ) {
191                                 // Handle multiple expressions
192                                 if ( !t.indexOf(",") ) {
193                                         // Clean the result set
194                                         if ( context == ret[0] ) ret.shift();
195
196                                         // Merge the result sets
197                                         done = jQuery.merge( done, ret );
198
199                                         // Reset the context
200                                         r = ret = [context];
201
202                                         // Touch up the selector string
203                                         t = " " + t.substr(1,t.length);
204
205                                 } else {
206                                         // Optomize for the case nodeName#idName
207                                         var re2 = new RegExp("^(" + jQuery.chars + "+)(#)(" + jQuery.chars + "+)");
208                                         var m = re2.exec(t);
209                                         
210                                         // Re-organize the results, so that they're consistent
211                                         if ( m ) {
212                                            m = [ 0, m[2], m[3], m[1] ];
213
214                                         } else {
215                                                 // Otherwise, do a traditional filter check for
216                                                 // ID, class, and element selectors
217                                                 re2 = new RegExp("^([#.]?)(" + jQuery.chars + "*)");
218                                                 m = re2.exec(t);
219                                         }
220
221                                         m[2] = m[2].replace(/\\/g, "");
222
223                                         var elem = ret[ret.length-1];
224
225                                         // Try to do a global search by ID, where we can
226                                         if ( m[1] == "#" && elem && elem.getElementById ) {
227                                                 // Optimization for HTML document case
228                                                 var oid = elem.getElementById(m[2]);
229                                                 
230                                                 // Do a quick check for the existence of the actual ID attribute
231                                                 // to avoid selecting by the name attribute in IE
232                                                 if ( (jQuery.browser.msie||jQuery.browser.opera) && oid && oid.id != m[2] )
233                                                         oid = jQuery('[@id="'+m[2]+'"]', elem)[0];
234
235                                                 // Do a quick check for node name (where applicable) so
236                                                 // that div#foo searches will be really fast
237                                                 ret = r = oid && (!m[3] || jQuery.nodeName(oid, m[3])) ? [oid] : [];
238                                         } else {
239                                                 // We need to find all descendant elements
240                                                 for ( var i = 0; ret[i]; i++ ) {
241                                                         // Grab the tag name being searched for
242                                                         var tag = m[1] != "" || m[0] == "" ? "*" : m[2];
243
244                                                         // Handle IE7 being really dumb about <object>s
245                                                         if ( tag == "*" && ret[i].nodeName.toLowerCase() == "object" )
246                                                                 tag = "param";
247
248                                                         r = jQuery.merge( r, ret[i].getElementsByTagName( tag ));
249                                                 }
250
251                                                 // It's faster to filter by class and be done with it
252                                                 if ( m[1] == "." )
253                                                         r = jQuery.classFilter( r, m[2] );
254
255                                                 // Same with ID filtering
256                                                 if ( m[1] == "#" ) {
257                                                         var tmp = [];
258
259                                                         // Try to find the element with the ID
260                                                         for ( var i = 0; r[i]; i++ )
261                                                                 if ( r[i].getAttribute("id") == m[2] ) {
262                                                                         tmp = [ r[i] ];
263                                                                         break;
264                                                                 }
265
266                                                         r = tmp;
267                                                 }
268
269                                                 ret = r;
270                                         }
271
272                                         t = t.replace( re2, "" );
273                                 }
274
275                         }
276
277                         // If a selector string still exists
278                         if ( t ) {
279                                 // Attempt to filter it
280                                 var val = jQuery.filter(t,r);
281                                 ret = r = val.r;
282                                 t = jQuery.trim(val.t);
283                         }
284                 }
285
286                 // An error occurred with the selector;
287                 // just return an empty set instead
288                 if ( t )
289                         ret = [];
290
291                 // Remove the root context
292                 if ( ret && context == ret[0] )
293                         ret.shift();
294
295                 // And combine the results
296                 done = jQuery.merge( done, ret );
297
298                 return done;
299         },
300
301         classFilter: function(r,m,not){
302                 m = " " + m + " ";
303                 var tmp = [];
304                 for ( var i = 0; r[i]; i++ ) {
305                         var pass = (" " + r[i].className + " ").indexOf( m ) >= 0;
306                         if ( !not && pass || not && !pass )
307                                 tmp.push( r[i] );
308                 }
309                 return tmp;
310         },
311
312         filter: function(t,r,not) {
313                 var last;
314
315                 // Look for common filter expressions
316                 while ( t  && t != last ) {
317                         last = t;
318
319                         var p = jQuery.parse, m;
320
321                         for ( var i = 0; p[i]; i++ ) {
322                                 m = p[i].exec( t );
323
324                                 if ( m ) {
325                                         // Remove what we just matched
326                                         t = t.substring( m[0].length );
327
328                                         // Re-organize the first match
329                                         if ( jQuery.expr[ m[1] ]._resort )
330                                                 m = jQuery.expr[ m[1] ]._resort( m );
331
332                                         m[2] = m[2].replace(/\\/g, "");
333
334                                         break;
335                                 }
336                         }
337
338                         if ( !m )
339                                 break;
340
341                         // :not() is a special case that can be optimized by
342                         // keeping it out of the expression list
343                         if ( m[1] == ":" && m[2] == "not" )
344                                 r = jQuery.filter(m[3], r, true).r;
345
346                         // We can get a big speed boost by filtering by class here
347                         else if ( m[1] == "." )
348                                 r = jQuery.classFilter(r, m[2], not);
349
350                         // Otherwise, find the expression to execute
351                         else {
352                                 var f = jQuery.expr[m[1]];
353                                 if ( typeof f != "string" )
354                                         f = jQuery.expr[m[1]][m[2]];
355
356                                 // Build a custom macro to enclose it
357                                 eval("f = function(a,i){" +
358                                         ( jQuery.expr[ m[1] ]._prefix || "" ) +
359                                         "return " + f + "}");
360
361                                 // Execute it against the current filter
362                                 r = jQuery.grep( r, f, not );
363                         }
364                 }
365
366                 // Return an array of filtered elements (r)
367                 // and the modified expression string (t)
368                 return { r: r, t: t };
369         },
370
371         /**
372          * All ancestors of a given element.
373          *
374          * @private
375          * @name $.parents
376          * @type Array<Element>
377          * @param Element elem The element to find the ancestors of.
378          * @cat DOM/Traversing
379          */
380         parents: function( elem ){
381                 var matched = [];
382                 var cur = elem.parentNode;
383                 while ( cur && cur != document ) {
384                         matched.push( cur );
385                         cur = cur.parentNode;
386                 }
387                 return matched;
388         },
389         
390         /**
391          * A handy, and fast, way to traverse in a particular direction and find
392          * a specific element.
393          *
394          * @private
395          * @name $.nth
396          * @type DOMElement
397          * @param DOMElement cur The element to search from.
398          * @param String|Number num The Nth result to match. Can be a number or a string (like 'even' or 'odd').
399          * @param String dir The direction to move in (pass in something like 'previousSibling' or 'nextSibling').
400          * @cat DOM/Traversing
401          */
402         nth: function(cur,result,dir,elem){
403                 result = result || 1;
404                 var num = 0;
405                 for ( ; cur; cur = cur[dir] ) {
406                         if ( cur.nodeType == 1 ) num++;
407                         if ( num == result || result == "even" && num % 2 == 0 && num > 1 && cur == elem ||
408                                 result == "odd" && num % 2 == 1 && cur == elem ) break;
409                 }
410                 return cur;
411         },
412         
413         /**
414          * All elements on a specified axis.
415          *
416          * @private
417          * @name $.sibling
418          * @type Array
419          * @param Element elem The element to find all the siblings of (including itself).
420          * @cat DOM/Traversing
421          */
422         sibling: function( n, elem ) {
423                 var r = [];
424
425                 for ( ; n; n = n.nextSibling ) {
426                         if ( n.nodeType == 1 && (!elem || n != elem) )
427                                 r.push( n );
428                 }
429
430                 return r;
431         }
432 });