git ssb

16+

Dominic / patchbay



Tree: 652e17c6ca36341c8b5f36c66780d9bae9bfc721

Files: 652e17c6ca36341c8b5f36c66780d9bae9bfc721 / modules_extra / search.js

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

Built with git-ssb-web