Skip to content

Instantly share code, notes, and snippets.

@michaschwab
Created April 20, 2020 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michaschwab/20d5f1e5daa091e699f5de4be662ea7d to your computer and use it in GitHub Desktop.
Save michaschwab/20d5f1e5daa091e699f5de4be662ea7d to your computer and use it in GitHub Desktop.
VisConnect Chat Example

This is an example of how VisConnect's event sharing can be used to easily create a chat application.

<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="https://unpkg.com/peerjs@1.0.4/dist/peerjs.min.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://michaschwab.github.io/VisConnect/visconnect-bundle.js"></script>
<link href="style.css" rel="stylesheet" />
</head>
<body collaboration="live" custom-events="chat-message" ignore-events="click, mousedown, mouseup, mousemove, selectstart, dragstart">
<div id="wrapper">
<h1>Chat</h1>
<div id="chat"></div>
<form>
<input id="chat-nick" size="60" value="Guest" type="text" name="nick" />
<input id="chat-input" size="60" type="text" name="message" />
</form>
<script src="js.js"></script>
</div>
</body>
</html>
document.body.addEventListener('keyup', (e) => {
if (e.key === 'Enter') {
const data = {
sender: document.getElementById('chat-nick').value,
text: document.getElementById('chat-input').value,
time: Date.now()
};
const event = new CustomEvent('chat-message', {detail: data});
document.body.dispatchEvent(event);
}
});
const messages = [];
document.body.addEventListener('chat-message', (e) => {
messages.push(e.detail);
rerender();
});
function rerender() {
const chat = d3.select('#chat');
const msgs = chat.selectAll('.msg').data(messages);
msgs.enter().append('div').attr('class', 'msg').html((d) => `<b>${d.sender}</b>: ${d.text}`);
}
#wrapper {
width: 900px;
margin: auto;
}
#chat {
height: 300px;
width: 600px;
overflow-y: auto;
border: 1px solid #ccc;
margin-bottom: 50px;
padding: 5px;
box-sizing: border-box;
}
input {
padding: 7px 15px;
border-radius: 5px;
border: 1px solid #ccc;
outline: none;
box-sizing: border-box;
}
input:focus {
border-color: #666;
}
#chat-nick {
width: 100px;
}
#chat-input {
width: 500px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment