hardlounge/client/js/socket.js

54 lines
1.6 KiB
JavaScript
Raw Normal View History

2017-04-18 03:31:46 -04:00
"use strict";
const $ = require("jquery");
const io = require("socket.io-client");
2017-09-10 11:28:28 -04:00
const utils = require("./utils");
2017-04-18 03:31:46 -04:00
const socket = io({
transports: $(document.body).data("transports"),
path: window.location.pathname + "socket.io/",
2017-04-18 03:31:46 -04:00
autoConnect: false,
reconnection: !$(document.body).hasClass("public"),
2017-04-18 03:31:46 -04:00
});
2017-08-28 11:03:27 -04:00
socket.on("disconnect", handleDisconnect);
socket.on("connect_error", handleDisconnect);
socket.on("error", handleDisconnect);
socket.on("reconnecting", function(attempt) {
$("#loading-page-message, #connection-error").text(`Reconnecting… (attempt ${attempt})`);
2017-04-18 03:31:46 -04:00
});
socket.on("connecting", function() {
$("#loading-page-message, #connection-error").text("Connecting…");
2017-04-18 03:31:46 -04:00
});
socket.on("connect", function() {
// Clear send buffer when reconnecting, socket.io would emit these
// immediately upon connection and it will have no effect, so we ensure
// nothing is sent to the server that might have happened.
socket.sendBuffer = [];
$("#loading-page-message, #connection-error").text("Finalizing connection…");
2017-04-18 03:31:46 -04:00
});
socket.on("authorized", function() {
$("#loading-page-message, #connection-error").text("Loading messages…");
2017-04-18 03:31:46 -04:00
});
2017-08-28 11:03:27 -04:00
function handleDisconnect(data) {
const message = data.message || data;
$("#loading-page-message, #connection-error").text(`Waiting to reconnect… (${message})`).addClass("shown");
$(".show-more button, #input").prop("disabled", true);
2017-08-28 11:03:27 -04:00
$("#submit").hide();
2017-09-10 11:28:28 -04:00
// If the server shuts down, socket.io skips reconnection
// and we have to manually call connect to start the process
if (socket.io.skipReconnect) {
utils.requestIdleCallback(() => socket.connect(), 2000);
}
2017-08-28 11:03:27 -04:00
}
2017-04-18 03:31:46 -04:00
module.exports = socket;