git ssb

10+

Matt McKegg / patchwork



Tree: 65ce43c530961dac5a312bda0a2f882c2b075ac7

Files: 65ce43c530961dac5a312bda0a2f882c2b075ac7 / modules / channel / obs / suggest.js

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

Built with git-ssb-web