| 1 |
(function ($) { |
| 2 |
|
| 3 |
var timer = 0; |
| 4 |
|
| 5 |
var sel = function (ptr, context) { |
| 6 |
if ($.isFunction(ptr)) |
| 7 |
return ptr.apply(context); |
| 8 |
return typeof ptr == "string" ? context.find(ptr) : ptr; |
| 9 |
}; |
| 10 |
|
| 11 |
// Writes text into box, wrapping the first match of re in the highlight element. |
| 12 |
// Text is only ever inserted as text nodes so names are never parsed as HTML. |
| 13 |
var highlight = function (box, text, re, opts) { |
| 14 |
var m = re ? text.match(re) : null; |
| 15 |
if (!m || !m[0].length) { |
| 16 |
box.text(text); |
| 17 |
return; |
| 18 |
} |
| 19 |
box.empty().append( |
| 20 |
document.createTextNode(text.slice(0, m.index)), |
| 21 |
$(opts.highlight).text(m[0]), |
| 22 |
document.createTextNode(text.slice(m.index + m[0].length)) |
| 23 |
); |
| 24 |
}; |
| 25 |
|
| 26 |
var filter = function (obj, search, opts) { |
| 27 |
var re = new RegExp(search.replace(/[.*+?^${}()|[\]\\-]/g, "\\$&"), |
| 28 |
opts.caseSensitive ? "" : "i"); |
| 29 |
var ctx = sel(opts.element, obj); |
| 30 |
var n = 0; |
| 31 |
var size = opts.stepSize || 100; |
| 32 |
|
| 33 |
var step = function () { |
| 34 |
for (var i = 0; i < size; i++) { |
| 35 |
|
| 36 |
if (n >= ctx.length) { |
| 37 |
if (opts.after) |
| 38 |
opts.after.apply(ctx); |
| 39 |
return; |
| 40 |
} |
| 41 |
|
| 42 |
var e = $(ctx[n++]); |
| 43 |
|
| 44 |
var box = opts.subject ? sel(opts.subject, e) : this; |
| 45 |
var val = box.text(); |
| 46 |
|
| 47 |
if (!e.hasClass('hidden')) { |
| 48 |
if (!search.length) { |
| 49 |
e.show(); |
| 50 |
if (opts.highlight) { |
| 51 |
highlight(box, val, null, opts); |
| 52 |
} |
| 53 |
} else if (val.match(re)) { |
| 54 |
e.show(); |
| 55 |
if (opts.highlight) { |
| 56 |
highlight(box, val, re, opts); |
| 57 |
} |
| 58 |
} else { |
| 59 |
e.hide(); |
| 60 |
} |
| 61 |
} |
| 62 |
} |
| 63 |
timer = setTimeout(step, 1); |
| 64 |
}; |
| 65 |
|
| 66 |
clearTimeout(timer); |
| 67 |
step(); |
| 68 |
|
| 69 |
}; |
| 70 |
|
| 71 |
$.fn.searchFilter = function (opts) { |
| 72 |
$(this).on("keyup", function () { |
| 73 |
filter(this, this.value, opts) |
| 74 |
}); |
| 75 |
$(this).on("change", function () { |
| 76 |
filter(this, this.value, opts) |
| 77 |
}); |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
})(window.jQuery); |