Skip to content

Instantly share code, notes, and snippets.

@carsonfarmer carsonfarmer/index.html

Last active Sep 5, 2018
Embed
What would you like to do?
Intermediate State of Chat Dapp
<!doctype html>
<html>
<head>
<meta charset="utf8">
<title>Chat ĐApp</title>
<link rel="stylesheet" href="./style.css">
</head>
<body>
<div id="main">
<div class="controls">
<input id="name" type="text" data-bind="value: name"
placeholder="Pick a name (or remain anonymous)"/>
</div>
<div class="output"
data-bind="foreach: { data: messages, as: 'msg' }">
<div>
<a data-bind="text: msg.name,
css: { local: msg.from === $root.id() },
attr: { href: `ipfs.io/ipns/${msg.from}` }">
</a>
<div data-bind="text: msg.text"></div>
</div>
</div>
<div class="input">
<input id="text" type="text" placeholder="Type a message"
data-bind="value: message, enable: subscribed" />
</div>
</div>
<script src="bundle.js"></script>
</body>
</html>
import 'babel-polyfill'
import Room from 'ipfs-pubsub-room'
import IPFS from 'ipfs'
import ko from 'knockout'
import queryString from 'query-string'
// Global references for demo purposes
let ipfs
let viewModel
const setup = async () => {
// Create view model with properties to control chat
function ViewModel() {
let self = this
// Stores username
self.name = ko.observable('')
// Stores current message
self.message = ko.observable('')
// Stores array of messages
self.messages = ko.observableArray([])
// Stores local peer id
self.id = ko.observable(null)
// Stores whether we've successfully subscribed to the room
self.subscribed = ko.observable(false)
// Logs latest error (just there in case we want it)
self.error = ko.observable(null)
// We compute the ipns link on the fly from the peer id
self.url = ko.pureComputed(() => {
return `https://ipfs.io/ipns/${self.id()}`
})
}
// Create default view model used for binding ui elements etc.
viewModel = new ViewModel()
// Apply default bindings
ko.applyBindings(viewModel)
window.viewModel = viewModel // Just for demo purposes later!
try {
ipfs = new IPFS({
// We need to enable pubsub...
EXPERIMENTAL: {
pubsub: true
},
config: {
Addresses: {
// ...And supply swarm address to announce on
Swarm: [
'/dns4/ws-star.discovery.libp2p.io/tcp/443/wss/p2p-websocket-star'
]
}
}
})
} catch(err) {
console.error('Failed to initialize peer', err)
viewModel.error(err) // Log error...
}
}
setup()
html, body {
margin: 10px;
font-family: Tahoma, Helvetica, Verdana, sans-serif;
}
input, label {
width: 100%;
height: 20px;
}
a:link, a:hover, a:visited {
color: darkgrey;
text-decoration: none;
}
.output {
margin: 10px 0px;
height: calc(100vh - 120px);
overflow: scroll;
display: flex;
flex-direction: column-reverse;
}
a.local {
color: lightblue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.