+ },
+ beforeDestroy: function() {
+ this.cleanBeforeDestroy();
+ },
+ methods: {
+ cleanBeforeDestroy: function() {
+ document.removeEventListener('visibilitychange', this.visibilityChange);
+ if (!!this.askLastate)
+ clearInterval(this.askLastate);
+ if (!!this.retrySendmove)
+ clearInterval(this.retrySendmove);
+ if (!!this.clockUpdate)
+ clearInterval(this.clockUpdate);
+ this.send("disconnect");
+ },
+ visibilityChange: function() {
+ // TODO: Use document.hidden? https://webplatform.news/issues/2019-03-27
+ this.send(
+ document.visibilityState == "visible"
+ ? "getfocus"
+ : "losefocus"
+ );
+ },
+ atCreation: function() {
+ document.addEventListener('visibilitychange', this.visibilityChange);
+ // 0] (Re)Set variables
+ this.gameRef = this.$route.params["id"];
+ // next = next corr games IDs to navigate faster (if applicable)
+ this.nextIds = JSON.parse(this.$route.query["next"] || "[]");
+ // Always add myself to players' list
+ const my = this.st.user;
+ this.$set(
+ this.people,
+ my.sid,
+ {
+ id: my.id,
+ name: my.name,
+ focus: true
+ }
+ );
+ this.game = {
+ players: [{ name: "" }, { name: "" }],
+ chats: [],
+ rendered: false
+ };
+ let chatComp = this.$refs["chatcomp"];
+ if (!!chatComp) chatComp.chats = [];
+ this.virtualClocks = [[0,0], [0,0]];
+ this.vr = null;
+ this.drawOffer = "";
+ this.lastateAsked = false;
+ this.rematchOffer = "";
+ this.lastate = undefined;
+ this.roomInitialized = false;
+ this.askGameTime = 0;
+ this.gameIsLoading = false;
+ this.gotLastate = false;
+ this.gotMoveIdx = -1;
+ this.opponentGotMove = false;
+ this.askLastate = null;
+ this.retrySendmove = null;
+ this.clockUpdate = null;
+ this.newConnect = {};
+ this.killed = {};
+ // 1] Initialize connection
+ this.connexionString =
+ params.socketUrl +
+ "/?sid=" +
+ this.st.user.sid +
+ "&id=" +
+ this.st.user.id +
+ "&tmpId=" +
+ getRandString() +
+ "&page=" +
+ // Discard potential "/?next=[...]" for page indication:
+ encodeURIComponent(this.$route.path.match(/\/game\/[a-zA-Z0-9]+/)[0]);
+ this.conn = new WebSocket(this.connexionString);
+ this.conn.addEventListener("message", this.socketMessageListener);
+ this.conn.addEventListener("close", this.socketCloseListener);
+ // Socket init required before loading remote game:
+ const socketInit = callback => {
+ if (this.conn.readyState == 1)
+ // 1 == OPEN state
+ callback();
+ else
+ // Socket not ready yet (initial loading)
+ // NOTE: first arg is Websocket object, unused here:
+ this.conn.onopen = () => callback();
+ };
+ this.fetchGame((game) => {
+ if (!!game)
+ this.loadVariantThenGame(game, () => socketInit(this.roomInit));
+ else
+ // Live game stored remotely: need socket to retrieve it
+ // NOTE: the callback "roomInit" will be lost, so we don't provide it.
+ // --> It will be given when receiving "fullgame" socket event.
+ socketInit(() => { this.send("askfullgame"); });
+ });
+ },
+ roomInit: function() {
+ if (!this.roomInitialized) {
+ // Notify the room only now that I connected, because
+ // messages might be lost otherwise (if game loading is slow)
+ this.send("connect");
+ this.send("pollclients");
+ // We may ask fullgame several times if some moves are lost,
+ // but room should be init only once:
+ this.roomInitialized = true;
+ }
+ },
+ send: function(code, obj) {
+ if (!!this.conn)
+ this.conn.send(JSON.stringify(Object.assign({ code: code }, obj)));
+ },
+ isConnected: function(index) {
+ const player = this.game.players[index];
+ // Is it me ? In this case no need to bother with focus
+ if (this.st.user.sid == player.sid || this.st.user.id == player.id)
+ // Still have to check for name (because of potential multi-accounts
+ // on same browser, although this should be rare...)
+ return (!this.st.user.name || this.st.user.name == player.name);
+ // Try to find a match in people:
+ return (
+ (
+ !!player.sid &&
+ Object.keys(this.people).some(sid =>
+ sid == player.sid && this.people[sid].focus)
+ )
+ ||
+ (
+ !!player.id &&
+ Object.values(this.people).some(p =>
+ p.id == player.id && p.focus)
+ )
+ );
+ },
+ getOppsid: function() {
+ let oppsid = this.game.oppsid;
+ if (!oppsid) {
+ oppsid = Object.keys(this.people).find(
+ sid => this.people[sid].id == this.game.oppid
+ );
+ }
+ // oppsid is useful only if opponent is online:
+ if (!!oppsid && !!this.people[oppsid]) return oppsid;
+ return null;
+ },
+ toggleChat: function() {
+ if (document.getElementById("modalChat").checked)
+ // Entering chat
+ document.getElementById("inputChat").focus();
+ // TODO: next line is only required when exiting chat,
+ // but the event for now isn't well detected.
+ document.getElementById("chatBtn").classList.remove("somethingnew");
+ },
+ processChat: function(chat) {
+ this.send("newchat", { data: chat });
+ // NOTE: anonymous chats in corr games are not stored on server (TODO?)
+ if (this.game.type == "corr" && this.st.user.id > 0)
+ this.updateCorrGame({ chat: chat });
+ },
+ clearChat: function() {
+ // Nothing more to do if game is live (chats not recorded)
+ if (this.game.type == "corr") {
+ if (!!this.game.mycolor) {
+ ajax(
+ "/chats",
+ "DELETE",
+ { data: { gid: this.game.id } }
+ );
+ }
+ this.$set(this.game, "chats", []);
+ }
+ },
+ getGameType: function(game) {
+ return game.cadence.indexOf("d") >= 0 ? "corr" : "live";
+ },
+ // Notify something after a new move (to opponent and me on MyGames page)
+ notifyMyGames: function(thing, data) {
+ this.send(
+ "notify" + thing,
+ {
+ data: data,
+ targets: this.game.players.map(p => {
+ return { sid: p.sid, id: p.id };
+ })
+ }
+ );
+ },
+ showNextGame: function() {
+ // Did I play in current game? If not, add it to nextIds list
+ if (this.game.score == "*" && this.vr.turn == this.game.mycolor)
+ this.nextIds.unshift(this.game.id);
+ const nextGid = this.nextIds.pop();
+ this.$router.push(
+ "/game/" + nextGid + "/?next=" + JSON.stringify(this.nextIds));
+ },
+ askGameAgain: function() {
+ this.gameIsLoading = true;
+ const currentUrl = document.location.href;
+ const doAskGame = () => {
+ if (document.location.href != currentUrl) return; //page change
+ this.fetchGame((game) => {
+ if (!!game)
+ // This is my game: just reload.
+ this.loadGame(game);
+ else
+ // Just ask fullgame again (once!), this is much simpler.
+ // If this fails, the user could just reload page :/
+ this.send("askfullgame");
+ });
+ };
+ // Delay of at least 2s between two game requests
+ const now = Date.now();
+ const delay = Math.max(2000 - (now - this.askGameTime), 0);
+ this.askGameTime = now;
+ setTimeout(doAskGame, delay);
+ },
+ socketMessageListener: function(msg) {
+ if (!this.conn) return;