git ssb

10+

Matt McKegg / patchwork



Tree: 01cee878b8ca9ff653f893db11ea3abc0f7eb5f8

Files: 01cee878b8ca9ff653f893db11ea3abc0f7eb5f8 / modules / feed / html / rollup.js

12794 bytesRaw
1var nest = require('depnest')
2var {Value, Proxy, Array: MutantArray, h, computed, when, onceTrue, throttle} = require('mutant')
3var pull = require('pull-stream')
4var Abortable = require('pull-abortable')
5var Scroller = require('../../../lib/scroller')
6var nextStepper = require('../../../lib/next-stepper')
7var extend = require('xtend')
8var paramap = require('pull-paramap')
9
10var bumpMessages = {
11 'vote': 'liked this message',
12 'post': 'replied to this message',
13 'about': 'added changes',
14 'mention': 'mentioned you',
15 'channel-mention': 'mentioned this channel'
16}
17
18// bump even for first message
19var rootBumpTypes = ['mention', 'channel-mention']
20
21exports.needs = nest({
22 'about.obs.name': 'first',
23 'app.sync.externalHandler': 'first',
24 'message.html.canRender': 'first',
25 'message.html.render': 'first',
26 'message.sync.isBlocked': 'first',
27 'message.sync.unbox': 'first',
28 'message.sync.timestamp': 'first',
29 'profile.html.person': 'first',
30 'channel.html.link': 'first',
31 'message.html.link': 'first',
32 'message.sync.root': 'first',
33 'feed.pull.rollup': 'first',
34 'feed.pull.withReplies': 'first',
35 'feed.pull.unique': 'first',
36 'sbot.async.get': 'first',
37 'keys.sync.id': 'first',
38 'intl.sync.i18n': 'first',
39 'intl.sync.i18n_n': 'first',
40 'message.html.missing': 'first'
41})
42
43exports.gives = nest({
44 'feed.html.rollup': true
45})
46
47exports.create = function (api) {
48 const i18n = api.intl.sync.i18n
49 const i18nPlural = api.intl.sync.i18n_n
50 return nest('feed.html.rollup', function (getStream, {
51 prepend,
52 rootFilter = returnTrue,
53 bumpFilter = returnTrue,
54 compactFilter = returnFalse,
55 prefiltered = false,
56 displayFilter = returnTrue,
57 updateStream, // override the stream used for realtime updates
58 waitFor = true
59 }) {
60 var updates = Value(0)
61 var yourId = api.keys.sync.id()
62 var throttledUpdates = throttle(updates, 200)
63 var updateLoader = h('a Notifier -loader', { href: '#', 'ev-click': refresh }, [
64 'Show ', h('strong', [throttledUpdates]), ' ', plural(throttledUpdates, i18n('update'), i18n('updates'))
65 ])
66
67 var abortLastFeed = null
68 var content = Value()
69 var loading = Proxy(true)
70 var unreadIds = new Set()
71 var newSinceRefresh = new Set()
72 var highlightItems = new Set()
73
74 var container = h('Scroller', {
75 style: { overflow: 'auto' },
76 hooks: [(element) => {
77 // don't activate until added to DOM
78 refresh()
79
80 // deactivate when removed from DOM
81 return () => {
82 if (abortLastFeed) {
83 abortLastFeed()
84 abortLastFeed = null
85 }
86 }
87 }]
88 }, [
89 h('div.wrapper', [
90 h('section.prepend', prepend),
91 content,
92 when(loading, h('Loading -large'))
93 ])
94 ])
95
96 onceTrue(waitFor, () => {
97 // display pending updates
98 pull(
99 updateStream || pull(
100 getStream({old: false}),
101 LookupRoot()
102 ),
103 pull.filter((msg) => {
104 // only render posts that have a root message
105 var root = msg.root || msg
106 return root && root.value && root.value.content && rootFilter(root) && bumpFilter(msg, root) && displayFilter(msg)
107 }),
108 pull.drain((msg) => {
109 if (msg.value.content.type === 'vote') return
110 if (api.app.sync.externalHandler(msg)) return
111
112 // Only increment the 'new since' for items that we render on
113 // the feed as otherwise the 'show <n> updates message' will be
114 // shown on new messages that patchwork cannot render
115 if (canRenderMessage(msg) && msg.value.author !== yourId && (!msg.root || canRenderMessage(msg.root))) {
116 newSinceRefresh.add(msg.key)
117 unreadIds.add(msg.key)
118 }
119
120 if (updates() === 0 && msg.value.author === yourId && container.scrollTop < 500) {
121 refresh()
122 } else if (msg.value.author === yourId && content()) {
123 // dynamically insert this post into the feed! (manually so that it doesn't get slow with mutant)
124 var existingContainer = content().querySelector(`[data-root-id="${msg.value.content.root}"]`)
125 if (existingContainer) {
126 var replies = existingContainer.querySelector('div.replies')
127 var lastReply = existingContainer.querySelector('div.replies > .Message:last-child')
128 var previousId = lastReply ? lastReply.getAttribute('data-id') : existingContainer.getAttribute('data-root-id')
129 replies.appendChild(api.message.html.render(msg, {
130 previousId,
131 compact: false,
132 priority: 2
133 }))
134 }
135 }
136
137 updates.set(newSinceRefresh.size)
138 })
139 )
140 })
141
142 var result = MutantArray([
143 when(updates, updateLoader),
144 container
145 ])
146
147 result.pendingUpdates = throttledUpdates
148 result.reload = refresh
149
150 return result
151
152 function canRenderMessage (msg) {
153 return api.message.html.canRender(msg)
154 }
155
156 function refresh () {
157 onceTrue(waitFor, () => {
158 if (abortLastFeed) abortLastFeed()
159 updates.set(0)
160 content.set(h('section.content'))
161
162 var abortable = Abortable()
163 abortLastFeed = abortable.abort
164
165 highlightItems = newSinceRefresh
166 newSinceRefresh = new Set()
167
168 var done = Value(false)
169 var stream = nextStepper(getStream, {reverse: true, limit: 50})
170 var scroller = Scroller(container, content(), renderItem, {
171 onDone: () => done.set(true),
172 onItemVisible: (item) => {
173 if (Array.isArray(item.msgIds)) {
174 item.msgIds.forEach(id => {
175 unreadIds.delete(id)
176 })
177 }
178 }
179 })
180
181 // track loading state
182 loading.set(computed([done, scroller.queue], (done, queue) => {
183 return !done && queue < 5
184 }))
185
186 pull(
187 stream,
188 abortable,
189 pull.filter(msg => msg && msg.value && msg.value.content),
190 prefiltered ? pull(
191 pull.filter(msg => !api.message.sync.isBlocked(msg)),
192 pull.filter(rootFilter),
193 api.feed.pull.unique(),
194 api.feed.pull.withReplies()
195 ) : pull(
196 pull.filter(bumpFilter),
197 api.feed.pull.rollup(rootFilter)
198 ),
199 scroller
200 )
201 })
202 }
203
204 function renderItem (item, opts) {
205 var partial = opts && opts.partial
206 var meta = null
207 var previousId = item.key
208
209 var groupedBumps = {}
210 var lastBumpType = null
211
212 var rootBumpType = bumpFilter(item)
213 if (rootBumpTypes.includes(rootBumpType)) {
214 lastBumpType = rootBumpType
215 groupedBumps[lastBumpType] = [item]
216 }
217
218 item.replies.forEach(msg => {
219 var value = bumpFilter(msg)
220 if (value) {
221 var type = typeof value === 'string' ? value : getType(msg)
222 ;(groupedBumps[type] = groupedBumps[type] || []).unshift(msg)
223 lastBumpType = type
224 }
225 })
226
227 var replies = item.replies.filter(isReply).sort(byAssertedTime)
228 var highlightedReplies = replies.filter(getPriority)
229 var replyElements = replies.filter(displayFilter).slice(-3).map((msg) => {
230 var result = api.message.html.render(msg, {
231 previousId,
232 compact: compactFilter(msg, item),
233 priority: getPriority(msg)
234 })
235 previousId = msg.key
236
237 return [
238 // insert missing message marker (if can't be found)
239 api.message.html.missing(last(msg.value.content.branch), msg),
240 result
241 ]
242 })
243
244 var renderedMessage = api.message.html.render(item, {
245 compact: compactFilter(item),
246 includeForks: false, // this is a root message, so forks are already displayed as replies
247 priority: getPriority(item)
248 })
249
250 unreadIds.delete(item.key)
251
252 if (!renderedMessage) return h('div')
253
254 if (rootBumpType === 'matches-channel') {
255 var channels = new Set()
256 if (item.filterResult) {
257 if (item.filterResult.matchesChannel) channels.add(item.value.content.channel)
258 if (Array.isArray(item.filterResult.matchingTags)) item.filterResult.matchingTags.forEach(x => channels.add(x))
259 }
260 meta = h('div.meta', [
261 many(channels, api.channel.html.link, i18n), ' ', i18n('mentioned in your network')
262 ])
263 } else if (lastBumpType) {
264 var bumps = lastBumpType === 'vote'
265 ? getLikeAuthors(groupedBumps[lastBumpType])
266 : getAuthors(groupedBumps[lastBumpType])
267
268 if (lastBumpType === 'matches-channel' && item.value.content.channel) {
269 var channel = api.channel.html.link(item.value.content.channel)
270 meta = h('div.meta', [
271 i18nPlural('%s people from your network replied to this message on ', groupedBumps[lastBumpType].length), channel
272 ])
273 } else {
274 var description = i18n(bumpMessages[lastBumpType] || 'added changes')
275 meta = h('div.meta', [
276 many(bumps, api.profile.html.person, i18n), ' ', description
277 ])
278 }
279 }
280
281 // if there are new messages, view full thread goes to the top of those, otherwise to very first reply
282 var anchorReply = highlightedReplies.length >= 3 ? highlightedReplies[0] : replies[0]
283
284 var result = h('FeedEvent -post', {
285 attributes: {
286 'data-root-id': item.key
287 }
288 }, [
289 meta,
290 renderedMessage,
291 when(replies.length > replyElements.length || partial,
292 h('a.full', {href: item.key, anchor: anchorReply && anchorReply.key}, [i18n('View full thread') + ' (', replies.length, ')'])
293 ),
294 h('div.replies', replyElements)
295 ])
296
297 result.msgIds = [item.key].concat(item.replies.map(x => x.key))
298
299 return result
300 }
301
302 function getPriority (msg) {
303 if (highlightItems.has(msg.key)) {
304 return 2
305 } else if (unreadIds.has(msg.key)) {
306 return 1
307 } else {
308 return 0
309 }
310 }
311 })
312
313 function LookupRoot () {
314 return paramap((msg, cb) => {
315 var rootId = api.message.sync.root(msg)
316 if (rootId) {
317 api.sbot.async.get(rootId, (_, value) => {
318 if (value && typeof value.content === 'string') {
319 // unbox private message
320 value = api.message.sync.unbox(value)
321 }
322 cb(null, extend(msg, {
323 root: {key: rootId, value}
324 }))
325 })
326 } else {
327 cb(null, msg)
328 }
329 })
330 }
331
332 function byAssertedTime (a, b) {
333 return api.message.sync.timestamp(a) - api.message.sync.timestamp(b)
334 }
335}
336
337function plural (value, single, many) {
338 return computed(value, (value) => {
339 if (value === 1) {
340 return single
341 } else {
342 return many
343 }
344 })
345}
346
347function many (ids, fn, intl) {
348 ids = Array.from(ids)
349 var featuredIds = ids.slice(0, 4)
350
351 if (ids.length) {
352 if (ids.length > 4) {
353 return [
354 fn(featuredIds[0]), ', ',
355 fn(featuredIds[1]), ', ',
356 fn(featuredIds[2]), intl(' and '),
357 ids.length - 3, intl(' others')
358 ]
359 } else if (ids.length === 4) {
360 return [
361 fn(featuredIds[0]), ', ',
362 fn(featuredIds[1]), ', ',
363 fn(featuredIds[2]), intl(' and '),
364 fn(featuredIds[3])
365 ]
366 } else if (ids.length === 3) {
367 return [
368 fn(featuredIds[0]), ', ',
369 fn(featuredIds[1]), intl(' and '),
370 fn(featuredIds[2])
371 ]
372 } else if (ids.length === 2) {
373 return [
374 fn(featuredIds[0]), intl(' and '),
375 fn(featuredIds[1])
376 ]
377 } else {
378 return fn(featuredIds[0])
379 }
380 }
381}
382
383function getAuthors (items) {
384 return items.reduce((result, msg) => {
385 result.add(msg.value.author)
386 return result
387 }, new Set())
388}
389
390function getLikeAuthors (items) {
391 return items.reduce((result, msg) => {
392 if (msg.value.content.type === 'vote') {
393 if (msg.value.content && msg.value.content.vote && msg.value.content.vote.value === 1) {
394 result.add(msg.value.author)
395 } else {
396 result.delete(msg.value.author)
397 }
398 }
399 return result
400 }, new Set())
401}
402
403function isReply (msg) {
404 if (msg.value && msg.value.content) {
405 var type = msg.value.content.type
406 return type === 'post' || (type === 'about' && msg.value.content.attendee)
407 }
408}
409
410function getType (msg) {
411 return msg && msg.value && msg.value.content && msg.value.content.type
412}
413
414function returnTrue () {
415 return true
416}
417
418function returnFalse () {
419 return false
420}
421
422function last (array) {
423 if (Array.isArray(array)) {
424 return array[array.length - 1]
425 } else {
426 return array
427 }
428}
429

Built with git-ssb-web