Files: e39763f409d19a3fb6f6c9052dccd36946f8be25 / unread.js
1251 bytesRaw
1 | var nest = require('depnest') |
2 | |
3 | exports.gives = nest({ |
4 | 'unread.sync.isUnread': true, |
5 | 'unread.sync.markRead': true, |
6 | }) |
7 | |
8 | //load current state of unread messages. |
9 | |
10 | exports.create = function (api) { |
11 | |
12 | var unread = null |
13 | if(localStorage.unread) { |
14 | try { |
15 | unread = JSON.parse(localStorage.unread) |
16 | } catch (err) {} |
17 | } |
18 | if(!unread) |
19 | unread = {timestamp: Date.now()} |
20 | |
21 | unread.timestamp = unread.timestamp || Date.now() |
22 | |
23 | if(!unread.filter) |
24 | unread.filter = {} |
25 | |
26 | var timer |
27 | function save () { |
28 | if(timer) return |
29 | |
30 | timer = setTimeout(function () { |
31 | timer = null |
32 | console.log('save!', Object.keys(unread.filter).length) |
33 | localStorage.unread = JSON.stringify(unread) |
34 | }, 2e3) |
35 | } |
36 | |
37 | function isUnread(msg) { |
38 | //ignore messages which do not have timestamps |
39 | |
40 | if(!msg.timestamp) return false |
41 | if(msg.timestamp < unread.timestamp) return false |
42 | return !unread.filter[msg.key] |
43 | } |
44 | |
45 | function markRead(msg) { |
46 | if(msg && 'string' === typeof msg.key) { |
47 | if(isUnread(msg)) { |
48 | unread.filter[msg.key] = true |
49 | save() |
50 | return true |
51 | } |
52 | } |
53 | } |
54 | |
55 | document.body.onunload = save |
56 | |
57 | return nest({ |
58 | 'unread.sync.isUnread': isUnread, |
59 | 'unread.sync.markRead': markRead |
60 | }) |
61 | } |
62 | |
63 |
Built with git-ssb-web