Files: 1b46fe809a87f906b19ab7dad059971d13730b4f / app / page / statsShow.js
10207 bytesRaw
1 | const nest = require('depnest') |
2 | const { h, when, Value, Struct, Array: MutantArray, Dict, onceTrue, map, computed, throttle, watchAll } = require('mutant') |
3 | const pull = require('pull-stream') |
4 | const marksum = require('markdown-summary') |
5 | const Chart = require('chart.js') |
6 | const groupBy = require('lodash/groupBy') |
7 | const flatMap = require('lodash/flatMap') |
8 | const get = require('lodash/get') |
9 | |
10 | const chartConfig = require('../../config/chart') |
11 | |
12 | exports.gives = nest('app.page.statsShow') |
13 | |
14 | exports.needs = nest({ |
15 | 'sbot.obs.connection': 'first', |
16 | 'history.sync.push': 'first', |
17 | 'message.html.markdown': 'first', |
18 | 'translations.sync.strings': 'first' |
19 | }) |
20 | |
21 | const COMMENTS = 'comments' |
22 | const LIKES = 'likes' |
23 | const SHARES = 'shares' |
24 | const DAY = 24 * 60 * 60 * 1000 |
25 | |
26 | const getRoot = { |
27 | [COMMENTS]: (msg) => get(msg, 'value.content.root'), |
28 | [LIKES]: (msg) => get(msg, 'value.content.vote.link') |
29 | } |
30 | |
31 | exports.create = (api) => { |
32 | return nest('app.page.statsShow', statsShow) |
33 | |
34 | function statsShow (location) { |
35 | const strings = api.translations.sync.strings() |
36 | const t = strings.statsShow |
37 | |
38 | var store = Struct({ |
39 | blogs: MutantArray([]), |
40 | comments: Dict(), |
41 | likes: Dict(), |
42 | shares: Dict() |
43 | }) |
44 | onceTrue(api.sbot.obs.connection, server => fetchBlogData({ server, store })) |
45 | |
46 | var foci = Struct({ |
47 | [COMMENTS]: computed([throttle(store.comments, 1000)], (msgs) => { |
48 | return flatMap(msgs, (val, key) => val) |
49 | }), |
50 | [LIKES]: computed([throttle(store.likes, 1000)], (msgs) => { |
51 | return flatMap(msgs, (val, key) => val) |
52 | }), |
53 | [SHARES]: [] |
54 | }) |
55 | |
56 | var howFarBack = Value(0) |
57 | // stats show a moving window of 30 days |
58 | var context = Struct({ |
59 | focus: Value(COMMENTS), |
60 | blog: Value(), |
61 | range: computed([howFarBack], howFarBack => { |
62 | const now = Date.now() |
63 | const endOfDay = (Math.floor(now / DAY) + 1) * DAY |
64 | |
65 | return { |
66 | upper: endOfDay - howFarBack * 30 * DAY, |
67 | lower: endOfDay - (howFarBack + 1) * 30 * DAY |
68 | } |
69 | }) |
70 | }) |
71 | |
72 | function totalOnscreenData (focus) { |
73 | return computed([foci[focus], context], (msgs, context) => { |
74 | // NOTE this filter logic is repeated in chartData |
75 | return msgs |
76 | .filter(msg => { |
77 | if (!context.blog) return true |
78 | // if context.blog is set, filter down to only msgs about that blog |
79 | return getRoot[focus](msg) === context.blog |
80 | }) |
81 | .filter(msg => { |
82 | // don't count unlikes |
83 | if (focus === LIKES) return get(msg, 'value.content.vote.value') > 0 |
84 | else return true |
85 | }) |
86 | .filter(msg => { |
87 | const ts = msg.value.timestamp |
88 | return ts > context.range.lower && ts <= context.range.upper |
89 | }) |
90 | .length |
91 | }) |
92 | } |
93 | |
94 | const canvas = h('canvas', { height: 200, width: 600, style: { height: '200px', width: '600px' } }) |
95 | |
96 | const page = h('Page -statsShow', [ |
97 | h('Scroller.content', [ |
98 | h('div.content', [ |
99 | h('h1', t.title), |
100 | h('section.totals', [COMMENTS, LIKES, SHARES].map(focus => { |
101 | return h('div', |
102 | { |
103 | classList: computed(context.focus, f => f === focus ? [focus, '-selected'] : [focus]), |
104 | 'ev-click': () => context.focus.set(focus) |
105 | }, [ |
106 | h('div.count', totalOnscreenData(focus)), |
107 | h('strong', strings[focus]), |
108 | '(', |
109 | t.thirtyDays, |
110 | ')' |
111 | ]) |
112 | })), |
113 | h('section.graph', [ |
114 | canvas, |
115 | h('div.changeRange', [ |
116 | '< ', |
117 | h('a', { 'ev-click': () => howFarBack.set(howFarBack() + 1) }, t.prevMonth), |
118 | ' | ', |
119 | when(howFarBack, |
120 | h('a', { 'ev-click': () => howFarBack.set(howFarBack() - 1) }, t.nextMonth), |
121 | h('span', t.nextMonth) |
122 | ), |
123 | ' >' |
124 | ]) |
125 | ]), |
126 | h('table.blogs', [ |
127 | h('thead', [ |
128 | h('tr', [ |
129 | h('th.details'), |
130 | h('th.comments', strings.comments), |
131 | h('th.likes', strings.likes), |
132 | h('th.shares', strings.shares) |
133 | ]) |
134 | ]), |
135 | h('tbody', map(store.blogs, BlogRow)) |
136 | ]) |
137 | ]) |
138 | ]) |
139 | ]) |
140 | |
141 | function BlogRow (blog) { |
142 | const className = computed(context.blog, b => { |
143 | if (!b) return '' |
144 | if (b !== blog.key) return '-background' |
145 | }) |
146 | |
147 | return h('tr.blog', { id: blog.key, className }, [ |
148 | h('td.details', [ |
149 | h('div.title', { |
150 | 'ev-click': () => { |
151 | if (context.blog() === blog.key) context.blog.set('') |
152 | else context.blog.set(blog.key) |
153 | } |
154 | }, getTitle({ blog, mdRenderer: api.message.html.markdown })), |
155 | h('a', { |
156 | href: '#', |
157 | 'ev-click': ev => { |
158 | ev.stopPropagation() // stop the click catcher! |
159 | api.history.sync.push(blog) |
160 | } |
161 | }, 'View blog') |
162 | ]), |
163 | h('td.comments', computed(store.comments.get(blog.key), msgs => msgs ? msgs.length : 0)), |
164 | h('td.likes', computed(store.likes.get(blog.key), msgs => msgs ? msgs.length : 0)), |
165 | h('td.shares', computed(store.shares.get(blog.key), msgs => msgs ? msgs.length : 0)) |
166 | ]) |
167 | } |
168 | |
169 | initialiseChart({ canvas, context, foci }) |
170 | |
171 | return page |
172 | } |
173 | } |
174 | |
175 | function getTitle ({ blog, mdRenderer }) { |
176 | if (blog.value.content.title) return blog.value.content.title |
177 | else if (blog.value.content.text) { |
178 | var md = mdRenderer(marksum.title(blog.value.content.text)) |
179 | if (md && md.innerText) return md.innerText |
180 | } |
181 | |
182 | return blog.key |
183 | } |
184 | |
185 | function fetchBlogData ({ server, store }) { |
186 | const myKey = server.id |
187 | |
188 | server.blogStats.getBlogs({}, (err, blogs) => { |
189 | if (err) console.error(err) |
190 | |
191 | // TODO - change this once merge in the new notifications-hanger work |
192 | // i.e. do one query for ALL comments on my blogs as opposed to N queries |
193 | blogs.forEach(blog => { |
194 | fetchComments({ server, store, blog }) |
195 | fetchLikes({ server, store, blog }) |
196 | }) |
197 | |
198 | blogs = blogs |
199 | .sort((a, b) => a.value.timestamp > b.value.timestamp ? -1 : +1) |
200 | store.blogs.set(blogs) |
201 | }) |
202 | |
203 | function fetchComments ({ server, store, blog }) { |
204 | if (!store.comments.has(blog.key)) store.comments.put(blog.key, MutantArray()) |
205 | |
206 | pull( |
207 | server.blogStats.readComments(blog), |
208 | pull.drain(msg => { |
209 | if (msg.value.author === myKey) return |
210 | store.comments.get(blog.key).push(msg) |
211 | }) |
212 | ) |
213 | } |
214 | |
215 | function fetchLikes ({ server, store, blog }) { |
216 | if (!store.likes.has(blog.key)) store.likes.put(blog.key, MutantArray()) |
217 | |
218 | pull( |
219 | server.blogStats.readLikes(blog), |
220 | pull.drain(msg => { |
221 | if (msg.value.author === myKey) return |
222 | |
223 | const isUnlike = get(msg, 'value.content.vote.value', 1) < 1 |
224 | |
225 | var likes = store.likes.get(blog.key) |
226 | var extantLike = likes.find(m => m.value.author === msg.value.author) |
227 | // extant means existing |
228 | |
229 | if (!extantLike) return likes.push(msg) |
230 | else { |
231 | if (msg.value.timestamp < extantLike.value.timestamp) return |
232 | else { |
233 | // case: we have a new like/ unlike value |
234 | if (isUnlike) likes.delete(extantLike) |
235 | else likes.put(likes.indexOf(extantLike), msg) |
236 | } |
237 | } |
238 | }) |
239 | ) |
240 | } |
241 | } |
242 | |
243 | function initialiseChart ({ canvas, context, foci }) { |
244 | var chart = new Chart(canvas.getContext('2d'), chartConfig({ context })) |
245 | |
246 | const chartData = computed([context, foci], (context, foci) => { |
247 | fixAnimationWhenNeeded(context) |
248 | |
249 | const { focus } = context |
250 | // NOTE this filter logic is repeated in totalOnscreenData |
251 | const msgs = foci[focus] |
252 | .filter(msg => { |
253 | if (!context.blog) return true |
254 | // if context.blog is set, filter down to only msgs about that blog |
255 | return getRoot[focus](msg) === context.blog |
256 | }) |
257 | .filter(msg => { |
258 | // don't count unlikes |
259 | if (focus === LIKES) return get(msg, 'value.content.vote.value') > 0 |
260 | else return true |
261 | }) |
262 | |
263 | const grouped = groupBy(msgs, m => toDay(m.value.timestamp)) |
264 | |
265 | return Object.keys(grouped) |
266 | .map(day => { |
267 | return { |
268 | t: day * DAY + DAY / 2, |
269 | y: grouped[day].length |
270 | } |
271 | // NOTE - this collects the data points for a day at t = 10ms into the day |
272 | // this is necessary for getting counts to line up (bars, and daily count) |
273 | // I think because total counts for totalOnscreenData don't collect data in the same way? |
274 | // TODO - refactor this, to be tidier |
275 | }) |
276 | }) |
277 | |
278 | chartData(data => { |
279 | chart.data.datasets[0].data = data |
280 | |
281 | chart.update() |
282 | }) |
283 | |
284 | // Scales the height of the graph (to the visible data)! |
285 | watchAll([chartData, context.range], (data, range) => { |
286 | const { lower, upper } = range |
287 | const slice = data |
288 | .filter(d => d.t > lower && d.t <= upper) |
289 | .map(d => d.y) |
290 | .sort((a, b) => a > b ? -1 : +1) |
291 | |
292 | var h = slice[0] |
293 | if (!h || h < 10) h = 10 |
294 | else h = h + (5 - h % 5) |
295 | // set the height of the graph to a minimum or 10, |
296 | // or some multiple of 5 above the max height |
297 | |
298 | chart.options.scales.yAxes[0].ticks.max = h |
299 | |
300 | chart.update() |
301 | }) |
302 | |
303 | // Update the x-axes bounds of the graph! |
304 | context.range(range => { |
305 | const { lower, upper } = range |
306 | |
307 | chart.options.scales.xAxes[0].time.min = lower |
308 | chart.options.scales.xAxes[0].time.max = upper |
309 | |
310 | chart.update() |
311 | }) |
312 | |
313 | // ///// HELPERS ///// |
314 | |
315 | // HACK - if the focus has changed, then zero the data |
316 | // this prevents the graph from showing some confusing animations when transforming between foci / selecting blog |
317 | var prevFocus = context.focus() |
318 | var prevBlog = context.blog() |
319 | function fixAnimationWhenNeeded (context) { |
320 | if (context.focus !== prevFocus || context.blog !== prevBlog) { |
321 | chart.data.datasets[0].data = [] |
322 | chart.update() |
323 | prevFocus = context.focus |
324 | prevBlog = context.blog |
325 | } |
326 | } |
327 | function toDay (ts) { return Math.floor(ts / DAY) } |
328 | } |
329 |
Built with git-ssb-web