nwsapi.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807
  1. /*
  2. * Copyright (C) 2007-2019 Diego Perini
  3. * All rights reserved.
  4. *
  5. * nwsapi.js - Fast CSS Selectors API Engine
  6. *
  7. * Author: Diego Perini <diego.perini at gmail com>
  8. * Version: 2.2.0
  9. * Created: 20070722
  10. * Release: 20220901
  11. *
  12. * License:
  13. * http://javascript.nwbox.com/nwsapi/MIT-LICENSE
  14. * Download:
  15. * http://javascript.nwbox.com/nwsapi/nwsapi.js
  16. */
  17. (function Export(global, factory) {
  18. 'use strict';
  19. if (typeof module == 'object' && typeof exports == 'object') {
  20. module.exports = factory;
  21. } else if (typeof define == 'function' && define['amd']) {
  22. define(factory);
  23. } else {
  24. global.NW || (global.NW = { });
  25. global.NW.Dom = factory(global, Export);
  26. }
  27. })(this, function Factory(global, Export) {
  28. var version = 'nwsapi-2.2.2',
  29. doc = global.document,
  30. root = doc.documentElement,
  31. slice = Array.prototype.slice,
  32. WSP = '[\\x20\\t\\r\\n\\f]',
  33. CFG = {
  34. // extensions
  35. operators: '[~*^$|]=|=',
  36. combinators: '[\\x20\\t>+~](?=[^>+~])'
  37. },
  38. NOT = {
  39. // not enclosed in double/single/parens/square
  40. double_enc: '(?=(?:[^"]*["][^"]*["])*[^"]*$)',
  41. single_enc: "(?=(?:[^']*['][^']*['])*[^']*$)",
  42. parens_enc: '(?![^\\x28]*\\x29)',
  43. square_enc: '(?![^\\x5b]*\\x5d)'
  44. },
  45. REX = {
  46. // regular expressions
  47. HasEscapes: RegExp('\\\\'),
  48. HexNumbers: RegExp('^[0-9a-fA-F]'),
  49. EscOrQuote: RegExp('^\\\\|[\\x22\\x27]'),
  50. RegExpChar: RegExp('(?:(?!\\\\)[\\\\^$.*+?()[\\]{}|\\/])', 'g'),
  51. TrimSpaces: RegExp('[\\r\\n\\f]|^' + WSP + '+|' + WSP + '+$', 'g'),
  52. CommaGroup: RegExp('(\\s*,\\s*)' + NOT.square_enc + NOT.parens_enc, 'g'),
  53. SplitGroup: RegExp('((?:\\x28[^\\x29]*\\x29|\\[[^\\]]*\\]|\\\\.|[^,])+)', 'g'),
  54. FixEscapes: RegExp('\\\\([0-9a-fA-F]{1,6}' + WSP + '?|.)|([\\x22\\x27])', 'g'),
  55. CombineWSP: RegExp('[\\n\\r\\f\\x20]+' + NOT.single_enc + NOT.double_enc, 'g'),
  56. TabCharWSP: RegExp('(\\x20?\\t+\\x20?)' + NOT.single_enc + NOT.double_enc, 'g'),
  57. PseudosWSP: RegExp('\\s+([-+])\\s+' + NOT.square_enc, 'g')
  58. },
  59. STD = {
  60. combinator: RegExp('\\s?([>+~])\\s?', 'g'),
  61. apimethods: RegExp('^(?:[a-z]+|\\*)\\|', 'i'),
  62. namespaces: RegExp('(\\*|[a-z]+)\\|[-a-z]+', 'i')
  63. },
  64. GROUPS = {
  65. // pseudo-classes requiring parameters
  66. linguistic: '(dir|lang)\\x28\\s?([-\\w]{2,})\\s?(?:\\x29|$)',
  67. logicalsel: '(is|where|matches|not)\\x28\\s?([^()]*|[^\\x28]*\\x28[^\\x29]*\\x29)\\s?(?:\\x29|$)',
  68. treestruct: '(nth(?:-last)?(?:-child|-of-type))(?:\\x28\\s?(even|odd|(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)?)\\s?(?:\\x29|$))',
  69. // pseudo-classes not requiring parameters
  70. locationpc: '(any-link|link|visited|target)\\b',
  71. useraction: '(hover|active|focus|focus-within)\\b',
  72. structural: '(root|empty|(?:(?:first|last|only)(?:-child|-of-type)))\\b',
  73. inputstate: '(enabled|disabled|read-only|read-write|placeholder-shown|default)\\b',
  74. inputvalue: '(checked|indeterminate|required|optional|valid|invalid|in-range|out-of-range)\\b',
  75. // pseudo-classes for parsing only selectors
  76. pseudo_nop: '(autofill|-webkit-autofill)\\b',
  77. // pseudo-elements starting with single colon (:)
  78. pseudo_sng: '(after|before|first-letter|first-line)\\b',
  79. // pseudo-elements starting with double colon (::)
  80. pseudo_dbl: ':(after|before|first-letter|first-line|selection|placeholder|-webkit-[-a-zA-Z0-9]{2,})\\b'
  81. },
  82. Patterns = {
  83. // pseudo-classes
  84. treestruct: RegExp('^:(?:' + GROUPS.treestruct + ')(.*)', 'i'),
  85. structural: RegExp('^:(?:' + GROUPS.structural + ')(.*)', 'i'),
  86. linguistic: RegExp('^:(?:' + GROUPS.linguistic + ')(.*)', 'i'),
  87. useraction: RegExp('^:(?:' + GROUPS.useraction + ')(.*)', 'i'),
  88. inputstate: RegExp('^:(?:' + GROUPS.inputstate + ')(.*)', 'i'),
  89. inputvalue: RegExp('^:(?:' + GROUPS.inputvalue + ')(.*)', 'i'),
  90. locationpc: RegExp('^:(?:' + GROUPS.locationpc + ')(.*)', 'i'),
  91. logicalsel: RegExp('^:(?:' + GROUPS.logicalsel + ')(.*)', 'i'),
  92. pseudo_nop: RegExp('^:(?:' + GROUPS.pseudo_nop + ')(.*)', 'i'),
  93. pseudo_sng: RegExp('^:(?:' + GROUPS.pseudo_sng + ')(.*)', 'i'),
  94. pseudo_dbl: RegExp('^:(?:' + GROUPS.pseudo_dbl + ')(.*)', 'i'),
  95. // combinator symbols
  96. children: RegExp('^' + WSP + '?\\>' + WSP + '?(.*)'),
  97. adjacent: RegExp('^' + WSP + '?\\+' + WSP + '?(.*)'),
  98. relative: RegExp('^' + WSP + '?\\~' + WSP + '?(.*)'),
  99. ancestor: RegExp('^' + WSP + '+(.*)'),
  100. // universal & namespace
  101. universal: RegExp('^\\*(.*)'),
  102. namespace: RegExp('^(\\w+|\\*)?\\|(.*)')
  103. },
  104. // regexp to aproximate detection of RTL languages (Arabic)
  105. RTL = RegExp('^[\\u0591-\\u08ff\\ufb1d-\\ufdfd\\ufe70-\\ufefc ]+$'),
  106. // emulate firefox error strings
  107. qsNotArgs = 'Not enough arguments',
  108. qsInvalid = ' is not a valid selector',
  109. // detect structural pseudo-classes in selectors
  110. reNthElem = RegExp('(:nth(?:-last)?-child)', 'i'),
  111. reNthType = RegExp('(:nth(?:-last)?-of-type)', 'i'),
  112. // placeholder for global regexp
  113. reOptimizer,
  114. reValidator,
  115. // special handling configuration flags
  116. Config = {
  117. IDS_DUPES: true,
  118. MIXEDCASE: true,
  119. LOGERRORS: true,
  120. VERBOSITY: true
  121. },
  122. NAMESPACE,
  123. QUIRKS_MODE,
  124. HTML_DOCUMENT,
  125. ATTR_STD_OPS = {
  126. '=': 1, '^=': 1, '$=': 1, '|=': 1, '*=': 1, '~=': 1
  127. },
  128. HTML_TABLE = {
  129. 'accept': 1, 'accept-charset': 1, 'align': 1, 'alink': 1, 'axis': 1,
  130. 'bgcolor': 1, 'charset': 1, 'checked': 1, 'clear': 1, 'codetype': 1, 'color': 1,
  131. 'compact': 1, 'declare': 1, 'defer': 1, 'dir': 1, 'direction': 1, 'disabled': 1,
  132. 'enctype': 1, 'face': 1, 'frame': 1, 'hreflang': 1, 'http-equiv': 1, 'lang': 1,
  133. 'language': 1, 'link': 1, 'media': 1, 'method': 1, 'multiple': 1, 'nohref': 1,
  134. 'noresize': 1, 'noshade': 1, 'nowrap': 1, 'readonly': 1, 'rel': 1, 'rev': 1,
  135. 'rules': 1, 'scope': 1, 'scrolling': 1, 'selected': 1, 'shape': 1, 'target': 1,
  136. 'text': 1, 'type': 1, 'valign': 1, 'valuetype': 1, 'vlink': 1
  137. },
  138. Combinators = { },
  139. Selectors = { },
  140. Operators = {
  141. '=': { p1: '^',
  142. p2: '$',
  143. p3: 'true' },
  144. '^=': { p1: '^',
  145. p2: '',
  146. p3: 'true' },
  147. '$=': { p1: '',
  148. p2: '$',
  149. p3: 'true' },
  150. '*=': { p1: '',
  151. p2: '',
  152. p3: 'true' },
  153. '|=': { p1: '^',
  154. p2: '(-|$)',
  155. p3: 'true' },
  156. '~=': { p1: '(^|\\s)',
  157. p2: '(\\s|$)',
  158. p3: 'true' }
  159. },
  160. concatCall =
  161. function(nodes, callback) {
  162. var i = 0, l = nodes.length, list = Array(l);
  163. while (l > i) {
  164. if (false === callback(list[i] = nodes[i])) break;
  165. ++i;
  166. }
  167. return list;
  168. },
  169. concatList =
  170. function(list, nodes) {
  171. var i = -1, l = nodes.length;
  172. while (l--) { list[list.length] = nodes[++i]; }
  173. return list;
  174. },
  175. documentOrder =
  176. function(a, b) {
  177. if (!hasDupes && a === b) {
  178. hasDupes = true;
  179. return 0;
  180. }
  181. return a.compareDocumentPosition(b) & 4 ? -1 : 1;
  182. },
  183. hasDupes = false,
  184. unique =
  185. function(nodes) {
  186. var i = 0, j = -1, l = nodes.length + 1, list = [ ];
  187. while (--l) {
  188. if (nodes[i++] === nodes[i]) continue;
  189. list[++j] = nodes[i - 1];
  190. }
  191. hasDupes = false;
  192. return list;
  193. },
  194. // check context for mixed content
  195. hasMixedCaseTagNames =
  196. function(context) {
  197. var ns, api = 'getElementsByTagNameNS';
  198. // current host context (ownerDocument)
  199. context = context.ownerDocument || context;
  200. // documentElement (root) element namespace or default html/xhtml namespace
  201. ns = context.documentElement.namespaceURI || 'http://www.w3.org/1999/xhtml';
  202. // checking the number of non HTML nodes in the document
  203. return (context[api]('*', '*').length - context[api](ns, '*').length) > 0;
  204. },
  205. switchContext =
  206. function(context, force) {
  207. var oldDoc = doc;
  208. doc = context.ownerDocument || context;
  209. if (force || oldDoc !== doc) {
  210. // force a new check for each document change
  211. // performed before the next select operation
  212. root = doc.documentElement;
  213. HTML_DOCUMENT = isHTML(doc);
  214. QUIRKS_MODE = HTML_DOCUMENT &&
  215. doc.compatMode.indexOf('CSS') < 0;
  216. NAMESPACE = root && root.namespaceURI;
  217. Snapshot.doc = doc;
  218. Snapshot.root = root;
  219. }
  220. return (Snapshot.from = context);
  221. },
  222. // convert single codepoint to UTF-16 encoding
  223. codePointToUTF16 =
  224. function(codePoint) {
  225. // out of range, use replacement character
  226. if (codePoint < 1 || codePoint > 0x10ffff ||
  227. (codePoint > 0xd7ff && codePoint < 0xe000)) {
  228. return '\\ufffd';
  229. }
  230. // javascript strings are UTF-16 encoded
  231. if (codePoint < 0x10000) {
  232. var lowHex = '000' + codePoint.toString(16);
  233. return '\\u' + lowHex.substr(lowHex.length - 4);
  234. }
  235. // supplementary high + low surrogates
  236. return '\\u' + (((codePoint - 0x10000) >> 0x0a) + 0xd800).toString(16) +
  237. '\\u' + (((codePoint - 0x10000) % 0x400) + 0xdc00).toString(16);
  238. },
  239. // convert single codepoint to string
  240. stringFromCodePoint =
  241. function(codePoint) {
  242. // out of range, use replacement character
  243. if (codePoint < 1 || codePoint > 0x10ffff ||
  244. (codePoint > 0xd7ff && codePoint < 0xe000)) {
  245. return '\ufffd';
  246. }
  247. if (codePoint < 0x10000) {
  248. return String.fromCharCode(codePoint);
  249. }
  250. return String.fromCodePoint ?
  251. String.fromCodePoint(codePoint) :
  252. String.fromCharCode(
  253. ((codePoint - 0x10000) >> 0x0a) + 0xd800,
  254. ((codePoint - 0x10000) % 0x400) + 0xdc00);
  255. },
  256. // convert escape sequence in a CSS string or identifier
  257. // to javascript string with javascript escape sequences
  258. convertEscapes =
  259. function(str) {
  260. return REX.HasEscapes.test(str) ?
  261. str.replace(REX.FixEscapes,
  262. function(substring, p1, p2) {
  263. // unescaped " or '
  264. return p2 ? '\\' + p2 :
  265. // javascript strings are UTF-16 encoded
  266. REX.HexNumbers.test(p1) ? codePointToUTF16(parseInt(p1, 16)) :
  267. // \' \"
  268. REX.EscOrQuote.test(p1) ? substring :
  269. // \g \h \. \# etc
  270. p1;
  271. }
  272. ) : str;
  273. },
  274. // convert escape sequence in a CSS string or identifier
  275. // to javascript string with characters representations
  276. unescapeIdentifier =
  277. function(str) {
  278. return REX.HasEscapes.test(str) ?
  279. str.replace(REX.FixEscapes,
  280. function(substring, p1, p2) {
  281. // unescaped " or '
  282. return p2 ? p2 :
  283. // javascript strings are UTF-16 encoded
  284. REX.HexNumbers.test(p1) ? stringFromCodePoint(parseInt(p1, 16)) :
  285. // \' \"
  286. REX.EscOrQuote.test(p1) ? substring :
  287. // \g \h \. \# etc
  288. p1;
  289. }
  290. ) : str;
  291. },
  292. method = {
  293. '#': 'getElementById',
  294. '*': 'getElementsByTagName',
  295. '|': 'getElementsByTagNameNS',
  296. '.': 'getElementsByClassName'
  297. },
  298. compat = {
  299. '#': function(c, n) { REX.HasEscapes.test(n) && (n = unescapeIdentifier(n)); return function(e, f) { return byId(n, c); }; },
  300. '*': function(c, n) { REX.HasEscapes.test(n) && (n = unescapeIdentifier(n)); return function(e, f) { return byTag(n, c); }; },
  301. '|': function(c, n) { REX.HasEscapes.test(n) && (n = unescapeIdentifier(n)); return function(e, f) { return byTag(n, c); }; },
  302. '.': function(c, n) { REX.HasEscapes.test(n) && (n = unescapeIdentifier(n)); return function(e, f) { return byClass(n, c); }; }
  303. },
  304. // find duplicate ids using iterative walk
  305. byIdRaw =
  306. function(id, context) {
  307. var node = context, nodes = [ ], next = node.firstElementChild;
  308. while ((node = next)) {
  309. node.id == id && (nodes[nodes.length] = node);
  310. if ((next = node.firstElementChild || node.nextElementSibling)) continue;
  311. while (!next && (node = node.parentElement) && node !== context) {
  312. next = node.nextElementSibling;
  313. }
  314. }
  315. return nodes;
  316. },
  317. // context agnostic getElementById
  318. byId =
  319. function(id, context) {
  320. var e, nodes, api = method['#'];
  321. // duplicates id allowed
  322. if (Config.IDS_DUPES === false) {
  323. if (api in context) {
  324. return (e = context[api](id)) ? [ e ] : none;
  325. }
  326. } else {
  327. if ('all' in context) {
  328. if ((e = context.all[id])) {
  329. if (e.nodeType == 1) return e.getAttribute('id') != id ? [ ] : [ e ];
  330. else if (id == 'length') return (e = context[api](id)) ? [ e ] : none;
  331. for (i = 0, l = e.length, nodes = [ ]; l > i; ++i) {
  332. if (e[i].id == id) nodes[nodes.length] = e[i];
  333. }
  334. return nodes && nodes.length ? nodes : [ nodes ];
  335. } else return none;
  336. }
  337. }
  338. return byIdRaw(id, context);
  339. },
  340. // context agnostic getElementsByTagName
  341. byTag =
  342. function(tag, context) {
  343. var e, nodes, api = method['*'];
  344. // DOCUMENT_NODE (9) & ELEMENT_NODE (1)
  345. if (api in context) {
  346. return slice.call(context[api](tag));
  347. } else {
  348. tag = tag.toLowerCase();
  349. // DOCUMENT_FRAGMENT_NODE (11)
  350. if ((e = context.firstElementChild)) {
  351. if (!(e.nextElementSibling || tag == '*' || e.localName == tag)) {
  352. return slice.call(e[api](tag));
  353. } else {
  354. nodes = [ ];
  355. do {
  356. if (tag == '*' || e.localName == tag) nodes[nodes.length] = e;
  357. concatList(nodes, e[api](tag));
  358. } while ((e = e.nextElementSibling));
  359. }
  360. } else nodes = none;
  361. }
  362. return nodes;
  363. },
  364. // context agnostic getElementsByClassName
  365. byClass =
  366. function(cls, context) {
  367. var e, nodes, api = method['.'], reCls;
  368. // DOCUMENT_NODE (9) & ELEMENT_NODE (1)
  369. if (api in context) {
  370. return slice.call(context[api](cls));
  371. } else {
  372. // DOCUMENT_FRAGMENT_NODE (11)
  373. if ((e = context.firstElementChild)) {
  374. reCls = RegExp('(^|\\s)' + cls + '(\\s|$)', QUIRKS_MODE ? 'i' : '');
  375. if (!(e.nextElementSibling || reCls.test(e.className))) {
  376. return slice.call(e[api](cls));
  377. } else {
  378. nodes = [ ];
  379. do {
  380. if (reCls.test(e.className)) nodes[nodes.length] = e;
  381. concatList(nodes, e[api](cls));
  382. } while ((e = e.nextElementSibling));
  383. }
  384. } else nodes = none;
  385. }
  386. return nodes;
  387. },
  388. // namespace aware hasAttribute
  389. // helper for XML/XHTML documents
  390. hasAttributeNS =
  391. function(e, name) {
  392. var i, l, attr = e.getAttributeNames();
  393. name = RegExp(':?' + name + '$', HTML_DOCUMENT ? 'i' : '');
  394. for (i = 0, l = attr.length; l > i; ++i) {
  395. if (name.test(attr[i])) return true;
  396. }
  397. return false;
  398. },
  399. // fast resolver for the :nth-child() and :nth-last-child() pseudo-classes
  400. nthElement = (function() {
  401. var idx = 0, len = 0, set = 0, parent = undefined, parents = Array(), nodes = Array();
  402. return function(element, dir) {
  403. // ensure caches are emptied after each run, invoking with dir = 2
  404. if (dir == 2) {
  405. idx = 0; len = 0; set = 0; nodes.length = 0;
  406. parents.length = 0; parent = undefined;
  407. return -1;
  408. }
  409. var e, i, j, k, l;
  410. if (parent === element.parentElement) {
  411. i = set; j = idx; l = len;
  412. } else {
  413. l = parents.length;
  414. parent = element.parentElement;
  415. for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) {
  416. if (parents[j] === parent) { i = j; break; }
  417. if (parents[k] === parent) { i = k; break; }
  418. }
  419. if (i < 0) {
  420. parents[i = l] = parent;
  421. l = 0; nodes[i] = Array();
  422. e = parent && parent.firstElementChild || element;
  423. while (e) { nodes[i][l] = e; if (e === element) j = l; e = e.nextElementSibling; ++l; }
  424. set = i; idx = 0; len = l;
  425. if (l < 2) return l;
  426. } else {
  427. l = nodes[i].length;
  428. set = i;
  429. }
  430. }
  431. if (element !== nodes[i][j] && element !== nodes[i][j = 0]) {
  432. for (j = 0, e = nodes[i], k = l - 1; l > j; ++j, --k) {
  433. if (e[j] === element) { break; }
  434. if (e[k] === element) { j = k; break; }
  435. }
  436. }
  437. idx = j + 1; len = l;
  438. return dir ? l - j : idx;
  439. };
  440. })(),
  441. // fast resolver for the :nth-of-type() and :nth-last-of-type() pseudo-classes
  442. nthOfType = (function() {
  443. var idx = 0, len = 0, set = 0, parent = undefined, parents = Array(), nodes = Array();
  444. return function(element, dir) {
  445. // ensure caches are emptied after each run, invoking with dir = 2
  446. if (dir == 2) {
  447. idx = 0; len = 0; set = 0; nodes.length = 0;
  448. parents.length = 0; parent = undefined;
  449. return -1;
  450. }
  451. var e, i, j, k, l, name = element.localName;
  452. if (nodes[set] && nodes[set][name] && parent === element.parentElement) {
  453. i = set; j = idx; l = len;
  454. } else {
  455. l = parents.length;
  456. parent = element.parentElement;
  457. for (i = -1, j = 0, k = l - 1; l > j; ++j, --k) {
  458. if (parents[j] === parent) { i = j; break; }
  459. if (parents[k] === parent) { i = k; break; }
  460. }
  461. if (i < 0 || !nodes[i][name]) {
  462. parents[i = l] = parent;
  463. nodes[i] || (nodes[i] = Object());
  464. l = 0; nodes[i][name] = Array();
  465. e = parent && parent.firstElementChild || element;
  466. while (e) { if (e === element) j = l; if (e.localName == name) { nodes[i][name][l] = e; ++l; } e = e.nextElementSibling; }
  467. set = i; idx = j; len = l;
  468. if (l < 2) return l;
  469. } else {
  470. l = nodes[i][name].length;
  471. set = i;
  472. }
  473. }
  474. if (element !== nodes[i][name][j] && element !== nodes[i][name][j = 0]) {
  475. for (j = 0, e = nodes[i][name], k = l - 1; l > j; ++j, --k) {
  476. if (e[j] === element) { break; }
  477. if (e[k] === element) { j = k; break; }
  478. }
  479. }
  480. idx = j + 1; len = l;
  481. return dir ? l - j : idx;
  482. };
  483. })(),
  484. // check if the document type is HTML
  485. isHTML =
  486. function(node) {
  487. var doc = node.ownerDocument || node;
  488. return doc.nodeType == 9 &&
  489. // contentType not in IE <= 11
  490. 'contentType' in doc ?
  491. doc.contentType.indexOf('/html') > 0 :
  492. doc.createElement('DiV').localName == 'div';
  493. },
  494. // configure the engine to use special handling
  495. configure =
  496. function(option, clear) {
  497. if (typeof option == 'string') { return !!Config[option]; }
  498. if (typeof option != 'object') { return Config; }
  499. for (var i in option) {
  500. Config[i] = !!option[i];
  501. }
  502. // clear lambda cache
  503. if (clear) {
  504. matchResolvers = { };
  505. selectResolvers = { };
  506. }
  507. setIdentifierSyntax();
  508. return true;
  509. },
  510. // centralized error and exceptions handling
  511. emit =
  512. function(message, proto) {
  513. var err;
  514. if (Config.VERBOSITY) {
  515. if (proto) {
  516. err = new proto(message);
  517. } else {
  518. err = new global.DOMException(message, 'SyntaxError');
  519. }
  520. throw err;
  521. }
  522. if (Config.LOGERRORS && console && console.log) {
  523. console.log(message);
  524. }
  525. },
  526. // execute the engine initialization code
  527. initialize =
  528. function(doc) {
  529. setIdentifierSyntax();
  530. lastContext = switchContext(doc, true);
  531. },
  532. // build validation regexps used by the engine
  533. setIdentifierSyntax =
  534. function() {
  535. //
  536. // NOTE: SPECIAL CASES IN CSS SYNTAX PARSING RULES
  537. //
  538. // The <EOF-token> https://drafts.csswg.org/css-syntax/#typedef-eof-token
  539. // allow mangled|unclosed selector syntax at the end of selectors strings
  540. //
  541. // Literal equivalent hex representations of the characters: " ' ` ] )
  542. //
  543. // \\x22 = " - double quotes \\x5b = [ - open square bracket
  544. // \\x27 = ' - single quote \\x5d = ] - closed square bracket
  545. // \\x60 = ` - back tick \\x28 = ( - open round parens
  546. // \\x5c = \ - back slash \\x29 = ) - closed round parens
  547. //
  548. // using hex format prevents false matches of opened/closed instances
  549. // pairs, coloring breakage and other editors highlightning problems.
  550. //
  551. var identifier =
  552. // doesn't start with a digit
  553. '(?=[^0-9])' +
  554. // can start with double dash
  555. '(?:-{2}' +
  556. // may include ascii chars
  557. '|[a-zA-Z0-9-_]' +
  558. // non-ascii chars
  559. '|[^\\x00-\\x9f]' +
  560. // escaped chars
  561. '|\\\\[^\\r\\n\\f0-9a-fA-F]' +
  562. // unicode chars
  563. '|\\\\[0-9a-fA-F]{1,6}(?:\\r\\n|\\s)?' +
  564. // any escaped chars
  565. '|\\\\.' +
  566. ')+',
  567. pseudonames = '[-\\w]+',
  568. pseudoparms = '(?:[-+]?\\d*)(?:n\\s?[-+]?\\s?\\d*)',
  569. doublequote = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*(?:"|$)',
  570. singlequote = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*(?:'|$)",
  571. attrparser = identifier + '|' + doublequote + '|' + singlequote,
  572. attrvalues = '([\\x22\\x27]?)((?!\\3)*|(?:\\\\?.)*?)(?:\\3|$)',
  573. attributes =
  574. '\\[' +
  575. // attribute presence
  576. '(?:\\*\\|)?' +
  577. WSP + '?' +
  578. '(' + identifier + '(?::' + identifier + ')?)' +
  579. WSP + '?' +
  580. '(?:' +
  581. '(' + CFG.operators + ')' + WSP + '?' +
  582. '(?:' + attrparser + ')' +
  583. ')?' +
  584. // attribute case sensitivity
  585. '(?:' + WSP + '?\\b(i))?' + WSP + '?' +
  586. '(?:\\]|$)',
  587. attrmatcher = attributes.replace(attrparser, attrvalues),
  588. pseudoclass =
  589. '(?:\\x28' + WSP + '*' +
  590. '(?:' + pseudoparms + '?)?|' +
  591. // universal * &
  592. // namespace *|*
  593. '(?:\\*|\\|)|' +
  594. '(?:' +
  595. '(?::' + pseudonames +
  596. '(?:\\x28' + pseudoparms + '?(?:\\x29|$))?|' +
  597. ')|' +
  598. '(?:[.#]?' + identifier + ')|' +
  599. '(?:' + attributes + ')' +
  600. ')+|' +
  601. '(?:' + WSP + '?,' + WSP + '?)|' +
  602. '(?:' + WSP + '?)|' +
  603. '(?:\\x29|$))*',
  604. standardValidator =
  605. '(?=' + WSP + '?[^>+~(){}<>])' +
  606. '(?:' +
  607. // universal * &
  608. // namespace *|*
  609. '(?:\\*|\\|)|' +
  610. '(?:[.#]?' + identifier + ')+|' +
  611. '(?:' + attributes + ')+|' +
  612. '(?:::?' + pseudonames + pseudoclass + ')|' +
  613. '(?:' + WSP + '?' + CFG.combinators + WSP + '?)|' +
  614. '(?:' + WSP + '?,' + WSP + '?)|' +
  615. '(?:' + WSP + '?)' +
  616. ')+';
  617. // the following global RE is used to return the
  618. // deepest localName in selector strings and then
  619. // use it to retrieve all possible matching nodes
  620. // that will be filtered by compiled resolvers
  621. reOptimizer = RegExp(
  622. '(?:([.:#*]?)' +
  623. '(' + identifier + ')' +
  624. '(?:' +
  625. ':[-\\w]+|' +
  626. '\\[[^\\]]+(?:\\]|$)|' +
  627. '\\x28[^\\x29]+(?:\\x29|$)' +
  628. ')*)$');
  629. // global
  630. reValidator = RegExp(standardValidator, 'g');
  631. Patterns.id = RegExp('^#(' + identifier + ')(.*)');
  632. Patterns.tagName = RegExp('^(' + identifier + ')(.*)');
  633. Patterns.className = RegExp('^\\.(' + identifier + ')(.*)');
  634. Patterns.attribute = RegExp('^(?:' + attrmatcher + ')(.*)');
  635. },
  636. F_INIT = '"use strict";return function Resolver(c,f,x,r)',
  637. S_HEAD = 'var e,n,o,j=r.length-1,k=-1',
  638. M_HEAD = 'var e,n,o',
  639. S_LOOP = 'main:while((e=c[++k]))',
  640. N_LOOP = 'main:while((e=c.item(++k)))',
  641. M_LOOP = 'e=c;',
  642. S_BODY = 'r[++j]=c[k];',
  643. N_BODY = 'r[++j]=c.item(k);',
  644. M_BODY = '',
  645. S_TAIL = 'continue main;',
  646. M_TAIL = 'r=true;',
  647. S_TEST = 'if(f(c[k])){break main;}',
  648. N_TEST = 'if(f(c.item(k))){break main;}',
  649. M_TEST = 'f(c);',
  650. S_VARS = [ ],
  651. M_VARS = [ ],
  652. // compile groups or single selector strings into
  653. // executable functions for matching or selecting
  654. compile =
  655. function(selector, mode, callback) {
  656. var factory, token, head = '', loop = '', macro = '', source = '', vars = '';
  657. // 'mode' can be boolean or null
  658. // true = select / false = match
  659. // null to use collection.item()
  660. switch (mode) {
  661. case true:
  662. if (selectLambdas[selector]) { return selectLambdas[selector]; }
  663. macro = S_BODY + (callback ? S_TEST : '') + S_TAIL;
  664. head = S_HEAD;
  665. loop = S_LOOP;
  666. break;
  667. case false:
  668. if (matchLambdas[selector]) { return matchLambdas[selector]; }
  669. macro = M_BODY + (callback ? M_TEST : '') + M_TAIL;
  670. head = M_HEAD;
  671. loop = M_LOOP;
  672. break;
  673. case null:
  674. if (selectLambdas[selector]) { return selectLambdas[selector]; }
  675. macro = N_BODY + (callback ? N_TEST : '') + S_TAIL;
  676. head = S_HEAD;
  677. loop = N_LOOP;
  678. break;
  679. default:
  680. break;
  681. }
  682. source = compileSelector(selector, macro, mode, callback);
  683. loop += mode || mode === null ? '{' + source + '}' : source;
  684. if (mode || mode === null && selector.includes(':nth')) {
  685. loop += reNthElem.test(selector) ? 's.nthElement(null, 2);' : '';
  686. loop += reNthType.test(selector) ? 's.nthOfType(null, 2);' : '';
  687. }
  688. if (S_VARS[0] || M_VARS[0]) {
  689. vars = ',' + (S_VARS.join(',') || M_VARS.join(','));
  690. S_VARS.length = 0;
  691. M_VARS.length = 0;
  692. }
  693. factory = Function('s', F_INIT + '{' + head + vars + ';' + loop + 'return r;}')(Snapshot);
  694. return mode || mode === null ? (selectLambdas[selector] = factory) : (matchLambdas[selector] = factory);
  695. },
  696. // build conditional code to check components of selector strings
  697. compileSelector =
  698. function(expression, source, mode, callback) {
  699. // N is the negation pseudo-class flag
  700. // D is the default inverted negation flag
  701. var a, b, n, f, i, l, name, NS, N = '', D = '!',
  702. compat, expr, match, result, status, symbol, test,
  703. type, selector = expression, selector_string, vars;
  704. // original 'select' or 'match' selector string before normalization
  705. selector_string = mode ? lastSelected : lastMatched;
  706. // isolate selector combinators/components and normalize whitespace
  707. selector = selector.replace(STD.combinator, '$1');//.replace(STD.whitespace, ' ');
  708. // javascript needs a label to break
  709. // out of the while loops processing
  710. selector_recursion_label:
  711. while (selector) {
  712. // get namespace prefix if present or get first char of selector
  713. symbol = STD.apimethods.test(selector) ? '|' : selector[0];
  714. switch (symbol) {
  715. // universal resolver
  716. case '*':
  717. match = selector.match(Patterns.universal);
  718. if (N == '!') {
  719. source = 'if(' + N + 'true' +
  720. '){' + source + '}';
  721. }
  722. break;
  723. // id resolver
  724. case '#':
  725. match = selector.match(Patterns.id);
  726. source = 'if(' + N + '(/^' + match[1] + '$/.test(e.getAttribute("id"))' +
  727. ')){' + source + '}';
  728. break;
  729. // class name resolver
  730. case '.':
  731. match = selector.match(Patterns.className);
  732. compat = (QUIRKS_MODE ? 'i' : '') + '.test(e.getAttribute("class"))';
  733. source = 'if(' + N + '(/(^|\\s)' + match[1] + '(\\s|$)/' + compat +
  734. ')){' + source + '}';
  735. break;
  736. // tag name resolver
  737. case (/[_a-z]/i.test(symbol) ? symbol : undefined):
  738. match = selector.match(Patterns.tagName);
  739. source = 'if(' + N + '(e.localName' +
  740. (Config.MIXEDCASE || hasMixedCaseTagNames(doc) ?
  741. '=="' + match[1].toLowerCase() + '"' :
  742. '=="' + match[1].toUpperCase() + '"') +
  743. ')){' + source + '}';
  744. break;
  745. // namespace resolver
  746. case '|':
  747. match = selector.match(Patterns.namespace);
  748. if (match[1] == '*') {
  749. source = 'if(' + N + 'true){' + source + '}';
  750. } else if (!match[1]) {
  751. source = 'if(' + N + '(!e.namespaceURI)){' + source + '}';
  752. } else if (typeof match[1] == 'string' && root.prefix == match[1]) {
  753. source = 'if(' + N + '(e.namespaceURI=="' + NAMESPACE + '")){' + source + '}';
  754. } else {
  755. emit('\'' + selector_string + '\'' + qsInvalid);
  756. }
  757. break;
  758. // attributes resolver
  759. case '[':
  760. match = selector.match(Patterns.attribute);
  761. NS = match[0].match(STD.namespaces);
  762. name = match[1];
  763. expr = name.split(':');
  764. expr = expr.length == 2 ? expr[1] : expr[0];
  765. if (match[2] && !(test = Operators[match[2]])) {
  766. emit('\'' + selector_string + '\'' + qsInvalid);
  767. return '';
  768. }
  769. if (match[4] === '') {
  770. test = match[2] == '~=' ?
  771. { p1: '^\\s', p2: '+$', p3: 'true' } :
  772. match[2] in ATTR_STD_OPS && match[2] != '~=' ?
  773. { p1: '^', p2: '$', p3: 'true' } : test;
  774. } else if (match[2] == '~=' && match[4].includes(' ')) {
  775. // whitespace separated list but value contains space
  776. source = 'if(' + N + 'false){' + source + '}';
  777. break;
  778. } else if (match[4]) {
  779. match[4] = convertEscapes(match[4]).replace(REX.RegExpChar, '\\$&');
  780. }
  781. type = match[5] == 'i' || (HTML_DOCUMENT && HTML_TABLE[expr.toLowerCase()]) ? 'i' : '';
  782. source = 'if(' + N + '(' +
  783. (!match[2] ? (NS ? 's.hasAttributeNS(e,"' + name + '")' : 'e.hasAttribute&&e.hasAttribute("' + name + '")') :
  784. !match[4] && ATTR_STD_OPS[match[2]] && match[2] != '~=' ? 'e.getAttribute&&e.getAttribute("' + name + '")==""' :
  785. '(/' + test.p1 + match[4] + test.p2 + '/' + type + ').test(e.getAttribute&&e.getAttribute("' + name + '"))==' + test.p3) +
  786. ')){' + source + '}';
  787. break;
  788. // *** General sibling combinator
  789. // E ~ F (F relative sibling of E)
  790. case '~':
  791. match = selector.match(Patterns.relative);
  792. source = 'n=e;while((e=e.previousElementSibling)){' + source + '}e=n;';
  793. break;
  794. // *** Adjacent sibling combinator
  795. // E + F (F adiacent sibling of E)
  796. case '+':
  797. match = selector.match(Patterns.adjacent);
  798. source = 'n=e;if((e=e.previousElementSibling)){' + source + '}e=n;';
  799. break;
  800. // *** Descendant combinator
  801. // E F (E ancestor of F)
  802. case '\x09':
  803. case '\x20':
  804. match = selector.match(Patterns.ancestor);
  805. source = 'n=e;while((e=e.parentElement)){' + source + '}e=n;';
  806. break;
  807. // *** Child combinator
  808. // E > F (F children of E)
  809. case '>':
  810. match = selector.match(Patterns.children);
  811. source = 'n=e;if((e=e.parentElement)){' + source + '}e=n;';
  812. break;
  813. // *** user supplied combinators extensions
  814. case (symbol in Combinators ? symbol : undefined):
  815. // for other registered combinators extensions
  816. match[match.length - 1] = '*';
  817. source = Combinators[symbol](match) + source;
  818. break;
  819. // *** tree-structural pseudo-classes
  820. // :root, :empty, :first-child, :last-child, :only-child, :first-of-type, :last-of-type, :only-of-type
  821. case ':':
  822. if ((match = selector.match(Patterns.structural))) {
  823. match[1] = match[1].toLowerCase();
  824. switch (match[1]) {
  825. case 'root':
  826. // there can only be one :root element, so exit the loop once found
  827. source = 'if(' + N + '(e===s.root)){' + source + (mode ? 'break main;' : '') + '}';
  828. break;
  829. case 'empty':
  830. // matches elements that don't contain elements or text nodes
  831. source = 'n=e.firstChild;while(n&&!(/1|3/).test(n.nodeType)){n=n.nextSibling}if(' + D + 'n){' + source + '}';
  832. break;
  833. // *** child-indexed pseudo-classes
  834. // :first-child, :last-child, :only-child
  835. case 'only-child':
  836. source = 'if(' + N + '(!e.nextElementSibling&&!e.previousElementSibling)){' + source + '}';
  837. break;
  838. case 'last-child':
  839. source = 'if(' + N + '(!e.nextElementSibling)){' + source + '}';
  840. break;
  841. case 'first-child':
  842. source = 'if(' + N + '(!e.previousElementSibling)){' + source + '}';
  843. break;
  844. // *** typed child-indexed pseudo-classes
  845. // :only-of-type, :last-of-type, :first-of-type
  846. case 'only-of-type':
  847. source = 'o=e.localName;' +
  848. 'n=e;while((n=n.nextElementSibling)&&n.localName!=o);if(!n){' +
  849. 'n=e;while((n=n.previousElementSibling)&&n.localName!=o);}if(' + D + 'n){' + source + '}';
  850. break;
  851. case 'last-of-type':
  852. source = 'n=e;o=e.localName;while((n=n.nextElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}';
  853. break;
  854. case 'first-of-type':
  855. source = 'n=e;o=e.localName;while((n=n.previousElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}';
  856. break;
  857. default:
  858. emit('\'' + selector_string + '\'' + qsInvalid);
  859. break;
  860. }
  861. }
  862. // *** child-indexed & typed child-indexed pseudo-classes
  863. // :nth-child, :nth-of-type, :nth-last-child, :nth-last-of-type
  864. else if ((match = selector.match(Patterns.treestruct))) {
  865. match[1] = match[1].toLowerCase();
  866. switch (match[1]) {
  867. case 'nth-child':
  868. case 'nth-of-type':
  869. case 'nth-last-child':
  870. case 'nth-last-of-type':
  871. expr = /-of-type/i.test(match[1]);
  872. if (match[1] && match[2]) {
  873. type = /last/i.test(match[1]);
  874. if (match[2] == 'n') {
  875. source = 'if(' + N + 'true){' + source + '}';
  876. break;
  877. } else if (match[2] == '1') {
  878. test = type ? 'next' : 'previous';
  879. source = expr ? 'n=e;o=e.localName;' +
  880. 'while((n=n.' + test + 'ElementSibling)&&n.localName!=o);if(' + D + 'n){' + source + '}' :
  881. 'if(' + N + '!e.' + test + 'ElementSibling){' + source + '}';
  882. break;
  883. } else if (match[2] == 'even' || match[2] == '2n0' || match[2] == '2n+0' || match[2] == '2n') {
  884. test = 'n%2==0';
  885. } else if (match[2] == 'odd' || match[2] == '2n1' || match[2] == '2n+1') {
  886. test = 'n%2==1';
  887. } else {
  888. f = /n/i.test(match[2]);
  889. n = match[2].split('n');
  890. a = parseInt(n[0], 10) || 0;
  891. b = parseInt(n[1], 10) || 0;
  892. if (n[0] == '-') { a = -1; }
  893. if (n[0] == '+') { a = +1; }
  894. test = (b ? '(n' + (b > 0 ? '-' : '+') + Math.abs(b) + ')' : 'n') + '%' + a + '==0' ;
  895. test =
  896. a >= +1 ? (f ? 'n>' + (b - 1) + (Math.abs(a) != 1 ? '&&' + test : '') : 'n==' + a) :
  897. a <= -1 ? (f ? 'n<' + (b + 1) + (Math.abs(a) != 1 ? '&&' + test : '') : 'n==' + a) :
  898. a === 0 ? (n[0] ? 'n==' + b : 'n>' + (b - 1)) : 'false';
  899. }
  900. expr = expr ? 'OfType' : 'Element';
  901. type = type ? 'true' : 'false';
  902. source = 'n=s.nth' + expr + '(e,' + type + ');if(' + N + '(' + test + ')){' + source + '}';
  903. } else {
  904. emit('\'' + selector_string + '\'' + qsInvalid);
  905. }
  906. break;
  907. default:
  908. emit('\'' + selector_string + '\'' + qsInvalid);
  909. break;
  910. }
  911. }
  912. // *** logical combination pseudo-classes
  913. // :is( s1, [ s2, ... ]), :not( s1, [ s2, ... ])
  914. else if ((match = selector.match(Patterns.logicalsel))) {
  915. match[1] = match[1].toLowerCase();
  916. switch (match[1]) {
  917. case 'is':
  918. case 'where':
  919. case 'matches':
  920. expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
  921. source = 'if(s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}';
  922. break;
  923. case 'not':
  924. expr = match[2].replace(REX.CommaGroup, ',').replace(REX.TrimSpaces, '');
  925. source = 'if(!s.match("' + expr.replace(/\x22/g, '\\"') + '",e)){' + source + '}';
  926. break;
  927. default:
  928. emit('\'' + selector_string + '\'' + qsInvalid);
  929. break;
  930. }
  931. }
  932. // *** linguistic pseudo-classes
  933. // :dir( ltr / rtl ), :lang( en )
  934. else if ((match = selector.match(Patterns.linguistic))) {
  935. match[1] = match[1].toLowerCase();
  936. switch (match[1]) {
  937. case 'dir':
  938. source = 'var p;if(' + N + '(' +
  939. '(/' + match[2] + '/i.test(e.dir))||(p=s.ancestor("[dir]", e))&&' +
  940. '(/' + match[2] + '/i.test(p.dir))||(e.dir==""||e.dir=="auto")&&' +
  941. '(' + (match[2] == 'ltr' ? '!':'')+ RTL +'.test(e.textContent)))' +
  942. '){' + source + '};';
  943. break;
  944. case 'lang':
  945. expr = '(?:^|-)' + match[2] + '(?:-|$)';
  946. source = 'var p;if(' + N + '(' +
  947. '(e.isConnected&&(e.lang==""&&(p=s.ancestor("[lang]",e)))&&' +
  948. '(p.lang=="' + match[2] + '")||/'+ expr +'/i.test(e.lang)))' +
  949. '){' + source + '};';
  950. break;
  951. default:
  952. emit('\'' + selector_string + '\'' + qsInvalid);
  953. break;
  954. }
  955. }
  956. // *** location pseudo-classes
  957. // :any-link, :link, :visited, :target
  958. else if ((match = selector.match(Patterns.locationpc))) {
  959. match[1] = match[1].toLowerCase();
  960. switch (match[1]) {
  961. case 'any-link':
  962. source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")||e.visited)){' + source + '}';
  963. break;
  964. case 'link':
  965. source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href"))){' + source + '}';
  966. break;
  967. case 'visited':
  968. source = 'if(' + N + '(/^a|area$/i.test(e.localName)&&e.hasAttribute("href")&&e.visited)){' + source + '}';
  969. break;
  970. case 'target':
  971. source = 'if(' + N + '((s.doc.compareDocumentPosition(e)&16)&&s.doc.location.hash&&e.id==s.doc.location.hash.slice(1))){' + source + '}';
  972. break;
  973. default:
  974. emit('\'' + selector_string + '\'' + qsInvalid);
  975. break;
  976. }
  977. }
  978. // *** user actions pseudo-classes
  979. // :hover, :active, :focus
  980. else if ((match = selector.match(Patterns.useraction))) {
  981. match[1] = match[1].toLowerCase();
  982. switch (match[1]) {
  983. case 'hover':
  984. source = 'hasFocus' in doc && doc.hasFocus() ?
  985. 'if(' + N + '(e===s.doc.hoverElement)){' + source + '}' :
  986. 'if(' + D + 'true){' + source + '}';
  987. break;
  988. case 'active':
  989. source = 'hasFocus' in doc && doc.hasFocus() ?
  990. 'if(' + N + '(e===s.doc.activeElement)){' + source + '}' :
  991. 'if(' + D + 'true){' + source + '}';
  992. break;
  993. case 'focus':
  994. source = 'hasFocus' in doc ?
  995. 'if(' + N + '(e===s.doc.activeElement&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source + '}' :
  996. 'if(' + N + '(e===s.doc.activeElement&&(e.type||e.href))){' + source + '}';
  997. break;
  998. case 'focus-within':
  999. source = 'hasFocus' in doc ?
  1000. 'n=s.doc.activeElement;while(e){if(e===n||e.parentNode===n)break;}' +
  1001. 'if(' + N + '(e===n&&s.doc.hasFocus()&&(e.type||e.href||typeof e.tabIndex=="number"))){' + source + '}' : source;
  1002. break;
  1003. default:
  1004. emit('\'' + selector_string + '\'' + qsInvalid);
  1005. break;
  1006. }
  1007. }
  1008. // *** user interface and form pseudo-classes
  1009. // :enabled, :disabled, :read-only, :read-write, :placeholder-shown, :default
  1010. else if ((match = selector.match(Patterns.inputstate))) {
  1011. match[1] = match[1].toLowerCase();
  1012. switch (match[1]) {
  1013. case 'enabled':
  1014. source = 'if(' + N + '(("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e &&e.disabled===false' +
  1015. ')){' + source + '}';
  1016. break;
  1017. case 'disabled':
  1018. // https://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute
  1019. source = 'if(' + N + '(("form" in e||/^optgroup$/i.test(e.localName))&&"disabled" in e&&' +
  1020. '(e.disabled===true||(n=s.ancestor("fieldset",e))&&(n=s.first("legend",n))&&!n.contains(e))' +
  1021. ')){' + source + '}';
  1022. break;
  1023. case 'read-only':
  1024. source =
  1025. 'if(' + N + '(' +
  1026. '(/^textarea$/i.test(e.localName)&&(e.readOnly||e.disabled))||' +
  1027. '("|password|text|".includes("|"+e.type+"|")&&e.readOnly)' +
  1028. ')){' + source + '}';
  1029. break;
  1030. case 'read-write':
  1031. source =
  1032. 'if(' + N + '(' +
  1033. '((/^textarea$/i.test(e.localName)&&!e.readOnly&&!e.disabled)||' +
  1034. '("|password|text|".includes("|"+e.type+"|")&&!e.readOnly&&!e.disabled))||' +
  1035. '(e.hasAttribute("contenteditable")||(s.doc.designMode=="on"))' +
  1036. ')){' + source + '}';
  1037. break;
  1038. case 'placeholder-shown':
  1039. source =
  1040. 'if(' + N + '(' +
  1041. '(/^input|textarea$/i.test(e.localName))&&e.hasAttribute("placeholder")&&' +
  1042. '("|textarea|password|number|search|email|text|tel|url|".includes("|"+e.type+"|"))&&' +
  1043. '(!s.match(":focus",e))' +
  1044. ')){' + source + '}';
  1045. break;
  1046. case 'default':
  1047. source =
  1048. 'if(' + N + '("form" in e && e.form)){' +
  1049. 'var x=0;n=[];' +
  1050. 'if(e.type=="image")n=e.form.getElementsByTagName("input");' +
  1051. 'if(e.type=="submit")n=e.form.elements;' +
  1052. 'while(n[x]&&e!==n[x]){' +
  1053. 'if(n[x].type=="image")break;' +
  1054. 'if(n[x].type=="submit")break;' +
  1055. 'x++;' +
  1056. '}' +
  1057. '}' +
  1058. 'if(' + N + '(e.form&&(e===n[x]&&"|image|submit|".includes("|"+e.type+"|"))||' +
  1059. '((/^option$/i.test(e.localName))&&e.defaultSelected)||' +
  1060. '(("|radio|checkbox|".includes("|"+e.type+"|"))&&e.defaultChecked)' +
  1061. ')){' + source + '}';
  1062. break;
  1063. default:
  1064. emit('\'' + selector_string + '\'' + qsInvalid);
  1065. break;
  1066. }
  1067. }
  1068. // *** input pseudo-classes (for form validation)
  1069. // :checked, :indeterminate, :valid, :invalid, :in-range, :out-of-range, :required, :optional
  1070. else if ((match = selector.match(Patterns.inputvalue))) {
  1071. match[1] = match[1].toLowerCase();
  1072. switch (match[1]) {
  1073. case 'checked':
  1074. source = 'if(' + N + '(/^input$/i.test(e.localName)&&' +
  1075. '("|radio|checkbox|".includes("|"+e.type+"|")&&e.checked)||' +
  1076. '(/^option$/i.test(e.localName)&&(e.selected||e.checked))' +
  1077. ')){' + source + '}';
  1078. break;
  1079. case 'indeterminate':
  1080. source =
  1081. 'if(' + N + '(/^progress$/i.test(e.localName)&&!e.hasAttribute("value"))||' +
  1082. '(/^input$/i.test(e.localName)&&("checkbox"==e.type&&e.indeterminate)||' +
  1083. '("radio"==e.type&&e.name&&!s.first("input[name="+e.name+"]:checked",e.form))' +
  1084. ')){' + source + '}';
  1085. break;
  1086. case 'required':
  1087. source =
  1088. 'if(' + N +
  1089. '(/^input|select|textarea$/i.test(e.localName)&&e.required)' +
  1090. '){' + source + '}';
  1091. break;
  1092. case 'optional':
  1093. source =
  1094. 'if(' + N +
  1095. '(/^input|select|textarea$/i.test(e.localName)&&!e.required)' +
  1096. '){' + source + '}';
  1097. break;
  1098. case 'invalid':
  1099. source =
  1100. 'if(' + N + '((' +
  1101. '(/^form$/i.test(e.localName)&&!e.noValidate)||' +
  1102. '(e.willValidate&&!e.formNoValidate))&&!e.checkValidity())||' +
  1103. '(/^fieldset$/i.test(e.localName)&&s.first(":invalid",e))' +
  1104. '){' + source + '}';
  1105. break;
  1106. case 'valid':
  1107. source =
  1108. 'if(' + N + '((' +
  1109. '(/^form$/i.test(e.localName)&&!e.noValidate)||' +
  1110. '(e.willValidate&&!e.formNoValidate))&&e.checkValidity())||' +
  1111. '(/^fieldset$/i.test(e.localName)&&s.first(":valid",e))' +
  1112. '){' + source + '}';
  1113. break;
  1114. case 'in-range':
  1115. source =
  1116. 'if(' + N +
  1117. '(/^input$/i.test(e.localName))&&' +
  1118. '(e.willValidate&&!e.formNoValidate)&&' +
  1119. '(!e.validity.rangeUnderflow&&!e.validity.rangeOverflow)&&' +
  1120. '("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&' +
  1121. '("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))' +
  1122. '){' + source + '}';
  1123. break;
  1124. case 'out-of-range':
  1125. source =
  1126. 'if(' + N +
  1127. '(/^input$/i.test(e.localName))&&' +
  1128. '(e.willValidate&&!e.formNoValidate)&&' +
  1129. '(e.validity.rangeUnderflow||e.validity.rangeOverflow)&&' +
  1130. '("|date|datetime-local|month|number|range|time|week|".includes("|"+e.type+"|"))&&' +
  1131. '("range"==e.type||e.getAttribute("min")||e.getAttribute("max"))' +
  1132. '){' + source + '}';
  1133. break;
  1134. default:
  1135. emit('\'' + selector_string + '\'' + qsInvalid);
  1136. break;
  1137. }
  1138. }
  1139. // allow pseudo-elements starting with single colon (:)
  1140. // :after, :before, :first-letter, :first-line
  1141. // assert: e.type is in double-colon format, like ::after
  1142. else if ((match = selector.match(Patterns.pseudo_sng))) {
  1143. source = 'if(e.element&&e.type.toLowerCase()=="' +
  1144. ':' + match[0].toLowerCase() + '"){e=e.element;' + source + '}';
  1145. }
  1146. // allow pseudo-elements starting with double colon (::)
  1147. // ::after, ::before, ::marker, ::placeholder, ::inactive-selection, ::selection, ::-webkit-<foo-bar>
  1148. // assert: e.type is in double-colon format, like ::after
  1149. else if ((match = selector.match(Patterns.pseudo_dbl))) {
  1150. source = 'if(e.element&&e.type.toLowerCase()=="' +
  1151. match[0].toLowerCase() + '"){e=e.element;' + source + '}';
  1152. }
  1153. // placeholder for parsed only no-op selectors
  1154. else if ((match = selector.match(Patterns.pseudo_nop))) {
  1155. source = 'if(' + N + 'false' + '){' + source + '}';
  1156. }
  1157. else {
  1158. // reset
  1159. expr = false;
  1160. status = false;
  1161. // process registered selector extensions
  1162. for (expr in Selectors) {
  1163. if ((match = selector.match(Selectors[expr].Expression))) {
  1164. result = Selectors[expr].Callback(match, source, mode, callback);
  1165. if ('match' in result) { match = result.match; }
  1166. vars = result.modvar;
  1167. if (mode) {
  1168. // add extra select() vars
  1169. vars && S_VARS.indexOf(vars) < 0 && (S_VARS[S_VARS.length] = vars);
  1170. } else {
  1171. // add extra match() vars
  1172. vars && M_VARS.indexOf(vars) < 0 && (M_VARS[M_VARS.length] = vars);
  1173. }
  1174. // extension source code
  1175. source = result.source;
  1176. // extension status code
  1177. status = result.status;
  1178. // break on status error
  1179. if (status) { break; }
  1180. }
  1181. }
  1182. if (!status) {
  1183. emit('unknown pseudo-class selector \'' + selector + '\'');
  1184. return '';
  1185. }
  1186. if (!expr) {
  1187. emit('unknown token in selector \'' + selector + '\'');
  1188. return '';
  1189. }
  1190. }
  1191. break;
  1192. default:
  1193. emit('\'' + selector_string + '\'' + qsInvalid);
  1194. break selector_recursion_label;
  1195. }
  1196. // end of switch symbol
  1197. if (!match) {
  1198. emit('\'' + selector_string + '\'' + qsInvalid);
  1199. return '';
  1200. }
  1201. // pop last component
  1202. selector = match.pop();
  1203. }
  1204. // end of while selector
  1205. return source;
  1206. },
  1207. // replace ':scope' pseudo-class with element references
  1208. makeref =
  1209. function(selectors, element) {
  1210. return selectors.replace(/:scope/ig,
  1211. element.localName +
  1212. (element.id ? '#' + element.id : '') +
  1213. (element.className ? '.' + element.classList[0] : ''));
  1214. },
  1215. // equivalent of w3c 'closest' method
  1216. ancestor =
  1217. function _closest(selectors, element, callback) {
  1218. if ((/:scope/i).test(selectors)) {
  1219. selectors = makeref(selectors, element);
  1220. }
  1221. while (element) {
  1222. if (match(selectors, element, callback)) break;
  1223. element = element.parentElement;
  1224. }
  1225. return element;
  1226. },
  1227. match_assert =
  1228. function(f, element, callback) {
  1229. for (var i = 0, l = f.length, r = false; l > i; ++i)
  1230. f[i](element, callback, null, false) && (r = true);
  1231. return r;
  1232. },
  1233. match_collect =
  1234. function(selectors, callback) {
  1235. for (var i = 0, l = selectors.length, f = [ ]; l > i; ++i)
  1236. f[i] = compile(selectors[i], false, callback);
  1237. return { factory: f };
  1238. },
  1239. // equivalent of w3c 'matches' method
  1240. match =
  1241. function _matches(selectors, element, callback) {
  1242. var expressions, parsed;
  1243. if (element && matchResolvers[selectors]) {
  1244. return match_assert(matchResolvers[selectors].factory, element, callback);
  1245. }
  1246. lastMatched = selectors;
  1247. // arguments validation
  1248. if (arguments.length === 0) {
  1249. emit(qsNotArgs, TypeError);
  1250. return Config.VERBOSITY ? undefined : false;
  1251. } else if (arguments[0] === '') {
  1252. emit('\'\'' + qsInvalid);
  1253. return Config.VERBOSITY ? undefined : false;
  1254. }
  1255. // input NULL or UNDEFINED
  1256. if (typeof selectors != 'string') {
  1257. selectors = '' + selectors;
  1258. }
  1259. if ((/:scope/i).test(selectors)) {
  1260. selectors = makeref(selectors, element);
  1261. }
  1262. // normalize input string
  1263. parsed = selectors.
  1264. replace(/\x00|\\$/g, '\ufffd').
  1265. replace(REX.CombineWSP, '\x20').
  1266. replace(REX.PseudosWSP, '$1').
  1267. replace(REX.TabCharWSP, '\t').
  1268. replace(REX.CommaGroup, ',').
  1269. replace(REX.TrimSpaces, '');
  1270. // parse, validate and split possible compound selectors
  1271. if ((expressions = parsed.match(reValidator)) && expressions.join('') == parsed) {
  1272. expressions = parsed.match(REX.SplitGroup);
  1273. if (parsed[parsed.length - 1] == ',') {
  1274. emit(qsInvalid);
  1275. return Config.VERBOSITY ? undefined : false;
  1276. }
  1277. } else {
  1278. emit('\'' + selectors + '\'' + qsInvalid);
  1279. return Config.VERBOSITY ? undefined : false;
  1280. }
  1281. matchResolvers[selectors] = match_collect(expressions, callback);
  1282. return match_assert(matchResolvers[selectors].factory, element, callback);
  1283. },
  1284. // equivalent of w3c 'querySelector' method
  1285. first =
  1286. function _querySelector(selectors, context, callback) {
  1287. if (arguments.length === 0) {
  1288. emit(qsNotArgs, TypeError);
  1289. }
  1290. return select(selectors, context,
  1291. typeof callback == 'function' ?
  1292. function firstMatch(element) {
  1293. callback(element);
  1294. return false;
  1295. } :
  1296. function firstMatch() {
  1297. return false;
  1298. }
  1299. )[0] || null;
  1300. },
  1301. // equivalent of w3c 'querySelectorAll' method
  1302. select =
  1303. function _querySelectorAll(selectors, context, callback) {
  1304. var expressions, nodes = [ ], parsed, resolver;
  1305. context || (context = doc);
  1306. if (selectors) {
  1307. if ((resolver = selectResolvers[selectors])) {
  1308. if (resolver.context === context && resolver.callback === callback) {
  1309. var f = resolver.factory, h = resolver.htmlset, n = resolver.nodeset;
  1310. if (n.length > 1) {
  1311. for (var i = 0, l = n.length, list; l > i; ++i) {
  1312. list = compat[n[i][0]](context, n[i].slice(1))();
  1313. if (f[i] !== null) {
  1314. f[i](list, callback, context, nodes);
  1315. } else {
  1316. nodes = nodes.concat(list);
  1317. }
  1318. }
  1319. if (l > 1 && nodes.length > 1) {
  1320. nodes.sort(documentOrder);
  1321. hasDupes && (nodes = unique(nodes));
  1322. }
  1323. } else {
  1324. if (f[0]) {
  1325. nodes = f[0](h[0](), callback, context, nodes);
  1326. } else {
  1327. nodes = h[0]();
  1328. }
  1329. }
  1330. return typeof callback == 'function' ?
  1331. concatCall(nodes, callback) : nodes;
  1332. }
  1333. }
  1334. }
  1335. lastSelected = selectors;
  1336. // arguments validation
  1337. if (arguments.length === 0) {
  1338. emit(qsNotArgs, TypeError);
  1339. return Config.VERBOSITY ? undefined : none;
  1340. } else if (arguments[0] === '') {
  1341. emit('\'\'' + qsInvalid);
  1342. return Config.VERBOSITY ? undefined : none;
  1343. } else if (lastContext !== context) {
  1344. lastContext = switchContext(context);
  1345. }
  1346. // input NULL or UNDEFINED
  1347. if (typeof selectors != 'string') {
  1348. selectors = '' + selectors;
  1349. }
  1350. if ((/:scope/i).test(selectors)) {
  1351. selectors = makeref(selectors, context);
  1352. }
  1353. // normalize input string
  1354. parsed = selectors.
  1355. replace(/\x00|\\$/g, '\ufffd').
  1356. replace(REX.CombineWSP, '\x20').
  1357. replace(REX.PseudosWSP, '$1').
  1358. replace(REX.TabCharWSP, '\t').
  1359. replace(REX.CommaGroup, ',').
  1360. replace(REX.TrimSpaces, '');
  1361. // parse, validate and split possible compound selectors
  1362. if ((expressions = parsed.match(reValidator)) && expressions.join('') == parsed) {
  1363. expressions = parsed.match(REX.SplitGroup);
  1364. if (parsed[parsed.length - 1] == ',') {
  1365. emit(qsInvalid);
  1366. return Config.VERBOSITY ? undefined : false;
  1367. }
  1368. } else {
  1369. emit('\'' + selectors + '\'' + qsInvalid);
  1370. return Config.VERBOSITY ? undefined : false;
  1371. }
  1372. // save/reuse factory and closure collection
  1373. selectResolvers[selectors] = collect(expressions, context, callback);
  1374. nodes = selectResolvers[selectors].results;
  1375. return typeof callback == 'function' ?
  1376. concatCall(nodes, callback) : nodes;
  1377. },
  1378. // optimize selectors avoiding duplicated checks
  1379. optimize =
  1380. function(selector, token) {
  1381. var index = token.index,
  1382. length = token[1].length + token[2].length;
  1383. return selector.slice(0, index) +
  1384. (' >+~'.indexOf(selector.charAt(index - 1)) > -1 ?
  1385. (':['.indexOf(selector.charAt(index + length + 1)) > -1 ?
  1386. '*' : '') : '') + selector.slice(index + length - (token[1] == '*' ? 1 : 0));
  1387. },
  1388. // prepare factory resolvers and closure collections
  1389. collect =
  1390. function(selectors, context, callback) {
  1391. var i, l, seen = { }, token = ['', '*', '*'], optimized = selectors,
  1392. factory = [ ], htmlset = [ ], nodeset = [ ], results = [ ], type;
  1393. for (i = 0, l = selectors.length; l > i; ++i) {
  1394. if (!seen[selectors[i]] && (seen[selectors[i]] = true)) {
  1395. type = selectors[i].match(reOptimizer);
  1396. if (type && type[1] != ':' && (token = type)) {
  1397. token[1] || (token[1] = '*');
  1398. optimized[i] = optimize(optimized[i], token);
  1399. } else {
  1400. token = ['', '*', '*'];
  1401. }
  1402. }
  1403. nodeset[i] = token[1] + token[2];
  1404. htmlset[i] = compat[token[1]](context, token[2]);
  1405. factory[i] = compile(optimized[i], true, null);
  1406. factory[i] ?
  1407. factory[i](htmlset[i](), callback, context, results) :
  1408. result.concat(htmlset[i]());
  1409. }
  1410. if (l > 1) {
  1411. results.sort(documentOrder);
  1412. hasDupes && (results = unique(results));
  1413. }
  1414. return {
  1415. callback: callback,
  1416. context: context,
  1417. factory: factory,
  1418. htmlset: htmlset,
  1419. nodeset: nodeset,
  1420. results: results
  1421. };
  1422. },
  1423. // QSA placeholders to native references
  1424. _closest, _matches, _querySelector, _querySelectorAll,
  1425. // overrides QSA methods (only for browsers)
  1426. install =
  1427. function(all) {
  1428. // save native QSA references
  1429. _closest = Element.prototype.closest;
  1430. _matches = Element.prototype.matches;
  1431. _querySelector = Document.prototype.querySelector;
  1432. _querySelectorAll = Document.prototype.querySelectorAll;
  1433. Element.prototype.closest =
  1434. function closest() {
  1435. var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
  1436. if (!('nodeType' in this)) { emit('\'closest\' called on an object that does not implement interface ' + ctor + '.', TypeError); }
  1437. return arguments.length < 1 ? ancestor.apply(this, [ ]) :
  1438. arguments.length < 2 ? ancestor.apply(this, [ arguments[0], this ]) :
  1439. ancestor.apply(this, [ arguments[0], this, typeof arguments[1] == 'function' ? arguments[1] : undefined ]);
  1440. };
  1441. Element.prototype.matches =
  1442. function matches() {
  1443. var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
  1444. if (!('nodeType' in this)) { emit('\'matches\' called on an object that does not implement interface ' + ctor + '.', TypeError); }
  1445. return arguments.length < 1 ? match.apply(this, [ ]) :
  1446. arguments.length < 2 ? match.apply(this, [ arguments[0], this ]) :
  1447. match.apply(this, [ arguments[0], this, typeof arguments[1] == 'function' ? arguments[1] : undefined ]);
  1448. };
  1449. Element.prototype.querySelector =
  1450. Document.prototype.querySelector =
  1451. DocumentFragment.prototype.querySelector =
  1452. function querySelector() {
  1453. var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
  1454. if (!('nodeType' in this)) { emit('\'querySelector\' called on an object that does not implement interface ' + ctor + '.', TypeError); }
  1455. return arguments.length < 1 ? first.apply(this, [ ]) :
  1456. arguments.length < 2 ? first.apply(this, [ arguments[0], this ]) :
  1457. first.apply(this, [ arguments[0], this, typeof arguments[1] == 'function' ? arguments[1] : undefined ]);
  1458. };
  1459. Element.prototype.querySelectorAll =
  1460. Document.prototype.querySelectorAll =
  1461. DocumentFragment.prototype.querySelectorAll =
  1462. function querySelectorAll() {
  1463. var ctor = Object.getPrototypeOf(this).__proto__.__proto__.constructor.name;
  1464. if (!('nodeType' in this)) { emit('\'querySelectorAll\' called on an object that does not implement interface ' + ctor + '.', TypeError); }
  1465. return arguments.length < 1 ? select.apply(this, [ ]) :
  1466. arguments.length < 2 ? select.apply(this, [ arguments[0], this ]) :
  1467. select.apply(this, [ arguments[0], this, typeof arguments[1] == 'function' ? arguments[1] : undefined ]);
  1468. };
  1469. if (all) {
  1470. document.addEventListener('load', function(e) {
  1471. var c, d, r, s, t = e.target;
  1472. if (/iframe/i.test(t.localName)) {
  1473. c = '(' + Export + ')(this, ' + Factory + ');'; d = t.contentDocument;
  1474. s = d.createElement('script'); s.textContent = c + 'NW.Dom.install()';
  1475. r = d.documentElement; r.removeChild(r.insertBefore(s, r.firstChild));
  1476. }
  1477. }, true);
  1478. }
  1479. },
  1480. // restore QSA methods (only for browsers)
  1481. uninstall =
  1482. function() {
  1483. // reinstates QSA native references
  1484. Element.prototype.closest = _closest;
  1485. Element.prototype.matches = _matches;
  1486. Element.prototype.querySelector =
  1487. Document.prototype.querySelector =
  1488. DocumentFragment.prototype.querySelector = _querySelector;
  1489. Element.prototype.querySelectorAll =
  1490. Document.prototype.querySelectorAll =
  1491. DocumentFragment.prototype.querySelectorAll = _querySelectorAll;
  1492. },
  1493. // empty set
  1494. none = Array(),
  1495. // context
  1496. lastContext,
  1497. // selector
  1498. lastMatched,
  1499. lastSelected,
  1500. // cached lambdas
  1501. matchLambdas = { },
  1502. selectLambdas = { },
  1503. // cached resolvers
  1504. matchResolvers = { },
  1505. selectResolvers = { },
  1506. // passed to resolvers
  1507. Snapshot = {
  1508. doc: doc,
  1509. from: doc,
  1510. root: root,
  1511. byTag: byTag,
  1512. first: first,
  1513. match: match,
  1514. ancestor: ancestor,
  1515. nthOfType: nthOfType,
  1516. nthElement: nthElement,
  1517. hasAttributeNS: hasAttributeNS
  1518. },
  1519. // public exported methods/objects
  1520. Dom = {
  1521. // exported cache objects
  1522. lastMatched: lastMatched,
  1523. lastSelected: lastSelected,
  1524. matchLambdas: matchLambdas,
  1525. selectLambdas: selectLambdas,
  1526. matchResolvers: matchResolvers,
  1527. selectResolvers: selectResolvers,
  1528. // exported compiler macros
  1529. CFG: CFG,
  1530. M_BODY: M_BODY,
  1531. S_BODY: S_BODY,
  1532. M_TEST: M_TEST,
  1533. S_TEST: S_TEST,
  1534. // exported engine methods
  1535. byId: byId,
  1536. byTag: byTag,
  1537. byClass: byClass,
  1538. match: match,
  1539. first: first,
  1540. select: select,
  1541. closest: ancestor,
  1542. compile: compile,
  1543. configure: configure,
  1544. emit: emit,
  1545. Config: Config,
  1546. Snapshot: Snapshot,
  1547. Version: version,
  1548. install: install,
  1549. uninstall: uninstall,
  1550. Operators: Operators,
  1551. Selectors: Selectors,
  1552. // register a new selector combinator symbol and its related function resolver
  1553. registerCombinator:
  1554. function(combinator, resolver) {
  1555. var i = 0, l = combinator.length, symbol;
  1556. for (; l > i; ++i) {
  1557. if (combinator[i] != '=') {
  1558. symbol = combinator[i];
  1559. break;
  1560. }
  1561. }
  1562. if (CFG.combinators.indexOf(symbol) < 0) {
  1563. CFG.combinators = CFG.combinators.replace('](', symbol + '](');
  1564. CFG.combinators = CFG.combinators.replace('])', symbol + '])');
  1565. Combinators[combinator] = resolver;
  1566. setIdentifierSyntax();
  1567. } else {
  1568. console.warn('Warning: the \'' + combinator + '\' combinator is already registered.');
  1569. }
  1570. },
  1571. // register a new attribute operator symbol and its related function resolver
  1572. registerOperator:
  1573. function(operator, resolver) {
  1574. var i = 0, l = operator.length, symbol;
  1575. for (; l > i; ++i) {
  1576. if (operator[i] != '=') {
  1577. symbol = operator[i];
  1578. break;
  1579. }
  1580. }
  1581. if (CFG.operators.indexOf(symbol) < 0 && !Operators[operator]) {
  1582. CFG.operators = CFG.operators.replace(']=', symbol + ']=');
  1583. Operators[operator] = resolver;
  1584. setIdentifierSyntax();
  1585. } else {
  1586. console.warn('Warning: the \'' + operator + '\' operator is already registered.');
  1587. }
  1588. },
  1589. // register a new selector symbol and its related function resolver
  1590. registerSelector:
  1591. function(name, rexp, func) {
  1592. Selectors[name] || (Selectors[name] = {
  1593. Expression: rexp,
  1594. Callback: func
  1595. });
  1596. }
  1597. };
  1598. initialize(doc);
  1599. return Dom;
  1600. });