summaryrefslogtreecommitdiff
path: root/js/catalog-search.js
blob: fc39b1ce31c725a9fc0a0d8f7774c4d6b1fbea70 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
 * catalog-search.js
 * https://github.com/mgrabovsky/lainchan/blob/catalog-search/js/catalog-search.js
 *
 * Released under the MIT license
 * Copyright (c) 2015 Matěj Grabovský <matej.grabovsky@gmail.com>
 *
 * Usage:
 *   $config['additional_javascript'][] = 'js/jquery.min.js';
 *   $config['additional_javascript'][] = 'js/catalog-search.js';
 */

(function() {

var catalogSearch = function() {
	var $controls = $('.controls'),
		$threads = $('.threads .thread'),
		$searchLabel = $('<label for="catalog_search">Search: </label>'),
		$searchBox = $('<input id="catalog_search" type="text" placeholder="Search" />');
		function searchToggle() {
			var button = $('#catalog_search_button');

			if (!button.data('expanded')) {
				button.data('expanded', '1');
				button.text('Close');
				$('.catalog_search').append(' <input id="search_field" style="border: inset 1px;">');
				$('#search_field').focus();
			} else {
				button.removeData('expanded');
				button.text('Search');
				$('.catalog_search').children().last().remove();
				$('div[id="Grid"]>.mix').each(function () { $(this).css('display', 'inline-block'); });
			}
		}

	$controls.append($searchLabel)
			.append($searchBox);

	$searchBox.keyup(function() {
		var $found = searchThreads($threads, this.value);
		$threads.hide();
		$found.show();
	});

	var m = location.hash.match(/[#&]s=([^&]+)/);
	if(m) {
		$searchBox.val(decodeURIComponent(m[1])).keyup();
	}
};

// Filter threads by their content, given a regex. Can be extended to load data
// remotely and filter by multiple fields
var searchThreads = function($threads, query) {
	var re = new RegExp(query, 'mi');
	return $threads.filter(function() {
		return re.test($('.replies', this).text());
	});
};

// Only load in the catalog
if (active_page == 'catalog') {
	onready(catalogSearch);
}

}());