Files: 08f7f6c18cb0575d7b590616918aeeca015ef462 / channel / async / suggest.js
1598 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', function () { |
19 | loadSuggestions() |
20 | return function (word) { |
21 | if (!word) { |
22 | return suggestions().slice(0, 100) |
23 | } else { |
24 | return suggestions().filter((item) => { |
25 | return item.title.toLowerCase().startsWith(word.toLowerCase()) |
26 | }) |
27 | } |
28 | } |
29 | }) |
30 | |
31 | function loadSuggestions () { |
32 | if (!suggestions) { |
33 | var id = api.keys.sync.id() |
34 | subscribed = api.channel.obs.subscribed(id) |
35 | var recentlyUpdated = api.channel.obs.recent() |
36 | var contacts = computed([subscribed, recentlyUpdated], function (a, b) { |
37 | var result = Array.from(a) |
38 | b.forEach((item, i) => { |
39 | if (!result.includes(item)) { |
40 | result.push(item) |
41 | } |
42 | }) |
43 | return result |
44 | }) |
45 | |
46 | suggestions = map(contacts, suggestion, {idle: true}) |
47 | watch(suggestions) |
48 | } |
49 | } |
50 | |
51 | function suggestion (id) { |
52 | return Struct({ |
53 | title: id, |
54 | id: `#${id}`, |
55 | subtitle: computed([id, subscribed], subscribedCaption), |
56 | value: computed([id], mention) |
57 | }) |
58 | } |
59 | } |
60 | |
61 | function subscribedCaption (id, subscribed) { |
62 | if (subscribed.has(id)) { |
63 | return 'subscribed' |
64 | } |
65 | } |
66 | |
67 | function mention (id) { |
68 | return `[#${id}](#${id})` |
69 | } |
70 |
Built with git-ssb-web