-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
84 lines (72 loc) · 2.22 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// client-side example
/*
* DATA/BACKEND
*/
var swarmlog = require('swarmlog')
// you should replace memdb with something that persists if you want the browser
// to store it for later
var memdb = require('memdb')
var db = memdb()
// sublevel is required basically to 'namespace' away the two stores kv uses to
// track data from hyperlogs
var sub = require('subleveldown')
var hyperkv = require('hyperkv')
var log = swarmlog({
keys: require('./keys.json'),
sodium: require('chloride/browser'),
db: sub(db, 'log'),
valueEncoding: 'json',
// hubs: [ 'https://signalhub.mafintosh.com' ]
hubs: [ 'http://localhost:8080' ] // localhost to stop abusing mafintosh's
// signalhub
})
// hyperkv wraps any hyperlog-like API, and swarmlog returns a hyperlog
var kv = hyperkv({
log: log,
db: sub(db, 'kv')
})
function logValByKey(key) {
kv.get(key, function (err, values) {
if (err) console.error(err)
// multiple values can come from a single key
else console.log("messages retrieved from hyperkv: ", values)
})
}
// pulls info about latest node to be replicated into hyperkv
kv.on('update', function (key, value, node) {
console.log('RECEIVED', value)
if (value.hasOwnProperty('msg')) {
loop.update({ msg: value.msg })
logValByKey(key) // just to prove it happened in console
}
})
/*
* TEMPLATING/FRONTEND
*/
var h = require('virtual-dom/h')
var vdom = require('virtual-dom')
var main = require('main-loop') // iconoclastic paleo reactive updates
var loop = main({ msg: "nothing yet" }, render, vdom)
document.querySelector('#container').appendChild(loop.target)
function render(state) {
return h('div#app', [
h('div#swarm-pane', [
h('h1#status', 'data from swarmlog: ' + state.msg || "no messages"),
h('input#submitter', { onkeypress: putText,
value: 'enter text here and tap enter'
})])
])
}
function putText(e) {
var charCode = e.which || event.keyCode
if ( charCode == '13' ) {
// Enter pressed
kv.put('reply', { msg: e.target.value }, function (err, node) {
if (err) console.error(err)
else {
console.log("Submitting data...")
console.log(node)
}
})
}
}