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