nwsapi.js 60 KB

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