Files: c431b9f86d04597436c8fd31782d8ab7a1a65f4e / modules_extra / search.js
2334 bytesRaw
1 | var h = require('hyperscript') |
2 | var u = require('../util') |
3 | var pull = require('pull-stream') |
4 | var Scroller = require('pull-scroll') |
5 | var TextNodeSearcher = require('text-node-searcher') |
6 | |
7 | exports.needs = { |
8 | build_scroller: 'first', |
9 | message_render: 'first', |
10 | sbot_log: 'first' |
11 | } |
12 | |
13 | exports.gives = 'screen_view' |
14 | |
15 | var whitespace = /\s+/ |
16 | |
17 | function andSearch(terms, inputs) { |
18 | for(var i = 0; i < terms.length; i++) { |
19 | var match = false |
20 | for(var j = 0; j < inputs.length; j++) { |
21 | if(terms[i].test(inputs[j])) match = true |
22 | } |
23 | //if a term was not matched by anything, filter this one |
24 | if(!match) return false |
25 | } |
26 | return true |
27 | } |
28 | |
29 | function searchFilter(terms) { |
30 | return function (msg) { |
31 | var c = msg && msg.value && msg.value.content |
32 | return c && ( |
33 | msg.key == terms[0] || |
34 | andSearch(terms.map(function (term) { |
35 | return new RegExp('\\b'+term+'\\b', 'i') |
36 | }), [c.text, c.name, c.title]) |
37 | ) |
38 | } |
39 | } |
40 | |
41 | function createOrRegExp(ary) { |
42 | return new RegExp(ary.map(function (e) { |
43 | return '\\b'+e+'\\b' |
44 | }).join('|'), 'i') |
45 | } |
46 | |
47 | function highlight(el, query) { |
48 | var searcher = new TextNodeSearcher({container: el}) |
49 | searcher.query = query |
50 | searcher.highlight() |
51 | return el |
52 | } |
53 | |
54 | exports.create = function (api) { |
55 | |
56 | return function (path) { |
57 | if(path[0] === '?') { |
58 | var query = path.substr(1).trim().split(whitespace) |
59 | var _matches = searchFilter(query) |
60 | |
61 | var total = 0, matches = 0 |
62 | |
63 | var header = h('div.search_header', '') |
64 | var { container, content } = api.build_scroller({ prepend: header}) |
65 | container.id = path // helps tabs find this tab |
66 | |
67 | function matchesQuery (data) { |
68 | total++ |
69 | var m = _matches(data) |
70 | if(m) matches++ |
71 | header.textContent = 'searched:'+total+', found:'+matches |
72 | return m |
73 | } |
74 | |
75 | function renderMsg(msg) { |
76 | var el = api.message_render(msg) |
77 | highlight(el, createOrRegExp(query)) |
78 | return el |
79 | } |
80 | |
81 | pull( |
82 | api.sbot_log({old: false}), |
83 | pull.filter(matchesQuery), |
84 | Scroller(container, content, renderMsg, true, false) |
85 | ) |
86 | |
87 | pull( |
88 | u.next(api.sbot_log, {reverse: true, limit: 500, live: false}), |
89 | pull.filter(matchesQuery), |
90 | Scroller(container, content, renderMsg, false, false) |
91 | ) |
92 | |
93 | return container |
94 | } |
95 | } |
96 | |
97 | } |
98 |
Built with git-ssb-web