Created
May 22, 2012 08:48
-
-
Save gregstewart/2767675 to your computer and use it in GitHub Desktop.
zepto.selector.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;(function($){ | |
var zepto = $.zepto, oldQsa = zepto.qsa, oldMatches = zepto.matches | |
function visible(elem){ | |
elem = $(elem) | |
return !!(elem.width() || elem.height()) && elem.css("display") !== "none" | |
} | |
// Implements a subset from: | |
// http://api.jquery.com/category/selectors/jquery-selector-extensions/ | |
// | |
// Each filter function receives the current index, all nodes in the | |
// considered set, and a value if there were parentheses. The value | |
// of `this` is the node currently being considered. The function returns the | |
// resulting node(s), null, or undefined. | |
// | |
// Complex selectors are not supported: | |
// li:has(label:contains("foo")) + li:has(label:contains("bar")) | |
// "> h2" | |
// ul.inner:first > li | |
var filters = zepto.cssFilters = { | |
visible: function(){ if (visible(this)) return this }, | |
hidden: function(){ if (!visible(this)) return this }, | |
selected: function(){ if (this.selected) return this }, | |
checked: function(){ if (this.checked) return this }, | |
parent: function(){ return this.parentNode }, | |
first: function(idx){ if (idx === 0) return this }, | |
last: function(idx, nodes){ if (idx === nodes.length - 1) return this }, | |
eq: function(idx, _, value){ if (idx === value) return this }, | |
contains: function(idx, _, text){ if ($(this).text().indexOf(text) > -1) return this }, | |
has: function(idx, _, sel){ if (zepto.qsa(this, sel).length) return this } | |
} | |
var re = new RegExp('(.*):(\\w+)(?:\\(([^)]+)\\))?$\\s*') | |
function process(sel, fn) { | |
var filter, arg, match = sel.match(re) | |
if (match && match[2] in filters) { | |
var filter = filters[match[2]], arg = match[3] | |
sel = match[1] | |
if (arg) { | |
var num = Number(arg) | |
if (isNaN(num)) arg = arg.replace(/^["']|["']$/g, '') | |
else arg = num | |
} | |
} | |
return fn(sel, filter, arg) | |
} | |
zepto.qsa = function(node, selector) { | |
return process(selector, function(sel, filter, arg){ | |
try { | |
if (!sel && filter) sel = '*' | |
var nodes = oldQsa(node, sel) | |
} catch(e) { | |
console.error('error performing selector: %o', selector) | |
throw e | |
} | |
return !filter ? nodes : | |
zepto.uniq($.map(nodes, function(n, i){ return filter.call(n, i, nodes, arg) })) | |
}) | |
} | |
zepto.matches = function(node, selector){ | |
return process(selector, function(sel, filter, arg){ | |
return (!sel || oldMatches(node, sel)) && | |
(!filter || filter.call(node, null, arg) === node) | |
}) | |
} | |
})(Zepto) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment