thelounge/client/js/socket.js
Pavel Djundik 2f635069e0 Move vuex state to a separate file and reorganize some code
Co-Authored-By: Tim Miller-Williams <timmw@users.noreply.github.com>
2019-11-25 20:12:54 +02:00

60 lines
1.9 KiB
JavaScript

"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/",
autoConnect: false,
reconnection: !$(document.body).hasClass("public"),
});
module.exports = socket;
const {requestIdleCallback} = require("./utils");
const store = require("./store").default;
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);
});
socket.on("connecting", function() {
store.commit("currentUserVisibleError", `Connecting…`);
$("#loading-page-message").text(store.state.currentUserVisibleError);
});
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);
});
socket.on("authorized", function() {
store.commit("currentUserVisibleError", "Loading messages…");
$("#loading-page-message").text(store.state.currentUserVisibleError);
});
function handleDisconnect(data) {
const message = data.message || data;
store.commit("isConnected", false);
store.commit("currentUserVisibleError", `Waiting to reconnect… (${message})`);
$("#loading-page-message").text(store.state.currentUserVisibleError);
// If the server shuts down, socket.io skips reconnection
// and we have to manually call connect to start the process
if (socket.io.skipReconnect) {
requestIdleCallback(() => socket.connect(), 2000);
}
}