Fix accumulation of socket.close code. Ready to finish Game.js and then the website
[vchess.git] / client / src / store.js
CommitLineData
c66a829b
BA
1import { ajax } from "./utils/ajax";
2import { getRandString } from "./utils/alea";
3import params from "./parameters"; //for socket connection
4
4486a21e 5// Global store: see https://medium.com/fullstackio/managing-state-in-vue-js-23a0352b1c87
c66a829b
BA
6export const store =
7{
8 state: {
9 variants: [],
10 tr: {},
11 user: {},
12 conn: null,
13 settings: {},
14 lang: "",
15 },
cdb34c93 16 socketCloseListener: null,
c66a829b
BA
17 initialize() {
18 ajax("/variants", "GET", res => { this.state.variants = res.variantArray; });
98f48579
BA
19 let mysid = localStorage["mysid"];
20 if (!mysid)
21 {
22 mysid = getRandString();
23 localStorage["mysid"] = mysid; //done only once (unless user clear browser data)
24 }
c66a829b 25 this.state.user = {
98f48579
BA
26 id: localStorage["myid"] || 0,
27 name: localStorage["myname"] || "", //"" for "anonymous"
a7f9f050
BA
28 email: "", //unknown yet
29 notify: false, //email notifications
98f48579 30 sid: mysid,
c66a829b 31 };
98f48579
BA
32 if (this.state.user.id > 0)
33 {
34 fetch(params.serverUrl + "/whoami", {
35 method: "GET",
36 credentials: params.cors ? "include" : "omit",
37 }).then((res) => {
a7f9f050
BA
38 this.state.user.email = res.email;
39 this.state.user.notify = res.notify;
98f48579
BA
40 });
41 }
03608482 42 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + this.state.user.sid);
c66a829b
BA
43 // Settings initialized with values from localStorage
44 this.state.settings = {
45 bcolor: localStorage["bcolor"] || "lichess",
46 sound: parseInt(localStorage["sound"]) || 2,
47 hints: parseInt(localStorage["hints"]) || 1,
48 coords: !!eval(localStorage["coords"]),
49 highlight: !!eval(localStorage["highlight"]),
50 sqSize: parseInt(localStorage["sqSize"]),
51 };
cdb34c93 52 this.socketCloseListener = () => {
c66a829b 53 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid);
f6f2bef1 54 };
cdb34c93 55 this.state.conn.onclose = this.socketCloseListener;
c66a829b
BA
56 const supportedLangs = ["en","es","fr"];
57 this.state.lang = localStorage["lang"] ||
58 supportedLangs.includes(navigator.language)
59 ? navigator.language
60 : "en";
61 this.setTranslations();
62 },
63 setTranslations: async function() {
7c3cd379 64 // Import translations from "./translations/$lang.js"
c66a829b
BA
65 const tModule = await import("@/translations/" + this.state.lang + ".js");
66 this.state.tr = tModule.translations;
67 },
68 setLanguage(lang) {
69 this.state.lang = lang;
70 this.setTranslations();
71 },
72};