aboutsummaryrefslogtreecommitdiff
path: root/public
diff options
context:
space:
mode:
Diffstat (limited to 'public')
-rw-r--r--public/index.html1
-rw-r--r--public/main.js12
-rw-r--r--public/sock.js43
3 files changed, 53 insertions, 3 deletions
diff --git a/public/index.html b/public/index.html
index c3828a5..a5892c1 100644
--- a/public/index.html
+++ b/public/index.html
@@ -11,6 +11,7 @@
<body>
<h1>nomicvote</h1>
+ <script src="sock.js"></script>
<script src="main.js"></script>
</body>
</html>
diff --git a/public/main.js b/public/main.js
index b3c7986..46d5432 100644
--- a/public/main.js
+++ b/public/main.js
@@ -2,9 +2,15 @@ document.addEventListener("DOMContentLoaded", async () => { "use strict"
const $ = s => document.querySelector(s);
const secure = location.protocol === "https:";
-const sock = new WebSocket(`ws${secure?"s":""}://${location.host}/ws`);
+sock.init(`ws${secure?"s":""}://${location.host}/ws`);
-sock.onmessage = e => console.log("sock", e);
-sock.onopen = () => sock.send("yay");
+sock.on("hello", e => {
+ console.log("hello", e);
+ sock.send("world", {foo:"bar"});
+});
+
+sock.on("yay", e => {
+ console.log("yay", e);
+});
});
diff --git a/public/sock.js b/public/sock.js
new file mode 100644
index 0000000..8cc73f0
--- /dev/null
+++ b/public/sock.js
@@ -0,0 +1,43 @@
+const sock = (() => { "use strict"
+const refresh = () => setTimeout(() => location.reload(), 1e3);
+
+let ws, pingTimeout;
+const prequeue = [];
+const handlers = {
+ "reset": [refresh],
+ "ping": [() => {
+ clearTimeout(pingTimeout);
+ pingTimeout = setTimeout(refresh, 3e4);
+ sock.send("pong", {});
+ }],
+};
+
+const sock = {
+ init: url => {
+ ws = new WebSocket(url);
+ ws.addEventListener("close", refresh);
+ ws.addEventListener("error", refresh);
+ ws.addEventListener("message", e => {
+ const d = JSON.parse(e.data);
+ (handlers[d.type]||[]).forEach(cb => cb(d.data));
+ });
+ ws.addEventListener("open", e => {
+ while (prequeue.length) sock.send(...prequeue.shift());
+ (handlers["open"]||[]).forEach(cb => cb());
+ delete handlers["open"];
+ });
+ },
+
+ on: (type, cb) => {
+ if (type === "open" && ws && ws.readyState === WebSocket.OPEN) cb();
+ else (handlers[type]||(handlers[type]=[])).push(cb);
+ },
+
+ send: (type, data) => {
+ if (ws && ws.readyState === WebSocket.OPEN)
+ ws.send(JSON.stringify({type, data}));
+ else prequeue.push([type, data]);
+ },
+};
+
+return sock })();