Files: 6b51ef76387825aa524424f71d8d722fa7eba2cf / channel / async / suggest.js
1793 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() |
25 | .sort(() => Math.random() > 0.5 ? +1 : -1) //shuffle |
26 | .slice(0, 100) |
27 | } |
28 | |
29 | word = word.toLowerCase() |
30 | return suggestions() |
31 | .filter(item => ~item.title.toLowerCase().indexOf(word)) |
32 | .sort((a, b) => { |
33 | // if word fragment occurs earlier in name, bump up |
34 | return a.title.indexOf(word) < b.title.indexOf(word) ? -1 : +1 |
35 | }) |
36 | } |
37 | } |
38 | |
39 | function loadSuggestions () { |
40 | if (!suggestions) { |
41 | var id = api.keys.sync.id() |
42 | subscribed = api.channel.obs.subscribed(id) |
43 | var recentlyUpdated = api.channel.obs.recent() |
44 | var contacts = computed([subscribed, recentlyUpdated], function (a, b) { |
45 | var result = Array.from(a) |
46 | b.forEach((item, i) => { |
47 | if (!result.includes(item)) { |
48 | result.push(item) |
49 | } |
50 | }) |
51 | return result |
52 | }) |
53 | |
54 | suggestions = map(contacts, suggestion, {idle: true}) |
55 | watch(suggestions) |
56 | } |
57 | } |
58 | |
59 | function suggestion (id) { |
60 | return Struct({ |
61 | title: id, |
62 | id: `#${id}`, |
63 | subtitle: computed([id, subscribed], subscribedCaption), |
64 | value: `#${id}` |
65 | }) |
66 | } |
67 | } |
68 | |
69 | function subscribedCaption (id, subscribed) { |
70 | if (subscribed.has(id)) { |
71 | return 'subscribed' |
72 | } |
73 | } |
74 | |
75 |
Built with git-ssb-web