forked from sproutcore/sproutcore
/
core_query.js
2029 lines (1646 loc) · 67.6 KB
/
core_query.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2009 Sprout Systems, Inc. and contributors.
// Portions ©2008-2009 Apple Inc. All rights reserved.
// License: Licened under MIT license (see license.js)
// ==========================================================================
/*globals CQ*/
sc_require('system/builder') ;
/**
CoreQuery is a simplified DOM manipulation library used internally by
SproutCore to find and edit DOM elements. Outside of SproutCore, you
should generally use a more full-featured DOM library such as Prototype
or jQuery.
CoreQuery itself is a subset of jQuery with some additional plugins. If
you have jQuery already loaded when SproutCore loads, in fact, it will
replace CoreQuery with the full jQuery library and install any CoreQuery
plugins, including support for the SC.Enumerable mixin.
Much of this code is adapted from jQuery 1.2.6, which is available under an
MIT license just like SproutCore.
h1. Using CoreQuery
You can work with CoreQuery much like you would work with jQuery. The core
manipulation object is exposed as SC.$. To find some elements on the page
you just pass in a selector like this:
{{{
var cq = SC.$('p');
}}}
The object returned from this call is a CoreQuery object that implements
SC.Enumerable as well as a number of other useful manipulation methods.
Often times we call this object the "matched set", because it usually an
array of elements matching the selector key you passed.
To work with the matched set, just call the various helper methods on it.
Here are some of the more useful ones:
{{{
// change all of the text red
cq.css('color','red');
// hide/show the set
cq.hide(); cq.show();
// set the text content of the set
cq.text("Hello World!");
}}}
Of course, you can also chain these methods, just like jQuery. Here is
how you might find all of the headings in your page, change their text and
color:
{{{
SC.$('h1').text('Hello World!').css('color','red');
}}}
h1. Using CoreQuery with Views
Usually you will not want to just blindly edit the HTML content in your
application. Instead, you will use CoreQuery to update the portion of the
page managed by your SC.View instances. Every SC.View instance has a $()
property just like SC.$(). The difference is that this function will start
searching from the root of the view. For example, you could use the
following code in your updateDisplay method to set your content and color:
{{{
updateDisplay: function() {
this.$().text(this.get('value')).css('color','red');
}
}}}
You could also work on content within your view, for example this will
change the title on your view held in the span.title element:
{{{
updateDisplay: function() {
this.$('span.title').text('Hello World');
this.$().setClassName('sc-enabled', YES) ;
}
}}}
@class
@extends SC.Builder.fn
*/
SC.CoreQuery = (function() {
// Define CoreQuery inside of its own scope to support some jQuery idioms.
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
var quickExpr = /^[^<]*(<(.|\s)+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.]*$/,
undefined ;
var styleFloat = SC.browser.msie ? "styleFloat" : "cssFloat";
// used for the find() method.
var chars = (SC.browser.safari && parseInt(SC.browser.version,0) < 417) ?
"(?:[\\w*_-]|\\\\.)" :
"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)" ;
var quickID = new RegExp("^(" + chars + "+)(#)(" + chars + "+)") ;
var singleClass = new RegExp("^([#.]?)(" + chars + "*)");
var quickSplit = new RegExp("([#.]?)(" + chars + "*)",'g');
// Constants used in CQ.css()
var LEFT_RIGHT = ["Left", "Right"];
var TOP_BOTTOM = ["Top", "Bottom"];
var CSS_DISPLAY_PROPS = {
position: "absolute", visibility: "hidden", display:"block"
} ;
var getWH = function getWH(elem, name, which) {
var val = name == "width" ? elem.offsetWidth : elem.offsetHeight;
var padding = 0, border = 0, loc=which.length, dim;
while(--loc>=0) {
dim = which[loc];
padding += parseFloat(CQ.curCSS( elem, "padding" + dim, true)) || 0;
border += parseFloat(CQ.curCSS( elem, "border" + dim + "Width", true)) ||0;
}
val -= Math.round(padding + border);
return val;
} ;
var expando = SC.guidKey, uuid = 0, windowData = {},
// exclude the following css properties to add px
exclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
// cache defaultView
defaultView = document.defaultView || {};
// A helper method for determining if an element's values are broken
var styleIsBorked = function styleIsBorked( elem ) {
if ( !SC.browser.safari ) return false;
// defaultView is cached
var ret = defaultView.getComputedStyle( elem, null );
return !ret || ret.getPropertyValue("color") == "";
} ;
// Helper function used by the dimensions and offset modules
function num(elem, prop) {
return elem[0] && parseInt( CQ.curCSS(elem[0], prop, true), 10 ) || 0;
} ;
var CoreQuery, CQ ;
// implement core methods here from jQuery that we want available all the
// time. Use this area to implement jQuery-compatible methods ONLY.
// New methods should be added at the bottom of the file, where they will
// be installed as plugins on CoreQuery or jQuery.
CQ = CoreQuery = SC.Builder.create( /** @scope SC.CoreQuery.fn */ {
/** Indicates that this is a jQuery-like object. */
jquery: 'SC.CoreQuery',
/**
Called on a new CoreQuery instance when it is first created. You
can pass a variety of options to the CoreQuery constructor function
including:
- a simple selector: this will find the element and return it
- element or array of elements - this will return a query with them
- html-string: this will convert to DOM.
@returns {CoreQuery} CoreQuery instance
*/
init: function( selector, context ) {
// Make sure that a selection was provided
selector = selector || document;
// Handle $(DOMElement)
if ( selector.nodeType ) {
this[0] = selector;
this.length = 1;
return this ;
// Handle HTML strings
} else if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
var match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] )
selector = CQ.clean( [ match[1] ], context );
// HANDLE: $("#id")
else {
var elem = document.getElementById( match[3] );
// Make sure an element was located
if ( elem ){
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id != match[3] ) return CQ().find( selector );
// Otherwise, we inject the element directly into the jQuery object
return CQ( elem );
}
selector = [];
}
// HANDLE: $(expr, [context])
// (which is just equivalent to: $(content).find(expr)
} else return CQ( context ).find( selector );
// HANDLE: $(function)
// Shortcut for document ready
} else if (SC.typeOf(selector) === SC.T_FUNCTION) {
return SC.ready(selector);
}
return this.setArray(CQ.makeArray(selector));
},
/** Return the number of elements in the matched set. */
size: function() { return this.length; },
/** Return the nth element of the working array OR return a clean array
with the result set, if no number is passed.
@param {Number} num (Optional)
@returns {Object|Array}
*/
get: function( num ) {
return num === undefined ? CQ.makeArray(this) : this[num];
},
/**
Find subelements matching the passed selector. Note that CoreQuery
supports only a very simplified selector search method. See
CoreQuery.find() for more information.
@param {String} selector
@returns {CoreQuery} new instance with match
*/
find: function( selector ) {
var elems = CQ.map(this, function(elem){
return CQ.find( selector, elem );
});
return this.pushStack(elems);
},
/**
Filters the matching set to include only those matching the passed
selector. Note that CoreQuery supports only a simplified selector
search method. See CoreQuery.find() for more information.
Also note that CoreQuery implements SC.Enumerable, which means you can
also call this method with a callback and target and the callback will
be executed on every element in the matching set to return a result.
@param {String} selector
@returns {CoreQuery}
*/
filter: function( selector ) {
return this.pushStack(
(SC.typeOf(selector) === SC.T_FUNCTION) &&
CQ.grep(this, function(elem, i){
return selector.call( elem, i );
}) || CQ.multiFilter( selector, this ) );
},
/**
Returns the results not matching the passed selector. This is the
opposite of filter.
@param {String} selector
@returns {CoreQuery}
*/
not: function( selector ) {
if ( typeof selector === "string" ) {
// test special case where just one selector is passed in
if ( isSimple.test( selector ) )
return this.pushStack( CQ.multiFilter( selector, this, true ) );
else
selector = CQ.multiFilter( selector, this );
}
var isArrayLike = selector.length && selector[selector.length - 1] !== undefined && !selector.nodeType;
return this.filter(function() {
return isArrayLike ? CQ.inArray( this, selector ) < 0 : this != selector;
});
},
/**
Force the current matched set of elements to become the specified array
of elements (destroying the stack in the process) You should use
pushStack() in order to do this, but maintain the stack.
This method is mostly used internally. You will not need to use it
yourself very often.
@param {Array} elems
@returns {CoreQuery} receiver
*/
setArray: function( elems ) {
// Resetting the length to 0, then using the native Array push
// is a super-fast way to populate an object with array-like properties
this.length = 0;
Array.prototype.push.apply( this, elems );
return this;
},
/**
Executes the passed function on every element in the CoreQuery object.
Returns an array with the return values. Note that null values will
be omitted from the resulting set. This differs from SC.Enumerable and
the JavaScript standard.
The callback must have the signature:
{{{
function(currentElement, currentIndex) { return mappedValue; }
}}}
Note that "this" on the function will also be the currentElement.
@param {Function} callback
@returns {CoreQuery} results
*/
map: function( callback ) {
return this.pushStack( CQ.map(this, function(elem, i){
return callback.call( elem, i, elem );
}));
},
/**
Execute a callback for every element in the matched set. (You can seed
the arguments with an array of args, but this is only used internally.)
@param {Function} callback
@param {Object} args
@returns {CoreQuery} receiver
*/
each: function( callback, args ) {
return CQ.each( this, callback, args );
},
/**
Determine the position of an element within a matched set of elements.
jQuery-compatible name for indexOf().
@param {Element} elem
@returns {Number} location
*/
index: function( elem ) {
if (elem && elem.jquery) elem = elem[0];
return Array.prototype.indexOf.call(this, elem);
},
/**
Returns a new CoreQuery object that contains just the matching item.
@param {Number} i
@returns {CoreQuery}
*/
eq: function( i ) {
return this.slice( i, +i + 1 );
},
/**
Slice the CoreQuery result set just like you might slice and array.
Returns a new CoreQuery object with the result set.
@returns {CoreQuery}
*/
slice: function() {
return this.pushStack( Array.prototype.slice.apply( this, arguments ) );
},
/** Adds the relevant elements to the existing matching set. */
add: function( selector ) {
return this.pushStack( CQ.merge(
this.get(),
typeof selector === 'string' ?
CQ( selector ) :
CQ.makeArray( selector )
).uniq()) ;
},
/**
Get to set the named attribute value on the element. You can either
pass in the name of an attribute you would like to read from the first
matched element, a single attribute/value pair to set on all elements
or a hash of attribute/value pairs to set on all elements.
@param {String} name attribute name
@param {Object} value attribute value
@param {String} type ?
@returns {CoreQuery} receiver
*/
attr: function( name, value, type ) {
var options = name;
// Look for the case where we're accessing a style value
if ( typeof name === "string" )
if ( value === undefined )
return this[0] && CQ[ type || "attr" ]( this[0], name );
else {
options = {};
options[ name ] = value;
}
// Check to see if we're setting style values
return this.each(function(i){
// Set all the styles
for ( name in options )
CQ.attr(
(type)?this.style:this,
name, CQ.prop( this, options[ name ], type, i, name ));
});
},
html: function( value ) {
return value === undefined ?
(this[0] ?
this[0].innerHTML.replace(/ CQ\d+="(?:\d+|null)"/g, "") :
null) :
this.empty().append( value );
// return value == undefined ?
// (this[0] ? this[0].innerHTML : null) :
// this.empty().append( value );
},
andSelf: function() { return this.add( this.prevObject ); },
/**
Returns YES if every element in the matching set matches the passed
selector. Remember that only simple selectors are supported in
CoreQuery.
@param {String} selector
@return {Boolean}
*/
is: function( selector ) {
return !!selector && CQ.multiFilter( selector, this ).length > 0;
},
/**
Returns YES if every element in the matching set has the named CSS
class.
@param {String} className
@returns {Boolean}
*/
hasClass: function( className ) {
return Array.prototype.every.call(this, function(elem) {
return (elem.nodeType!=1) || CQ.className.has(elem, className) ;
});
},
/**
Provides a standardized, cross-browser method to get and set the
value attribute of a form element. Optionally pass a value to set or
no value to get.
@param {Object} value
@return {Object|CoreQuery}
*/
val: function( value ) {
// get the value
if ( value === undefined ) {
var elem = this[0];
if (elem) {
if(CQ.nodeName(elem, 'option'))
return (elem.attributes.value || {}).specified ? elem.value : elem.text;
// We need to handle select boxes special
if ( CQ.nodeName( elem, "select" ) ) {
var index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type == "select-one";
// Nothing was selected
if ( index < 0 ) return null;
// Loop through all the selected options
var i, max = one ? index+1:options.length;
for (i = one ? index : 0; i < max; i++ ) {
var option = options[ i ];
if ( option.selected ) {
value = CQ(option).val(); // get value
if (one) return value; // We don't need an array for one
values.push( value ); // Multi-Selects return an array
}
}
return values;
}
// Everything else, we just grab the value
return (elem.value || "").replace(/\r/g, "");
}
return undefined;
// otherwise set the value
} else {
if( typeof value === "number" ) value += ''; // force to string
this.each(function(){
if ( this.nodeType != 1 ) return;
// handle radio/checkbox. set the checked value
if (SC.typeOf(value) === SC.T_ARRAY && (/radio|checkbox/).test(this.type)) {
this.checked = (CQ.inArray(this.value, value) >= 0 ||
CQ.inArray(this.name, value) >= 0);
// handle selects
} else if ( CQ.nodeName( this, "select" ) ) {
var values = CQ.makeArray(value);
CQ( "option", this ).each(function(){
this.selected = (CQ.inArray( this.value, values ) >= 0 ||
CQ.inArray( this.text, values ) >= 0);
});
if (!values.length) this.selectedIndex = -1;
// otherwise, just set the value property
} else this.value = value;
});
}
return this ;
},
/**
Returns a clone of the matching set of elements. Note that this will
NOT clone event handlers like the jQuery version does becaue CoreQuery
does not deal with events.
*/
clone: function() {
// Do the clone
var ret = this.map(function(){
if ( SC.browser.msie && !CQ.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var clone = this.cloneNode(true),
container = document.createElement("div");
container.appendChild(clone);
return CQ.clean([container.innerHTML])[0];
} else return this.cloneNode(true);
});
// Need to set the expando to null on the cloned set if it exists
// removeData doesn't work here, IE removes it from the original as well
// this is primarily for IE but the data expando shouldn't be copied
// over in any browser
var clone = ret.find("*").andSelf().each(function(){
if ( this[ SC.guidKey ] !== undefined )
this[ SC.guidKey ] = null;
});
// Return the cloned set
return ret;
},
/**
Set or retrieve the specified CSS value. Pass only a key to get the
current value, pass a key and value to change it.
@param {String} key
@param {Object} value
@returns {Object|CoreQuery}
*/
css: function( key, value ) {
// ignore negative width and height values
if ((key == 'width' || key == 'height') && parseFloat(value,0) < 0 ) {
value = undefined;
}
return this.attr( key, value, "curCSS" );
},
/**
Set or retrieve the text content of an element. Pass a text element to
update or set to end it.
@param {String} text
@returns {String|CoreQuery}
*/
text: function( text ) {
if ( typeof text !== "object" && text != null )
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
var ret = "";
CQ.each( text || this, function(){
CQ.each( this.childNodes, function(){
if ( this.nodeType != 8 )
ret += this.nodeType != 1 ?
this.nodeValue : CQ.fn.text( [ this ] );
});
});
return ret;
},
/** Simple method to show elements without animation. */
show: function() {
var isVisible = SC.$.isVisible;
this.each(function() {
if (!isVisible(this)) {
// try to restore to natural layout as defined by CSS
this.style.display = this.oldblock || '';
// handle edge case where the CSS style is none so we can't detect
// the natural display state.
if (CQ.css(this,'display') == 'none') {
var elem = CQ('<' + this.tagName + '/>');
CQ('body').append(elem);
this.style.display = elem.css('display');
// edge case where we still can't get the display
if (this.style.display === 'none') this.style.display = 'block';
elem.remove(); elem = null;
}
}
}) ;
return this ;
},
/** Simple method to hide elements without animation. */
hide: function() {
var isVisible = SC.$.isVisible;
this.each(function() {
if (isVisible(this)) {
this.oldblock = this.oldblock || CQ.css(this,'display');
this.style.display = 'none';
}
}) ;
return this ;
},
/**
Low-level dom manipulation method used by append(), before(), after()
among others. Unlike the jQuery version, this version does not execute
<script> tags. That is generally not a good way to input scripts.
*/
domManip: function( args, table, reverse, callback ) {
var clone = this.length > 1, elems;
return this.each(function(){
if ( !elems ) {
elems = CQ.clean( args, this.ownerDocument );
if (reverse) elems.reverse();
}
var obj = this;
if ( table && CQ.nodeName( this, "table" ) && CQ.nodeName( elems[0], "tr" ) ) {
obj = this.getElementsByTagName("tbody")[0] || this.appendChild( this.ownerDocument.createElement("tbody") );
}
CQ.each(elems, function(){
var elem = clone ? CQ( this ).clone( true )[0] : this;
// Inject the elements into the document
callback.call( obj, elem );
});
});
},
append: function() {
return this.domManip(arguments, true, false, function(elem){
if (this.nodeType == 1)
this.appendChild( elem );
});
},
prepend: function() {
return this.domManip(arguments, true, true, function(elem){
if (this.nodeType == 1)
this.insertBefore( elem, this.firstChild );
});
},
before: function() {
return this.domManip(arguments, false, false, function(elem){
this.parentNode.insertBefore( elem, this );
});
},
after: function() {
return this.domManip(arguments, false, true, function(elem){
this.parentNode.insertBefore( elem, this.nextSibling );
});
},
replaceWith: function( value ) {
return this.after( value ).remove();
},
removeData: function( key ){
return this.each(function(){ SC.removeData( this, key ); });
}
}) ;
// add useful helper methods to CoreQuery
CoreQuery.mixin(/** @scope SC.CoreQuery */ {
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() == name.toUpperCase();
},
/**
Execute the passed callback on the elems array, returning an array with
the mapped values. Note that null return values are left out of the
resulting mapping array. This differs from the standard map() function
defined by SC.Enumerable and the JavaScript standard.
The callback must have the signature:
{{{
function(currentElement, currentIndex) { return mappedValue; }
}}}
Note that "this" on the function will also be the currentElement.
@param {Array} elems
@param {Function} callback
@returns {Array} mapped elements
*/
map: function( elems, callback ) {
var ret = [];
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
var value = callback( elems[ i ], i );
if ( value != null )
ret[ ret.length ] = value;
}
return ret.concat.apply([],ret) ;
},
/**
Executes the passed callback on each item in the iterable object
passed. This deviates from the standard getEach() method defined in
SC.Enumerable and in the JavaScript standards.
@param {Array} object
@param {Function} callback
@param {Object} args internal use only
@returns {Object} object
*/
each: function( object, callback, args ) {
var name, i = 0, length = object.length;
if ( args ) {
if ( length === undefined ) {
for ( name in object )
if ( callback.apply( object[ name ], args ) === false )
break;
} else
for ( ; i < length; )
if ( callback.apply( object[ i++ ], args ) === false )
break;
// A special, fast, case for the most common use of each
} else {
if ( length === undefined ) {
for ( name in object )
if ( callback.call( object[ name ], name, object[ name ] ) === false )
break;
} else
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
}
return object;
},
isXMLDoc: function( elem ) {
return elem.documentElement && !elem.body ||
elem.tagName && elem.ownerDocument && !elem.ownerDocument.body;
},
clean: function( elems, context ) {
var ret = [];
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if (typeof context.createElement == 'undefined') {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
CQ.each(elems, function(i, elem){
if ( typeof elem === 'number' ) elem += '';
if ( !elem ) return;
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(/(<(\w+)[^>]*?)\/>/g, function(all, front, tag){
return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i) ?
all :
front + "></" + tag + ">";
});
// Trim whitespace, otherwise indexOf won't work as expected
var tags = elem.replace(/^\s+/, "").substring(0, 10).toLowerCase(),
div = context.createElement("div");
var wrap =
// option or optgroup
!tags.indexOf("<opt") &&
[ 1, "<select multiple='multiple'>", "</select>" ] ||
!tags.indexOf("<leg") &&
[ 1, "<fieldset>", "</fieldset>" ] ||
tags.match(/^<(thead|tbody|tfoot|colg|cap)/) &&
[ 1, "<table>", "</table>" ] ||
!tags.indexOf("<tr") &&
[ 2, "<table><tbody>", "</tbody></table>" ] ||
// <thead> matched above
(!tags.indexOf("<td") || !tags.indexOf("<th")) &&
[ 3, "<table><tbody><tr>", "</tr></tbody></table>" ] ||
!tags.indexOf("<col") &&
[ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ] ||
// IE can't serialize <link> and <script> tags normally
SC.browser.msie &&
[ 1, "div<div>", "</div>" ] ||
[ 0, "", "" ];
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( wrap[0]-- ) div = div.lastChild;
// Remove IE's autoinserted <tbody> from table fragments
if ( SC.browser.msie ) {
// String was a <table>, *may* have spurious <tbody>
var tbody = !tags.indexOf("<table") && tags.indexOf("<tbody") < 0 ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] == "<table>" && tags.indexOf("<tbody") < 0 ?
div.childNodes :
[];
for ( var j = tbody.length - 1; j >= 0 ; --j )
if ( CQ.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length )
tbody[ j ].parentNode.removeChild( tbody[ j ] );
// IE completely kills leading whitespace when innerHTML is used
if ( /^\s/.test( elem ) )
div.insertBefore( context.createTextNode( elem.match(/^\s*/)[0] ), div.firstChild );
}
elem = CQ.makeArray( div.childNodes );
}
if (elem.length === 0 && (!CQ.nodeName( elem, "form" ) && !CQ.nodeName( elem, "select" ))) return;
if (elem[0] === undefined || CQ.nodeName( elem, "form" ) || elem.options) ret.push( elem );
else ret = CQ.merge( ret, elem );
});
return ret;
},
/**
Core element finder function in SC.CoreQuery. CoreQuery supports only
a very simple set of finders. Namely, you can specify the following
simple types of selectors:
- .class-name: this will find all elements with the matching class name
- #id: this will find all elements matching the ID
- tagname: this will find all elements with the matching tags.
You can also do some basic joined expressions like:
{{{
tagname.class-name and tagname#id
}}}
Finally, you can do simple compound searches like
{{{
tagname .class-name tagname#id
}}}
You can also pass multiple selectors separated by commas. The return
set will be the OR of all the result set.
{{{
#item1,#item2,#item3
}}}
You cannot do any child searches, psuedo-selectors or other complex
searches. These are only the kinds of selectors that can be parsed
quickly and use built-in methods on the browser.
@param {String} t selector
@param {Element} context
@returns {Array} matched elements
*/
find: function( t, context ) {
// Quickly handle non-string expressions
if ( typeof t != "string" ) return [ t ];
// if the selector contains commas, then we actually want to search
// multiple selectors.
if (t.indexOf(',')>=0) {
var ret = t.split(',').map(function(sel) {
return CQ.find(sel,context);
});
// flatten arrays
return ret.concat.apply([],ret).uniq() ;
}
// check to make sure context is a DOM element or a document
if ( context && context.nodeType != 1 && context.nodeType != 9) {
return [];
}
// Set the correct context (if none is provided)
context = context || document;
// Initialize the search. split the selector into pieces
var ret = [context], nodeName, inFindMode = YES;
var parts = t.match(quickSplit), len = parts.length, m ;
// loop through each part and either find or filter as needed
for(var idx=0;idx<len;idx++) {
t = parts[idx]; // the current selector to parse
// handle space separators. this just resets to find mode
if (t === ' ' || t === '') {
inFindMode = YES ;
// if we are in find mode, then use the current selector to
// find new elements that are children. at the end, leave findMode.
} else if (inFindMode) {
// split into parts to test result
m = singleClass.exec(t);
// handle special case where we get a tag name followed by an ID.
// in this case, just swap the two and proceed.
if ((m[1] === '') && (idx<(len-1)) && (parts[idx+1].charAt(0)==='#')) {
t = parts[idx+1]; parts[idx+1] = parts[idx]; // swap
m = singleClass.exec(t); // reparse
}
// now loop through and find elements based on tag
var next = [], retlen = ret.length, retidx, cur, val = m[2], found;
for(retidx=0;retidx<retlen;retidx++) {
cur = ret[retidx];
switch(m[1]) {
case '': // tag
if (!val) val = '*';
// Handle IE7 being really dumb about <object>s
if ( val == "*" && cur.nodeName.toLowerCase() == "object" ) {
val = "param";
}
next = CQ.merge(next, cur.getElementsByTagName(val));
break;
case '#': // id
// handle special case where we are searching the document
if (cur === document) {
found = document.getElementById(val) ;
// if this is IE, verify that it didn't search by name
if (SC.browser.msie && found && found.getAttribute('id')!==val){
found = NO; // clear