forked from dperini/nwmatcher
/
nwmatcher.js
1656 lines (1407 loc) · 56.1 KB
/
nwmatcher.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
/*
* Copyright (C) 2007-2013 Diego Perini
* All rights reserved.
*
* nwmatcher.js - A fast CSS selector engine and matcher
*
* Author: Diego Perini <diego.perini at gmail com>
* Version: 1.3.1
* Created: 20070722
* Release: 20130211
*
* License:
* http://javascript.nwbox.com/NWMatcher/MIT-LICENSE
* Download:
* http://javascript.nwbox.com/NWMatcher/nwmatcher.js
*/
(function(global, factory) {
if (typeof module == 'object' && typeof exports == 'object') {
// in a Node.js environment, the nwmatcher functions will operate on
// the passed "browserGlobal" and will be returned in an object
module.exports = function (browserGlobal) {
var exports = { };
factory(browserGlobal, exports);
return exports;
};
} else {
// in a browser environment, the nwmatcher functions will operate on
// the "global" loading them and be attached to "global.NW.Dom"
if (!global.NW) {
global.NW = { };
}
if (!global.NW.Dom) {
global.NW.Dom = { };
}
factory(global, global.NW.Dom);
}
})(this, function(global, exports) {
var version = 'nwmatcher-1.3.1',
Dom = exports,
// processing context & root element
doc = global.document,
root = doc.documentElement,
// save utility methods references
slice = global.Array.prototype.slice,
string = global.Object.prototype.toString,
// persist previous parsed data
isSingleMatch,
isSingleSelect,
lastSlice,
lastContext,
lastPosition,
lastMatcher,
lastSelector,
lastPartsMatch,
lastPartsSelect,
// accepted prefix identifiers
// (id, class & pseudo-class)
prefixes = '[#.:]?',
// accepted attribute operators
operators = '([~*^$|!]?={1})',
// accepted whitespace characters
whitespace = '[\\x20\\t\\n\\r\\f]*',
// 4 combinators F E, F>E, F+E, F~E
combinators = '[\\x20]|[>+~][^>+~]',
// an+b format params for pseudo-classes
pseudoparms = '(?:[-+]?\\d*n)?[-+]?\\d*',
// CSS quoted string values
quotedvalue = '"[^"]*"' + "|'[^']*'",
// skip round brackets groups
skipround = '\\([^()]+\\)|\\(.*\\)',
// skip curly brackets groups
skipcurly = '\\{[^{}]+\\}|\\{.*\\}',
// skip square brackets groups
skipsquare = '\\[[^[\\]]*\\]|\\[.*\\]',
// skip [ ], ( ), { } brackets groups
skipgroup = '\\[.*\\]|\\(.*\\)|\\{.*\\}',
// http://www.w3.org/TR/css3-syntax/#characters
// unicode/ISO 10646 characters 161 and higher
// NOTE: Safari 2.0.x crashes with escaped (\\)
// Unicode ranges in regular expressions so we
// use a negated character range class instead
encoding = '(?:[-\\w]|[^\\x00-\\xa0]|\\\\.)',
// CSS identifier syntax
identifier = '(?:-?[_a-zA-Z]{1}[-\\w]*|[^\\x00-\\xa0]+|\\\\.+)+',
// build attribute string
attrcheck = '(' + quotedvalue + '|' + identifier + ')',
attributes = whitespace + '(' + encoding + '*:?' + encoding + '+)' +
whitespace + '(?:' + operators + whitespace + attrcheck + ')?' + whitespace,
attrmatcher = attributes.replace(attrcheck, '([\\x22\\x27]*)((?:\\\\?.)*?)\\3'),
// build pseudoclass string
pseudoclass = '((?:' +
// an+b parameters or quoted string
pseudoparms + '|' + quotedvalue + '|' +
// id, class, pseudo-class selector
prefixes + '|' + encoding + '+|' +
// nested HTML attribute selector
'\\[' + attributes + '\\]|' +
// nested pseudo-class selector
'\\(.+\\)|' + whitespace + '|' +
// nested pseudos/separators
',)+)',
// placeholder for extensions
extensions = '.+',
// CSS3: syntax scanner and
// one pass validation only
// using regular expression
standardValidator =
// discard start
'(?=[\\x20\\t\\n\\r\\f]*[^>+~(){}<>])' +
// open match group
'(' +
//universal selector
'\\*' +
// id/class/tag/pseudo-class identifier
'|(?:' + prefixes + identifier + ')' +
// combinator selector
'|' + combinators +
// HTML attribute selector
'|\\[' + attributes + '\\]' +
// pseudo-classes parameters
'|\\(' + pseudoclass + '\\)' +
// dom properties selector (extension)
'|\\{' + extensions + '\\}' +
// selector group separator (comma)
'|(?:,|' + whitespace + ')' +
// close match group
')+',
// validator for complex selectors in ':not()' pseudo-classes
extendedValidator = standardValidator.replace(pseudoclass, '.*'),
// validator for standard selectors as default
reValidator = new global.RegExp(standardValidator, 'g'),
// whitespace is any combination of these 5 character [\x20\t\n\r\f]
// http://www.w3.org/TR/css3-selectors/#selector-syntax
reTrimSpaces = new global.RegExp('^' +
whitespace + '|' + whitespace + '$', 'g'),
// only allow simple selectors nested in ':not()' pseudo-classes
reSimpleNot = new global.RegExp('^(' +
'(?!:not)' +
'(' + prefixes +
'|' + identifier +
'|\\([^()]*\\))+' +
'|\\[' + attributes + '\\]' +
')$'),
// split comma groups, exclude commas from
// quotes '' "" and from brackets () [] {}
reSplitGroup = new global.RegExp('(' +
'[^,\\\\()[\\]]+' +
'|' + skipsquare +
'|' + skipround +
'|' + skipcurly +
'|\\\\.' +
')+', 'g'),
// split last, right most, selector group token
reSplitToken = new global.RegExp('(' +
'\\[' + attributes + '\\]|' +
'\\(' + pseudoclass + '\\)|' +
'\\\\.|[^\\x20\\t\\r\\n\\f>+~])+', 'g'),
// for in excess whitespace removal
reWhiteSpace = /[\x20\t\n\r\f]+/g,
reOptimizeSelector = new global.RegExp(identifier + '|^$'),
/*----------------------------- FEATURE TESTING ----------------------------*/
// detect native methods
isNative = (function() {
var s = (doc.appendChild + '').replace(/appendChild/g, '');
return function(object, method) {
var m = object && object[method] || false;
return m && typeof m != 'string' &&
s == (m + '').replace(new global.RegExp(method, 'g'), '');
};
})(),
// NATIVE_XXXXX true if method exist and is callable
// detect if DOM methods are native in browsers
NATIVE_FOCUS = isNative(doc, 'hasFocus'),
NATIVE_QSAPI = isNative(doc, 'querySelector'),
NATIVE_GEBID = isNative(doc, 'getElementById'),
NATIVE_GEBTN = isNative(root, 'getElementsByTagName'),
NATIVE_GEBCN = isNative(root, 'getElementsByClassName'),
// detect native getAttribute/hasAttribute methods,
// frameworks extend these to elements, but it seems
// this does not work for XML namespaced attributes,
// used to check both getAttribute/hasAttribute in IE
NATIVE_GET_ATTRIBUTE = isNative(root, 'getAttribute'),
NATIVE_HAS_ATTRIBUTE = isNative(root, 'hasAttribute'),
// check if slice() can convert nodelist to array
// see http://yura.thinkweb2.com/cft/
NATIVE_SLICE_PROTO =
(function() {
var isBuggy = false;
try {
isBuggy = !!slice.call(doc.childNodes, 0)[0];
} catch(e) { }
return isBuggy;
})(),
// supports the new traversal API
NATIVE_TRAVERSAL_API =
'nextElementSibling' in root && 'previousElementSibling' in root,
// BUGGY_XXXXX true if method is feature tested and has known bugs
// detect buggy gEBID
BUGGY_GEBID = NATIVE_GEBID ?
(function() {
var isBuggy = true, x = 'x' + global.String(+new global.Date),
a = doc.createElementNS ? 'a' : '<a name="' + x + '">';
(a = doc.createElement(a)).name = x;
root.insertBefore(a, root.firstChild);
isBuggy = !!doc.getElementById(x);
root.removeChild(a);
return isBuggy;
})() :
true,
// detect IE gEBTN comment nodes bug
BUGGY_GEBTN = NATIVE_GEBTN ?
(function() {
var div = doc.createElement('div');
div.appendChild(doc.createComment(''));
return !!div.getElementsByTagName('*')[0];
})() :
true,
// detect Opera gEBCN second class and/or UTF8 bugs as well as Safari 3.2
// caching class name results and not detecting when changed,
// tests are based on the jQuery selector test suite
BUGGY_GEBCN = NATIVE_GEBCN ?
(function() {
var isBuggy, div = doc.createElement('div'), test = '\u53f0\u5317';
// Opera tests
div.appendChild(doc.createElement('span')).
setAttribute('class', test + 'abc ' + test);
div.appendChild(doc.createElement('span')).
setAttribute('class', 'x');
isBuggy = !div.getElementsByClassName(test)[0];
// Safari test
div.lastChild.className = test;
return isBuggy || div.getElementsByClassName(test).length != 2;
})() :
true,
// detect IE bug with dynamic attributes
BUGGY_GET_ATTRIBUTE = NATIVE_GET_ATTRIBUTE ?
(function() {
var input = doc.createElement('input');
input.setAttribute('value', 5);
return input.defaultValue != 5;
})() :
true,
// detect IE bug with non-standard boolean attributes
BUGGY_HAS_ATTRIBUTE = NATIVE_HAS_ATTRIBUTE ?
(function() {
var option = doc.createElement('option');
option.setAttribute('selected', 'selected');
return !option.hasAttribute('selected');
})() :
true,
// detect Safari bug with selected option elements
BUGGY_SELECTED =
(function() {
var select = doc.createElement('select');
select.appendChild(doc.createElement('option'));
return !select.firstChild.selected;
})(),
// initialized with the loading context
// and reset for each different context
BUGGY_QUIRKS_GEBCN,
BUGGY_QUIRKS_QSAPI,
QUIRKS_MODE,
XML_DOCUMENT,
// detect Opera browser
OPERA = /opera/i.test(string.call(global.opera)),
// skip simple selector optimizations for Opera >= 11
OPERA_QSAPI = OPERA && parseFloat(opera.version()) >= 11,
// check Selector API implementations
RE_BUGGY_QSAPI = NATIVE_QSAPI ?
(function() {
var pattern = [ ], div = doc.createElement('div'), element,
expect = function(selector, context, element, n) {
var result = false;
context.appendChild(element);
try { result = context.querySelectorAll(selector).length == n; } catch(e) { }
while (context.firstChild) { context.removeChild(context.firstChild); }
return result;
};
// ^= $= *= operators bugs with empty values (Opera 10 / IE8)
element = doc.createElement('p');
element.setAttribute('class', '');
expect('[class^=""]', div, element, 1) &&
pattern.push('[*^$]=[\\x20\\t\\n\\r\\f]*(?:""|' + "'')");
// :checked bug with option elements (Firefox 3.6.x)
// it wrongly includes 'selected' options elements
// HTML5 rules says selected options also match
element = doc.createElement('option');
element.setAttribute('selected', 'selected');
expect(':checked', div, element, 0) &&
pattern.push(':checked');
// :enabled :disabled bugs with hidden fields (Firefox 3.5)
// http://www.w3.org/TR/html5/links.html#selector-enabled
// http://www.w3.org/TR/css3-selectors/#enableddisabled
// not supported by IE8 Query Selector
element = doc.createElement('input');
element.setAttribute('type', 'hidden');
expect(':enabled', div, element, 0) &&
pattern.push(':enabled', ':disabled');
// :link bugs with hyperlinks matching (Firefox/Safari)
element = doc.createElement('link');
element.setAttribute('href', 'x');
expect(':link', div, element, 1) ||
pattern.push(':link');
// avoid attribute selectors for IE QSA
if (BUGGY_HAS_ATTRIBUTE) {
// IE fails in reading:
// - original values for input/textarea
// - original boolean values for controls
pattern.push('\\[[\\x20\\t\\n\\r\\f]*(?:checked|disabled|ismap|multiple|readonly|selected|value)');
}
return pattern.length ?
new global.RegExp(pattern.join('|')) :
{ 'test': function() { return false; } };
})() :
true,
// matches class selectors
RE_CLASS = new global.RegExp('(?:\\[[\\x20\\t\\n\\r\\f]*class\\b|\\.' + identifier + ')'),
// matches simple id, tag & class selectors
RE_SIMPLE_SELECTOR = new global.RegExp(
!(BUGGY_GEBTN && BUGGY_GEBCN) ? !OPERA ?
'^(?:\\*|[.#]?-?[_a-zA-Z]{1}' + encoding + '*)$' :
'^(?:\\*|#-?[_a-zA-Z]{1}' + encoding + '*)$' :
'^#?-?[_a-zA-Z]{1}' + encoding + '*$'),
/*----------------------------- LOOKUP OBJECTS -----------------------------*/
LINK_NODES = { 'a': 1, 'A': 1, 'area': 1, 'AREA': 1, 'link': 1, 'LINK': 1 },
// boolean attributes should return attribute name instead of true/false
ATTR_BOOLEAN = {
'checked': 1, 'disabled': 1, 'ismap': 1,
'multiple': 1, 'readonly': 1, 'selected': 1
},
// dynamic attributes that needs to be checked against original HTML value
ATTR_DEFAULT = {
'value': 'defaultValue',
'checked': 'defaultChecked',
'selected': 'defaultSelected'
},
// attributes referencing URI data values need special treatment in IE
ATTR_URIDATA = {
'action': 2, 'cite': 2, 'codebase': 2, 'data': 2, 'href': 2,
'longdesc': 2, 'lowsrc': 2, 'src': 2, 'usemap': 2
},
// HTML 5 draft specifications
// http://www.whatwg.org/specs/web-apps/current-work/#selectors
HTML_TABLE = {
// class attribute must be treated case-insensitive in HTML quirks mode
// initialized by default to Standard Mode (case-sensitive),
// set dynamically by the attribute resolver
'class': 0,
'accept': 1, 'accept-charset': 1, 'align': 1, 'alink': 1, 'axis': 1,
'bgcolor': 1, 'charset': 1, 'checked': 1, 'clear': 1, 'codetype': 1, 'color': 1,
'compact': 1, 'declare': 1, 'defer': 1, 'dir': 1, 'direction': 1, 'disabled': 1,
'enctype': 1, 'face': 1, 'frame': 1, 'hreflang': 1, 'http-equiv': 1, 'lang': 1,
'language': 1, 'link': 1, 'media': 1, 'method': 1, 'multiple': 1, 'nohref': 1,
'noresize': 1, 'noshade': 1, 'nowrap': 1, 'readonly': 1, 'rel': 1, 'rev': 1,
'rules': 1, 'scope': 1, 'scrolling': 1, 'selected': 1, 'shape': 1, 'target': 1,
'text': 1, 'type': 1, 'valign': 1, 'valuetype': 1, 'vlink': 1
},
// the following attributes must be treated case-insensitive in XHTML mode
// Niels Leenheer http://rakaz.nl/item/css_selector_bugs_case_sensitivity
XHTML_TABLE = {
'accept': 1, 'accept-charset': 1, 'alink': 1, 'axis': 1,
'bgcolor': 1, 'charset': 1, 'codetype': 1, 'color': 1,
'enctype': 1, 'face': 1, 'hreflang': 1, 'http-equiv': 1,
'lang': 1, 'language': 1, 'link': 1, 'media': 1, 'rel': 1,
'rev': 1, 'target': 1, 'text': 1, 'type': 1, 'vlink': 1
},
/*-------------------------- REGULAR EXPRESSIONS ---------------------------*/
// placeholder to add functionalities
Selectors = {
// as a simple example this will check
// for chars not in standard ascii table
//
// 'mySpecialSelector': {
// 'Expression': /\u0080-\uffff/,
// 'Callback': mySelectorCallback
// }
//
// 'mySelectorCallback' will be invoked
// only after passing all other standard
// checks and only if none of them worked
},
// attribute operators
Operators = {
'=': "n=='%m'",
'^=': "n.indexOf('%m')==0",
'*=': "n.indexOf('%m')>-1",
'|=': "(n+'-').indexOf('%m-')==0",
'~=': "(' '+n+' ').indexOf(' %m ')>-1",
'$=': "n.substr(n.length-'%m'.length)=='%m'"
},
// optimization expressions
Optimize = {
ID: new global.RegExp('^\\*?#(' + encoding + '+)|' + skipgroup),
TAG: new global.RegExp('^(' + encoding + '+)|' + skipgroup),
CLASS: new global.RegExp('^\\*?\\.(' + encoding + '+$)|' + skipgroup)
},
// precompiled Regular Expressions
Patterns = {
// structural pseudo-classes and child selectors
spseudos: /^\:(root|empty|(?:first|last|only)(?:-child|-of-type)|nth(?:-last)?(?:-child|-of-type)\(\s*(even|odd|(?:[-+]{0,1}\d*n\s*)?[-+]{0,1}\s*\d*)\s*\))?(.*)/i,
// uistates + dynamic + negation pseudo-classes
dpseudos: /^\:(link|visited|target|active|focus|hover|checked|disabled|enabled|selected|lang\(([-\w]{2,})\)|not\(([^()]*|.*)\))?(.*)/i,
// element attribute matcher
attribute: new global.RegExp('^\\[' + attrmatcher + '\\](.*)'),
// E > F
children: /^[\x20\t\n\r\f]*\>[\x20\t\n\r\f]*(.*)/,
// E + F
adjacent: /^[\x20\t\n\r\f]*\+[\x20\t\n\r\f]*(.*)/,
// E ~ F
relative: /^[\x20\t\n\r\f]*\~[\x20\t\n\r\f]*(.*)/,
// E F
ancestor: /^[\x20\t\n\r\f]+(.*)/,
// all
universal: /^\*(.*)/,
// id
id: new global.RegExp('^#(' + encoding + '+)(.*)'),
// tag
tagName: new global.RegExp('^(' + encoding + '+)(.*)'),
// class
className: new global.RegExp('^\\.(' + encoding + '+)(.*)')
},
/*------------------------------ UTIL METHODS ------------------------------*/
// concat elements to data
concatList =
function(data, elements) {
var i = -1, element;
if (!data.length && Array.slice)
return Array.slice(elements);
while ((element = elements[++i]))
data[data.length] = element;
return data;
},
// concat elements to data and callback
concatCall =
function(data, elements, callback) {
var i = -1, element;
while ((element = elements[++i])) {
if (false === callback(data[data.length] = element)) { break; }
}
return data;
},
// change context specific variables
switchContext =
function(from, force) {
var div, oldDoc = doc;
// save passed context
lastContext = from;
// set new context document
doc = from.ownerDocument || from;
if (force || oldDoc !== doc) {
// set document root
root = doc.documentElement;
// set host environment flags
XML_DOCUMENT = doc.createElement('DiV').nodeName == 'DiV';
// In quirks mode css class names are case insensitive.
// In standards mode they are case sensitive. See docs:
// https://developer.mozilla.org/en/Mozilla_Quirks_Mode_Behavior
// http://www.whatwg.org/specs/web-apps/current-work/#selectors
QUIRKS_MODE = !XML_DOCUMENT &&
typeof doc.compatMode == 'string' ?
doc.compatMode.indexOf('CSS') < 0 :
(function() {
var style = doc.createElement('div').style;
return style && (style.width = 1) && style.width == '1px';
})();
div = doc.createElement('div');
div.appendChild(doc.createElement('p')).setAttribute('class', 'xXx');
div.appendChild(doc.createElement('p')).setAttribute('class', 'xxx');
// GEBCN buggy in quirks mode, match count is:
// Firefox 3.0+ [xxx = 1, xXx = 1]
// Opera 10.63+ [xxx = 0, xXx = 2]
BUGGY_QUIRKS_GEBCN =
!XML_DOCUMENT && NATIVE_GEBCN && QUIRKS_MODE &&
(div.getElementsByClassName('xxx').length != 2 ||
div.getElementsByClassName('xXx').length != 2);
// QSAPI buggy in quirks mode, match count is:
// At least Chrome 4+, Firefox 3.5+, Opera 10.x+, Safari 4+ [xxx = 1, xXx = 2]
// Safari 3.2 QSA doesn't work with mixedcase in quirksmode [xxx = 1, xXx = 0]
// https://bugs.webkit.org/show_bug.cgi?id=19047
// must test the attribute selector '[class~=xxx]'
// before '.xXx' or the bug may not present itself
BUGGY_QUIRKS_QSAPI =
!XML_DOCUMENT && NATIVE_QSAPI && QUIRKS_MODE &&
(div.querySelectorAll('[class~=xxx]').length != 2 ||
div.querySelectorAll('.xXx').length != 2);
Config.CACHING && Dom.setCache(true, doc);
}
},
/*------------------------------ DOM METHODS -------------------------------*/
// element by id (raw)
// @return reference or null
byIdRaw =
function(id, elements) {
var i = -1, element = null;
while ((element = elements[++i])) {
if (element.getAttribute('id') == id) {
break;
}
}
return element;
},
// element by id
// @return reference or null
_byId = !BUGGY_GEBID ?
function(id, from) {
id = id.replace(/\\([^\\]{1})/g, '$1');
return from.getElementById && from.getElementById(id) ||
byIdRaw(id, from.getElementsByTagName('*'));
} :
function(id, from) {
var element = null;
id = id.replace(/\\([^\\]{1})/g, '$1');
if (XML_DOCUMENT || from.nodeType != 9) {
return byIdRaw(id, from.getElementsByTagName('*'));
}
if ((element = from.getElementById(id)) &&
element.name == id && from.getElementsByName) {
return byIdRaw(id, from.getElementsByName(id));
}
return element;
},
// publicly exposed byId
// @return reference or null
byId =
function(id, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byId(id, from);
},
// elements by tag (raw)
// @return array
byTagRaw =
function(tag, from) {
var any = tag == '*', element = from, elements = [ ], next = element.firstChild;
any || (tag = tag.toUpperCase());
while ((element = next)) {
if (element.tagName > '@' && (any || element.tagName.toUpperCase() == tag)) {
elements[elements.length] = element;
}
if ((next = element.firstChild || element.nextSibling)) continue;
while (!next && (element = element.parentNode) && element !== from) {
next = element.nextSibling;
}
}
return elements;
},
// elements by tag
// @return array
_byTag = !BUGGY_GEBTN && NATIVE_SLICE_PROTO ?
function(tag, from) {
return XML_DOCUMENT || from.nodeType == 11 ? byTagRaw(tag, from) :
slice.call(from.getElementsByTagName(tag), 0);
} :
function(tag, from) {
var i = -1, j = i, data = [ ],
element, elements = from.getElementsByTagName(tag);
if (tag == '*') {
while ((element = elements[++i])) {
if (element.nodeName > '@')
data[++j] = element;
}
} else {
while ((element = elements[++i])) {
data[i] = element;
}
}
return data;
},
// publicly exposed byTag
// @return array
byTag =
function(tag, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byTag(tag, from);
},
// publicly exposed byName
// @return array
byName =
function(name, from) {
return select('[name="' + name.replace(/\\([^\\]{1})/g, '$1') + '"]', from);
},
// elements by class (raw)
// @return array
byClassRaw =
function(name, from) {
var i = -1, j = i, data = [ ], element, elements = _byTag('*', from), n;
name = ' ' + (QUIRKS_MODE ? name.toLowerCase() : name).replace(/\\([^\\]{1})/g, '$1') + ' ';
while ((element = elements[++i])) {
n = XML_DOCUMENT ? element.getAttribute('class') : element.className;
if (n && n.length && (' ' + (QUIRKS_MODE ? n.toLowerCase() : n).
replace(reWhiteSpace, ' ') + ' ').indexOf(name) > -1) {
data[++j] = element;
}
}
return data;
},
// elements by class
// @return array
_byClass =
function(name, from) {
return (BUGGY_GEBCN || BUGGY_QUIRKS_GEBCN || XML_DOCUMENT || !from.getElementsByClassName) ?
byClassRaw(name, from) : slice.call(from.getElementsByClassName(name.replace(/\\([^\\]{1})/g, '$1')), 0);
},
// publicly exposed byClass
// @return array
byClass =
function(name, from) {
from || (from = doc);
if (lastContext !== from) { switchContext(from); }
return _byClass(name, from);
},
// check element is descendant of container
// @return boolean
contains = 'compareDocumentPosition' in root ?
function(container, element) {
return (container.compareDocumentPosition(element) & 16) == 16;
} : 'contains' in root ?
function(container, element) {
return container !== element && container.contains(element);
} :
function(container, element) {
while ((element = element.parentNode)) {
if (element === container) return true;
}
return false;
},
// attribute value
// @return string
getAttribute = !BUGGY_GET_ATTRIBUTE ?
function(node, attribute) {
return node.getAttribute(attribute) || '';
} :
function(node, attribute) {
attribute = attribute.toLowerCase();
if (typeof node[attribute] == 'object') {
return node.attributes[attribute] &&
node.attributes[attribute].value || '';
}
return (
// 'type' can only be read by using native getAttribute
attribute == 'type' ? node.getAttribute(attribute) || '' :
// specific URI data attributes (parameter 2 to fix IE bug)
ATTR_URIDATA[attribute] ? node.getAttribute(attribute, 2) || '' :
// boolean attributes should return name instead of true/false
ATTR_BOOLEAN[attribute] ? node.getAttribute(attribute) ? attribute : 'false' :
((node = node.getAttributeNode(attribute)) && node.value) || '');
},
// attribute presence
// @return boolean
hasAttribute = !BUGGY_HAS_ATTRIBUTE ?
function(node, attribute) {
return XML_DOCUMENT ?
!!node.getAttribute(attribute) :
node.hasAttribute(attribute);
} :
function(node, attribute) {
attribute = attribute.toLowerCase();
if (ATTR_DEFAULT[attribute]) {
return !!node[ATTR_DEFAULT[attribute]];
}
// read the attribute node
node = node.getAttributeNode(attribute);
return !!(node && node.specified);
},
// check node emptyness
// @return boolean
isEmpty =
function(node) {
node = node.firstChild;
while (node) {
if (node.nodeType == 3 || node.nodeName > '@') return false;
node = node.nextSibling;
}
return true;
},
// check if element matches the :link pseudo
// @return boolean
isLink =
function(element) {
return hasAttribute(element,'href') && LINK_NODES[element.nodeName];
},
// child position by nodeType
// @return number
nthElement =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling';
while ((element = element[succ])) {
if (element.nodeName > '@') ++count;
}
return count;
},
// child position by nodeName
// @return number
nthOfType =
function(element, last) {
var count = 1, succ = last ? 'nextSibling' : 'previousSibling', type = element.nodeName;
while ((element = element[succ])) {
if (element.nodeName == type) ++count;
}
return count;
},
/*------------------------------- DEBUGGING --------------------------------*/
// get/set (string/object) working modes
configure =
function(option) {
if (typeof option == 'string') { return Config[option]; }
if (typeof option != 'object') { return false; }
for (var i in option) {
Config[i] = !!option[i];
if (i == 'SIMPLENOT') {
matchContexts = { };
matchResolvers = { };
selectContexts = { };
selectResolvers = { };
Config['USE_QSAPI'] = false;
} else if (i == 'USE_QSAPI') {
Config[i] = !!option[i] && NATIVE_QSAPI;
}
}
reValidator = new global.RegExp(Config.SIMPLENOT ?
standardValidator : extendedValidator, 'g');
return true;
},
// control user notifications
emit =
function(message) {
if (Config.VERBOSITY) { throw new global.Error(message); }
if (global.console && global.console.log) {
global.console.log(message);
}
},
Config = {
// used to enable/disable caching of result sets
CACHING: false,
// by default do not add missing left/right context
// to selector string shortcuts like "+div" or "ul>"
// callable Dom.shortcuts method has to be available
SHORTCUTS: false,
// by default disable complex selectors nested in
// ':not()' pseudo-classes, as for specifications
SIMPLENOT: true,
// strict QSA match all non-unique IDs (false)
// speed & libs compat match unique ID (true)
UNIQUE_ID: true,
// HTML5 handling for the ":checked" pseudo-class
USE_HTML5: true,
// controls enabling the Query Selector API branch
USE_QSAPI: NATIVE_QSAPI,
// controls the engine error/warning notifications
VERBOSITY: true
},
/*---------------------------- COMPILER METHODS ----------------------------*/
// code string reused to build compiled functions
ACCEPT_NODE = 'r[r.length]=c[k];if(f&&false===f(c[k]))break main;else continue main;',
// compile a comma separated group of selector
// @mode boolean true for select, false for match
// return a compiled function
compile =
function(selector, source, mode) {
var parts = typeof selector == 'string' ? selector.match(reSplitGroup) : selector;
// ensures that source is a string
typeof source == 'string' || (source = '');
if (parts.length == 1) {
source += compileSelector(parts[0], mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
} else {
// for each selector in the group
var i = -1, seen = { }, token;
while ((token = parts[++i])) {
token = token.replace(reTrimSpaces, '');
// avoid repeating the same token
// in comma separated group (p, p)
if (!seen[token] && (seen[token] = true)) {
source += compileSelector(token, mode ? ACCEPT_NODE : 'f&&f(k);return true;', mode);
}
}
}
if (mode) {
// for select method
return new global.Function('c,s,r,d,h,g,f,v',
'var N,n,x=0,k=-1,e;main:while((e=c[++k])){' + source + '}return r;');
} else {
// for match method
return new global.Function('e,s,r,d,h,g,f,v',
'var N,n,x=0,k=e;' + source + 'return false;');
}
},
// allows to cache already visited nodes
FILTER =
'var z=v[@]||(v[@]=[]),l=z.length-1;' +
'while(l>=0&&z[l]!==e)--l;' +
'if(l!==-1){break;}' +
'z[z.length]=e;',
// compile a CSS3 string selector into ad-hoc javascript matching function
// @return string (to be compiled)
compileSelector =
function(selector, source, mode) {
var a, b, n, k = 0, expr, match, result, status, test, type;
while (selector) {
k++;
// *** Universal selector
// * match all (empty block, do not remove)
if ((match = selector.match(Patterns.universal))) {
// do nothing, handled in the compiler where
// BUGGY_GEBTN return comment nodes (ex: IE)
expr = '';
}
// *** ID selector
// #Foo Id case sensitive
else if ((match = selector.match(Patterns.id))) {
// document can contain conflicting elements (id/name)
// prototype selector unit need this method to recover bad HTML forms
source = 'if(' + (XML_DOCUMENT ?
's.getAttribute(e,"id")' :
'(e.submit?s.getAttribute(e,"id"):e.id)') +
'=="' + match[1] + '"' +
'){' + source + '}';
}
// *** Type selector
// Foo Tag (case insensitive)
else if ((match = selector.match(Patterns.tagName))) {
// both tagName and nodeName properties may be upper/lower case
// depending on their creation NAMESPACE in createElementNS()
source = 'if(e.nodeName' + (XML_DOCUMENT ?
'=="' + match[1] + '"' : '.toUpperCase()' +
'=="' + match[1].toUpperCase() + '"') +
'){' + source + '}';
}
// *** Class selector
// .Foo Class (case sensitive)
else if ((match = selector.match(Patterns.className))) {
// W3C CSS3 specs: element whose "class" attribute has been assigned a
// list of whitespace-separated values, see section 6.4 Class selectors
// and notes at the bottom; explicitly non-normative in this specification.
source = 'if((n=' + (XML_DOCUMENT ?
's.getAttribute(e,"class")' : 'e.className') +
')&&n.length&&(" "+' + (QUIRKS_MODE ? 'n.toLowerCase()' : 'n') +
'.replace(' + reWhiteSpace + '," ")+" ").indexOf(" ' +
(QUIRKS_MODE ? match[1].toLowerCase() : match[1]) + ' ")>-1' +
'){' + source + '}';
}
// *** Attribute selector
// [attr] [attr=value] [attr="value"] [attr='value'] and !=, *=, ~=, |=, ^=, $=
// case sensitivity is treated differently depending on the document type (see map)
else if ((match = selector.match(Patterns.attribute))) {
// xml namespaced attribute ?
expr = match[1].split(':');
expr = expr.length == 2 ? expr[1] : expr[0] + '';
if (match[2] && !Operators[match[2]]) {
emit('Unsupported operator in attribute selectors "' + selector + '"');
return '';
}
test = false;
type = 'false';
// replace Operators parameter if needed
if (match[2] && match[4] && (type = Operators[match[2]])) {
// case treatment depends on document
HTML_TABLE['class'] = QUIRKS_MODE ? 1 : 0;
// replace escaped values and HTML entities
match[4] = match[4].replace(/(\x22|\x27)/g, '\\$1');
match[4] = match[4].replace(/\\([0-9a-f]{2,2})/g, '\\x$1');
test = (XML_DOCUMENT ? XHTML_TABLE : HTML_TABLE)[expr.toLowerCase()];
type = type.replace(/\%m/g, test ? match[4].toLowerCase() : match[4]);
} else if (match[2] == '!=' || match[2] == '=') {
match[4] = match[4].replace(/(\x22|\x27)/g, '\\$1');