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