hardlounge/client/js/socket.js

66 lines
2.1 KiB
JavaScript
Raw Normal View History

2017-04-18 07:31:46 +00:00
"use strict";
const $ = require("jquery");
const io = require("socket.io-client");
const socket = io({
transports: $(document.body).data("transports"),
path: window.location.pathname + "socket.io/",
2017-04-18 07:31:46 +00:00
autoConnect: false,
reconnection: !$(document.body).hasClass("public"),
2017-04-18 07:31:46 +00:00
});
2018-07-08 17:53:23 +00:00
module.exports = socket;
const store = require("./store").default;
2017-08-28 15:03:27 +00:00
socket.on("disconnect", handleDisconnect);
socket.on("connect_error", handleDisconnect);
socket.on("error", handleDisconnect);
socket.on("reconnecting", function(attempt) {
store.commit("currentUserVisibleError", `Reconnecting… (attempt ${attempt})`);
$("#loading-page-message").text(store.state.currentUserVisibleError);
2017-04-18 07:31:46 +00:00
});
socket.on("connecting", function() {
store.commit("currentUserVisibleError", `Connecting…`);
$("#loading-page-message").text(store.state.currentUserVisibleError);
2017-04-18 07:31:46 +00: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 = [];
store.commit("currentUserVisibleError", "Finalizing connection…");
$("#loading-page-message").text(store.state.currentUserVisibleError);
2017-04-18 07:31:46 +00:00
});
2017-08-28 15:03:27 +00:00
function handleDisconnect(data) {
const message = data.message || data;
store.commit("isConnected", false);
2019-11-05 19:29:51 +00:00
store.commit("currentUserVisibleError", `Waiting to reconnect… (${message})`);
$("#loading-page-message").text(store.state.currentUserVisibleError);
2017-09-10 15:28:28 +00:00
// If the server shuts down, socket.io skips reconnection
// and we have to manually call connect to start the process
2019-11-05 19:29:51 +00:00
// However, do not reconnect if TL client manually closed the connection
if (socket.io.skipReconnect && message !== "io client disconnect") {
2018-07-08 17:53:23 +00:00
requestIdleCallback(() => socket.connect(), 2000);
2017-09-10 15:28:28 +00:00
}
2017-08-28 15:03:27 +00:00
}
2019-11-03 11:23:03 +00:00
function requestIdleCallback(callback, timeout) {
if (window.requestIdleCallback) {
// During an idle period the user agent will run idle callbacks in FIFO order
// until either the idle period ends or there are no more idle callbacks eligible to be run.
window.requestIdleCallback(callback, {timeout});
} else {
callback();
}
}