pax_global_header00006660000000000000000000000064130401162220014501gustar00rootroot0000000000000052 comment=e3aac04569197a9ee770a8aeadc3563f1eb85132 css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/000077500000000000000000000000001304011622200206305ustar00rootroot00000000000000css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/.eslintrc000066400000000000000000000030511304011622200224530ustar00rootroot00000000000000{ "extends": "eslint:recommended", "env": { "node": true }, "globals": { "beforeEach": true, "describe": true, "it": true }, "rules": { "no-console": 0, "new-cap": 0, "space-before-blocks": [2, "never"], "space-in-parens": [2, "never"], "eqeqeq": [2, "allow-null"], "no-extend-native": 2, "no-use-before-define": [ 2, { "functions": false, "classes": false } ], "no-caller": 2, "no-irregular-whitespace": 2, "quotes": [ 2, "double" ], "no-undef": 2, "no-unused-vars": 2, "no-proto": 2, "curly": [ 2, "multi-line" ], "no-mixed-spaces-and-tabs": [ 2, "smart-tabs" ], "space-infix-ops": 2, "keyword-spacing": [ 2, { "overrides": { "if": { "after": false }, "catch": { "after": false }, "for": { "after": false }, "while": { "after": false } } } ], "comma-style": [ 2, "last" ], "dot-notation": 2, "wrap-iife": 2, "no-empty": 2, "space-unary-ops": [ 2, { "words": false, "nonwords": false } ], "no-with": 2, "no-multi-str": 2, "no-trailing-spaces": 2, "indent": [ 2, "tab", { "SwitchCase": 1 } ], "linebreak-style": [ 2, "unix" ], "consistent-this": [ 2, "_this" ] } } css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/.travis.yml000066400000000000000000000001151304011622200227360ustar00rootroot00000000000000language: node_js node_js: - stable - 6 - 4 script: npm run coveralls css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/LICENSE000066400000000000000000000023541304011622200216410ustar00rootroot00000000000000Copyright (c) Felix Böhm All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/README.md000066400000000000000000000210401304011622200221040ustar00rootroot00000000000000# css-select [![NPM version](http://img.shields.io/npm/v/css-select.svg)](https://npmjs.org/package/css-select) [![Build Status](https://travis-ci.org/fb55/css-select.svg?branch=master)](http://travis-ci.org/fb55/css-select) [![Downloads](https://img.shields.io/npm/dm/css-select.svg)](https://npmjs.org/package/css-select) [![Coverage](https://coveralls.io/repos/fb55/css-select/badge.svg?branch=master)](https://coveralls.io/r/fb55/css-select) a CSS selector compiler/engine ## What? css-select turns CSS selectors into functions that tests if elements match them. When searching for elements, testing is executed "from the top", similar to how browsers execute CSS selectors. In its default configuration, css-select queries the DOM structure of the [`domhandler`](https://github.com/fb55/domhandler) module (also known as htmlparser2 DOM). It uses [`domutils`](https://github.com/fb55/domutils) as its default adapter over the DOM structure. See Options below for details on querying alternative DOM structures. __Features:__ - Full implementation of CSS3 selectors - Partial implementation of jQuery/Sizzle extensions - Very high test coverage - Pretty good performance ## Why? The traditional approach of executing CSS selectors, named left-to-right execution, is to execute every component of the selector in order, from left to right _(duh)_. The execution of the selector `a b` for example will first query for `a` elements, then search these for `b` elements. (That's the approach of eg. [`Sizzle`](https://github.com/jquery/sizzle), [`nwmatcher`](https://github.com/dperini/nwmatcher/) and [`qwery`](https://github.com/ded/qwery).) While this works, it has some downsides: Children of `a`s will be checked multiple times; first, to check if they are also `a`s, then, for every superior `a` once, if they are `b`s. Using [Big O notation](http://en.wikipedia.org/wiki/Big_O_notation), that would be `O(n^(k+1))`, where `k` is the number of descendant selectors (that's the space in the example above). The far more efficient approach is to first look for `b` elements, then check if they have superior `a` elements: Using big O notation again, that would be `O(n)`. That's called right-to-left execution. And that's what css-select does – and why it's quite performant. ## How does it work? By building a stack of functions. _Wait, what?_ Okay, so let's suppose we want to compile the selector `a b` again, for right-to-left execution. We start by _parsing_ the selector, which means we turn the selector into an array of the building-blocks of the selector, so we can distinguish them easily. That's what the [`css-what`](https://github.com/fb55/css-what) module is for, if you want to have a look. Anyway, after parsing, we end up with an array like this one: ```js [ { type: 'tag', name: 'a' }, { type: 'descendant' }, { type: 'tag', name: 'b' } ] ``` Actually, this array is wrapped in another array, but that's another story (involving commas in selectors). Now that we know the meaning of every part of the selector, we can compile it. That's where it becomes interesting. The basic idea is to turn every part of the selector into a function, which takes an element as its only argument. The function checks whether a passed element matches its part of the selector: If it does, the element is passed to the next turned-into-a-function part of the selector, which does the same. If an element is accepted by all parts of the selector, it _matches_ the selector and double rainbow ALL THE WAY. As said before, we want to do right-to-left execution with all the big O improvements nonsense, so elements are passed from the rightmost part of the selector (`b` in our example) to the leftmost (~~which would be `c`~~ of course `a`). _//TODO: More in-depth description. Implementation details. Build a spaceship._ ## API ```js var CSSselect = require("css-select"); ``` #### `CSSselect(query, elems, options)` Queries `elems`, returns an array containing all matches. - `query` can be either a CSS selector or a function. - `elems` can be either an array of elements, or a single element. If it is an element, its children will be queried. - `options` is described below. Aliases: `CSSselect.selectAll(query, elems)`, `CSSselect.iterate(query, elems)`. #### `CSSselect.compile(query)` Compiles the query, returns a function. #### `CSSselect.is(elem, query, options)` Tests whether or not an element is matched by `query`. `query` can be either a CSS selector or a function. #### `CSSselect.selectOne(query, elems, options)` Arguments are the same as for `CSSselect(query, elems)`. Only returns the first match, or `null` if there was no match. ### Options - `xmlMode`: When enabled, tag names will be case-sensitive. Default: `false`. - `strict`: Limits the module to only use CSS3 selectors. Default: `false`. - `rootFunc`: The last function in the stack, will be called with the last element that's looked at. Should return `true`. - `adapter`: The adapter to use when interacting with the backing DOM structure. By default it uses [`domutils`](https://github.com/fb55/domutils). #### Custom Adapters A custom adapter must implement the following functions: ``` isTag, existsOne, getAttributeValue, getChildren, getName, getParent, getSiblings, getText, hasAttrib, removeSubsets, findAll, findOne ``` The method signature notation used below should be fairly intuitive - if not, see the [`rtype`](https://github.com/ericelliott/rtype) or [`TypeScript`](https://www.typescriptlang.org/) docs, as it is very similar to both of those. You may also want to look at -[`domutils`](https://github.com/fb55/domutils) to see the default -implementation, or at -[`css-select-browser-adapter`](https://github.com/nrkn/css-select-browser-adapter/blob/master/index.js) -for an implementation backed by the DOM. ```ts { // is the node a tag? isTag: ( node:Node ) => isTag:Boolean, // does at least one of passed element nodes pass the test predicate? existsOne: ( test:Predicate, elems:[ElementNode] ) => existsOne:Boolean, // get the attribute value getAttributeValue: ( elem:ElementNode, name:String ) => value:String, // get the node's children getChildren: ( node:Node ) => children:[Node], // get the name of the tag getName: ( elem:ElementNode ) => tagName:String, // get the parent of the node getParent: ( node:Node ) => parentNode:Node, /* get the siblings of the node. Note that unlike jQuery's `siblings` method, this is expected to include the current node as well */ getSiblings: ( node:Node ) => siblings:[Node], // get the text content of the node, and its children if it has any getText: ( node:Node ) => text:String, // does the element have the named attribute? hasAttrib: ( elem:ElementNode, name:String ) => hasAttrib:Boolean, // takes an array of nodes, and removes any duplicates, as well as any nodes // whose ancestors are also in the array removeSubsets: ( nodes:[Node] ) => unique:[Node], // finds all of the element nodes in the array that match the test predicate, // as well as any of their children that match it findAll: ( test:Predicate, nodes:[Node] ) => elems:[ElementNode], // finds the first node in the array that matches the test predicate, or one // of its children findOne: ( test:Predicate, elems:[ElementNode] ) => findOne:ElementNode, /* The adapter can also optionally include an equals method, if your DOM structure needs a custom equality test to compare two objects which refer to the same underlying node. If not provided, `css-select` will fall back to `a === b`. */ equals: ( a:Node, b:Node ) => Boolean } ``` ## Supported selectors _As defined by CSS 4 and / or jQuery._ * Universal (`*`) * Tag (``) * Descendant (` `) * Child (`>`) * Parent (`<`) * * Sibling (`+`) * Adjacent (`~`) * Attribute (`[attr=foo]`), with supported comparisons: * `[attr]` (existential) * `=` * `~=` * `|=` * `*=` * `^=` * `$=` * `!=` * * Also, `i` can be added after the comparison to make the comparison case-insensitive (eg. `[attr=foo i]`) * * Pseudos: * `:not` * `:contains` * * `:icontains` * (case-insensitive version of `:contains`) * `:has` * * `:root` * `:empty` * `:parent` * * `:[first|last]-child[-of-type]` * `:only-of-type`, `:only-child` * `:nth-[last-]child[-of-type]` * `:link`, `:visited` (the latter doesn't match any elements) * `:selected` *, `:checked` * `:enabled`, `:disabled` * `:required`, `:optional` * `:header`, `:button`, `:input`, `:text`, `:checkbox`, `:file`, `:password`, `:reset`, `:radio` etc. * * `:matches` * __*__: Not part of CSS3 --- License: BSD-like css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/index.js000066400000000000000000000052301304011622200222750ustar00rootroot00000000000000"use strict"; module.exports = CSSselect; var DomUtils = require("domutils"), falseFunc = require("boolbase").falseFunc, compileFactory = require("./lib/compile.js"), defaultCompile = compileFactory(DomUtils); function adapterCompile(adapter){ return adapter === DomUtils ? defaultCompile : compileFactory(adapter); } function getSelectorFunc(searchFunc){ return function select(query, elems, options){ options = options || {} options.adapter = options.adapter || DomUtils; var compile = adapterCompile(options.adapter); if(typeof query !== "function") query = compile.compileUnsafe(query, options, elems); if(query.shouldTestNextSiblings) elems = appendNextSiblings((options && options.context) || elems, options.adapter); if(!Array.isArray(elems)) elems = options.adapter.getChildren(elems); else elems = options.adapter.removeSubsets(elems); return searchFunc(query, elems, options); }; } function getNextSiblings(elem, adapter){ var siblings = adapter.getSiblings(elem); if(!Array.isArray(siblings)) return []; siblings = siblings.slice(0); while(siblings.shift() !== elem); return siblings; } function appendNextSiblings(elems, adapter){ // Order matters because jQuery seems to check the children before the siblings if(!Array.isArray(elems)) elems = [elems]; var newElems = elems.slice(0); for(var i = 0, len = elems.length; i < len; i++){ var nextSiblings = getNextSiblings(newElems[i], adapter); newElems.push.apply(newElems, nextSiblings); } return newElems; } var selectAll = getSelectorFunc(function selectAll(query, elems, options){ return (query === falseFunc || !elems || elems.length === 0) ? [] : options.adapter.findAll(query, elems); }); var selectOne = getSelectorFunc(function selectOne(query, elems, options){ return (query === falseFunc || !elems || elems.length === 0) ? null : options.adapter.findOne(query, elems); }); function is(elem, query, options){ options = options || {} options.adapter = options.adapter || DomUtils; var compile = adapterCompile(options.adapter); return (typeof query === "function" ? query : compile(query, options))(elem); } /* the exported interface */ function CSSselect(query, elems, options){ return selectAll(query, elems, options); } CSSselect.compile = defaultCompile; CSSselect.filters = defaultCompile.Pseudos.filters; CSSselect.pseudos = defaultCompile.Pseudos.pseudos; CSSselect.selectAll = selectAll; CSSselect.selectOne = selectOne; CSSselect.is = is; //legacy methods (might be removed) CSSselect.parse = defaultCompile; CSSselect.iterate = selectAll; //hooks CSSselect._compileUnsafe = defaultCompile.compileUnsafe; CSSselect._compileToken = defaultCompile.compileToken; css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/000077500000000000000000000000001304011622200213765ustar00rootroot00000000000000css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/attributes.js000066400000000000000000000106731304011622200241310ustar00rootroot00000000000000var falseFunc = require("boolbase").falseFunc; //https://github.com/slevithan/XRegExp/blob/master/src/xregexp.js#L469 var reChars = /[-[\]{}()*+?.,\\^$|#\s]/g; function factory(adapter){ /* attribute selectors */ var attributeRules = { __proto__: null, equals: function(next, data){ var name = data.name, value = data.value; if(data.ignoreCase){ value = value.toLowerCase(); return function equalsIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.toLowerCase() === value && next(elem); }; } return function equals(elem){ return adapter.getAttributeValue(elem, name) === value && next(elem); }; }, hyphen: function(next, data){ var name = data.name, value = data.value, len = value.length; if(data.ignoreCase){ value = value.toLowerCase(); return function hyphenIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && (attr.length === len || attr.charAt(len) === "-") && attr.substr(0, len).toLowerCase() === value && next(elem); }; } return function hyphen(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(0, len) === value && (attr.length === len || attr.charAt(len) === "-") && next(elem); }; }, element: function(next, data){ var name = data.name, value = data.value; if(/\s/.test(value)){ return falseFunc; } value = value.replace(reChars, "\\$&"); var pattern = "(?:^|\\s)" + value + "(?:$|\\s)", flags = data.ignoreCase ? "i" : "", regex = new RegExp(pattern, flags); return function element(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; }, exists: function(next, data){ var name = data.name; return function exists(elem){ return adapter.hasAttrib(elem, name) && next(elem); }; }, start: function(next, data){ var name = data.name, value = data.value, len = value.length; if(len === 0){ return falseFunc; } if(data.ignoreCase){ value = value.toLowerCase(); return function startIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(0, len).toLowerCase() === value && next(elem); }; } return function start(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(0, len) === value && next(elem); }; }, end: function(next, data){ var name = data.name, value = data.value, len = -value.length; if(len === 0){ return falseFunc; } if(data.ignoreCase){ value = value.toLowerCase(); return function endIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(len).toLowerCase() === value && next(elem); }; } return function end(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.substr(len) === value && next(elem); }; }, any: function(next, data){ var name = data.name, value = data.value; if(value === ""){ return falseFunc; } if(data.ignoreCase){ var regex = new RegExp(value.replace(reChars, "\\$&"), "i"); return function anyIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && regex.test(attr) && next(elem); }; } return function any(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.indexOf(value) >= 0 && next(elem); }; }, not: function(next, data){ var name = data.name, value = data.value; if(value === ""){ return function notEmpty(elem){ return !!adapter.getAttributeValue(elem, name) && next(elem); }; } else if(data.ignoreCase){ value = value.toLowerCase(); return function notIC(elem){ var attr = adapter.getAttributeValue(elem, name); return attr != null && attr.toLowerCase() !== value && next(elem); }; } return function not(elem){ return adapter.getAttributeValue(elem, name) !== value && next(elem); }; } }; return { compile: function(next, data, options){ if(options && options.strict && ( data.ignoreCase || data.action === "not" )) throw new Error("Unsupported attribute selector"); return attributeRules[data.action](next, data); }, rules: attributeRules }; } module.exports = factory; css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/compile.js000066400000000000000000000123271304011622200233710ustar00rootroot00000000000000/* compiles a selector to an executable function */ module.exports = compileFactory; var parse = require("css-what"), BaseFuncs = require("boolbase"), sortRules = require("./sort.js"), procedure = require("./procedure.json"), rulesFactory = require("./general.js"), pseudosFactory = require("./pseudos.js"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc; function compileFactory(adapter){ var Pseudos = pseudosFactory(adapter), filters = Pseudos.filters, Rules = rulesFactory(adapter, Pseudos); function compile(selector, options, context){ var next = compileUnsafe(selector, options, context); return wrap(next); } function wrap(next){ return function base(elem){ return adapter.isTag(elem) && next(elem); }; } function compileUnsafe(selector, options, context){ var token = parse(selector, options); return compileToken(token, options, context); } function includesScopePseudo(t){ return t.type === "pseudo" && ( t.name === "scope" || ( Array.isArray(t.data) && t.data.some(function(data){ return data.some(includesScopePseudo); }) ) ); } var DESCENDANT_TOKEN = {type: "descendant"}, FLEXIBLE_DESCENDANT_TOKEN = {type: "_flexibleDescendant"}, SCOPE_TOKEN = {type: "pseudo", name: "scope"}, PLACEHOLDER_ELEMENT = {}; //CSS 4 Spec (Draft): 3.3.1. Absolutizing a Scope-relative Selector //http://www.w3.org/TR/selectors4/#absolutizing function absolutize(token, context){ //TODO better check if context is document var hasContext = !!context && !!context.length && context.every(function(e){ return e === PLACEHOLDER_ELEMENT || !!adapter.getParent(e); }); token.forEach(function(t){ if(t.length > 0 && isTraversal(t[0]) && t[0].type !== "descendant"){ //don't return in else branch } else if(hasContext && !includesScopePseudo(t)){ t.unshift(DESCENDANT_TOKEN); } else { return; } t.unshift(SCOPE_TOKEN); }); } function compileToken(token, options, context){ token = token.filter(function(t){ return t.length > 0; }); token.forEach(sortRules); var isArrayContext = Array.isArray(context); context = (options && options.context) || context; if(context && !isArrayContext) context = [context]; absolutize(token, context); var shouldTestNextSiblings = false; var query = token .map(function(rules){ if(rules[0] && rules[1] && rules[0].name === "scope"){ var ruleType = rules[1].type; if(isArrayContext && ruleType === "descendant") rules[1] = FLEXIBLE_DESCENDANT_TOKEN; else if(ruleType === "adjacent" || ruleType === "sibling") shouldTestNextSiblings = true; } return compileRules(rules, options, context); }) .reduce(reduceRules, falseFunc); query.shouldTestNextSiblings = shouldTestNextSiblings; return query; } function isTraversal(t){ return procedure[t.type] < 0; } function compileRules(rules, options, context){ return rules.reduce(function(func, rule){ if(func === falseFunc) return func; return Rules[rule.type](func, rule, options, context); }, options && options.rootFunc || trueFunc); } function reduceRules(a, b){ if(b === falseFunc || a === trueFunc){ return a; } if(a === falseFunc || b === trueFunc){ return b; } return function combine(elem){ return a(elem) || b(elem); }; } function containsTraversal(t){ return t.some(isTraversal); } //:not, :has and :matches have to compile selectors //doing this in lib/pseudos.js would lead to circular dependencies, //so we add them here filters.not = function(next, token, options, context){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict) }; if(opts.strict){ if(token.length > 1 || token.some(containsTraversal)){ throw new Error("complex selectors in :not aren't allowed in strict mode"); } } var func = compileToken(token, opts, context); if(func === falseFunc) return next; if(func === trueFunc) return falseFunc; return function(elem){ return !func(elem) && next(elem); }; }; filters.has = function(next, token, options){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict) }; //FIXME: Uses an array as a pointer to the current element (side effects) var context = token.some(containsTraversal) ? [PLACEHOLDER_ELEMENT] : null; var func = compileToken(token, opts, context); if(func === falseFunc) return falseFunc; if(func === trueFunc){ return function(elem){ return adapter.getChildren(elem).some(adapter.isTag) && next(elem); }; } func = wrap(func); if(context){ return function has(elem){ return next(elem) && ( (context[0] = elem), adapter.existsOne(func, adapter.getChildren(elem)) ); }; } return function has(elem){ return next(elem) && adapter.existsOne(func, adapter.getChildren(elem)); }; }; filters.matches = function(next, token, options, context){ var opts = { xmlMode: !!(options && options.xmlMode), strict: !!(options && options.strict), rootFunc: next }; return compileToken(token, opts, context); }; compile.compileToken = compileToken; compile.compileUnsafe = compileUnsafe; compile.Pseudos = Pseudos; return compile; } css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/general.js000066400000000000000000000040671304011622200233600ustar00rootroot00000000000000var attributeFactory = require("./attributes.js"); function generalFactory(adapter, Pseudos){ /* all available rules */ return { __proto__: null, attribute: attributeFactory(adapter).compile, pseudo: Pseudos.compile, //tags tag: function(next, data){ var name = data.name; return function tag(elem){ return adapter.getName(elem) === name && next(elem); }; }, //traversal descendant: function(next){ return function descendant(elem){ var found = false; while(!found && (elem = adapter.getParent(elem))){ found = next(elem); } return found; }; }, _flexibleDescendant: function(next){ // Include element itself, only used while querying an array return function descendant(elem){ var found = next(elem); while(!found && (elem = adapter.getParent(elem))){ found = next(elem); } return found; }; }, parent: function(next, data, options){ if(options && options.strict) throw new Error("Parent selector isn't part of CSS3"); return function parent(elem){ return adapter.getChildren(elem).some(test); }; function test(elem){ return adapter.isTag(elem) && next(elem); } }, child: function(next){ return function child(elem){ var parent = adapter.getParent(elem); return !!parent && next(parent); }; }, sibling: function(next){ return function sibling(elem){ var siblings = adapter.getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; if(next(siblings[i])) return true; } } return false; }; }, adjacent: function(next){ return function adjacent(elem){ var siblings = adapter.getSiblings(elem), lastElement; for(var i = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; lastElement = siblings[i]; } } return !!lastElement && next(lastElement); }; }, universal: function(next){ return next; } }; } module.exports = generalFactory; css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/procedure.json000066400000000000000000000002321304011622200242560ustar00rootroot00000000000000{ "universal": 50, "tag": 30, "attribute": 1, "pseudo": 0, "descendant": -1, "child": -1, "parent": -1, "sibling": -1, "adjacent": -1 } css-select-e3aac04569197a9ee770a8aeadc3563f1eb85132/lib/pseudos.js000066400000000000000000000246261304011622200234300ustar00rootroot00000000000000/* pseudo selectors --- they are available in two forms: * filters called when the selector is compiled and return a function that needs to return next() * pseudos get called on execution they need to return a boolean */ var getNCheck = require("nth-check"), BaseFuncs = require("boolbase"), attributesFactory = require("./attributes.js"), trueFunc = BaseFuncs.trueFunc, falseFunc = BaseFuncs.falseFunc; function filtersFactory(adapter){ var attributes = attributesFactory(adapter), checkAttrib = attributes.rules.equals; //helper methods function equals(a, b){ if(typeof adapter.equals === "function") return adapter.equals(a, b); return a === b; } function getAttribFunc(name, value){ var data = {name: name, value: value}; return function attribFunc(next){ return checkAttrib(next, data); }; } function getChildFunc(next){ return function(elem){ return !!adapter.getParent(elem) && next(elem); }; } var filters = { contains: function(next, text){ return function contains(elem){ return next(elem) && adapter.getText(elem).indexOf(text) >= 0; }; }, icontains: function(next, text){ var itext = text.toLowerCase(); return function icontains(elem){ return next(elem) && adapter.getText(elem).toLowerCase().indexOf(itext) >= 0; }; }, //location specific methods "nth-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthChild(elem){ var siblings = adapter.getSiblings(elem); for(var i = 0, pos = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-last-child": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastChild(elem){ var siblings = adapter.getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; else pos++; } } return func(pos) && next(elem); }; }, "nth-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthOfType(elem){ var siblings = adapter.getSiblings(elem); for(var pos = 0, i = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; if(adapter.getName(siblings[i]) === adapter.getName(elem)) pos++; } } return func(pos) && next(elem); }; }, "nth-last-of-type": function(next, rule){ var func = getNCheck(rule); if(func === falseFunc) return func; if(func === trueFunc) return getChildFunc(next); return function nthLastOfType(elem){ var siblings = adapter.getSiblings(elem); for(var pos = 0, i = siblings.length - 1; i >= 0; i--){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) break; if(adapter.getName(siblings[i]) === adapter.getName(elem)) pos++; } } return func(pos) && next(elem); }; }, //TODO determine the actual root element root: function(next){ return function(elem){ return !adapter.getParent(elem) && next(elem); }; }, scope: function(next, rule, options, context){ if(!context || context.length === 0){ //equivalent to :root return filters.root(next); } if(context.length === 1){ //NOTE: can't be unpacked, as :has uses this for side-effects return function(elem){ return equals(context[0], elem) && next(elem); }; } return function(elem){ return context.indexOf(elem) >= 0 && next(elem); }; }, //jQuery extensions (others follow as pseudos) checkbox: getAttribFunc("type", "checkbox"), file: getAttribFunc("type", "file"), password: getAttribFunc("type", "password"), radio: getAttribFunc("type", "radio"), reset: getAttribFunc("type", "reset"), image: getAttribFunc("type", "image"), submit: getAttribFunc("type", "submit") }; return filters; } function pseudosFactory(adapter){ //helper methods function getFirstElement(elems){ for(var i = 0; elems && i < elems.length; i++){ if(adapter.isTag(elems[i])) return elems[i]; } } //while filters are precompiled, pseudos get called when they are needed var pseudos = { empty: function(elem){ return !adapter.getChildren(elem).some(function(elem){ return adapter.isTag(elem) || elem.type === "text"; }); }, "first-child": function(elem){ return getFirstElement(adapter.getSiblings(elem)) === elem; }, "last-child": function(elem){ var siblings = adapter.getSiblings(elem); for(var i = siblings.length - 1; i >= 0; i--){ if(siblings[i] === elem) return true; if(adapter.isTag(siblings[i])) break; } return false; }, "first-of-type": function(elem){ var siblings = adapter.getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) return true; if(adapter.getName(siblings[i]) === adapter.getName(elem)) break; } } return false; }, "last-of-type": function(elem){ var siblings = adapter.getSiblings(elem); for(var i = siblings.length - 1; i >= 0; i--){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) return true; if(adapter.getName(siblings[i]) === adapter.getName(elem)) break; } } return false; }, "only-of-type": function(elem){ var siblings = adapter.getSiblings(elem); for(var i = 0, j = siblings.length; i < j; i++){ if(adapter.isTag(siblings[i])){ if(siblings[i] === elem) continue; if(adapter.getName(siblings[i]) === adapter.getName(elem)) return false; } } return true; }, "only-child": function(elem){ var siblings = adapter.getSiblings(elem); for(var i = 0; i < siblings.length; i++){ if(adapter.isTag(siblings[i]) && siblings[i] !== elem) return false; } return true; }, //:matches(a, area, link)[href] link: function(elem){ return adapter.hasAttrib(elem, "href"); }, visited: falseFunc, //seems to be a valid implementation //TODO: :any-link once the name is finalized (as an alias of :link) //forms //to consider: :target //:matches([selected], select:not([multiple]):not(> option[selected]) > option:first-of-type) selected: function(elem){ if(adapter.hasAttrib(elem, "selected")) return true; else if(adapter.getName(elem) !== "option") return false; //the first