Files: f0235b59cf6966ab85150a690a3c660bc0dc7f15 / modules / channel / obs / suggest.js
1851 bytesRaw
1 | var nest = require('depnest') |
2 | var {Struct, map, computed, watch} = require('mutant') |
3 | |
4 | exports.needs = nest({ |
5 | 'channel.obs.recent': 'first', |
6 | 'channel.obs.subscribed': 'first', |
7 | 'channel.obs.mostActive': 'first', |
8 | 'keys.sync.id': 'first' |
9 | }) |
10 | |
11 | exports.gives = nest('channel.async.suggest') |
12 | |
13 | exports.create = function (api) { |
14 | var suggestions = null |
15 | var subscribed = null |
16 | |
17 | return nest('channel.async.suggest', function () { |
18 | loadSuggestions() |
19 | return function (word) { |
20 | if (!word) { |
21 | return suggestions().slice(0, 200) |
22 | } else { |
23 | return suggestions().filter((item) => { |
24 | return item.title.toLowerCase().startsWith(word.toLowerCase()) |
25 | }) |
26 | } |
27 | } |
28 | }) |
29 | |
30 | function loadSuggestions () { |
31 | if (!suggestions) { |
32 | var id = api.keys.sync.id() |
33 | subscribed = api.channel.obs.subscribed(id) |
34 | var mostActive = api.channel.obs.mostActive() |
35 | var contacts = computed([subscribed, mostActive], function (a, b) { |
36 | var result = Array.from(a) |
37 | b.forEach((item, i) => { |
38 | if (!result.includes(item[0])) { |
39 | result.push(item) |
40 | } |
41 | }) |
42 | return result |
43 | }) |
44 | |
45 | suggestions = map(contacts, suggestion, {idle: true}) |
46 | watch(suggestions) |
47 | } |
48 | } |
49 | |
50 | function suggestion (id) { |
51 | if (Array.isArray(id)) { |
52 | return Struct({ |
53 | title: id[0], |
54 | id: `#${id[0]}`, |
55 | subtitle: computed([id[0], subscribed, `(${id[1]})`], subscribedCaption), |
56 | value: `#${id[0]}` |
57 | }) |
58 | } else { |
59 | return Struct({ |
60 | title: id, |
61 | id: `#${id}`, |
62 | subtitle: computed([id, subscribed], subscribedCaption), |
63 | value: `#${id}` |
64 | }) |
65 | } |
66 | } |
67 | } |
68 | |
69 | function subscribedCaption (id, subscribed, fallback) { |
70 | if (subscribed.has(id)) { |
71 | return 'subscribed' |
72 | } else { |
73 | return fallback || '' |
74 | } |
75 | } |
76 |
Built with git-ssb-web