Fix multiple challenges bug
[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 },
16 initialize() {
17 ajax("/variants", "GET", res => { this.state.variants = res.variantArray; });
98f48579
BA
18 let mysid = localStorage["mysid"];
19 if (!mysid)
20 {
21 mysid = getRandString();
22 localStorage["mysid"] = mysid; //done only once (unless user clear browser data)
23 }
c66a829b 24 this.state.user = {
98f48579
BA
25 id: localStorage["myid"] || 0,
26 name: localStorage["myname"] || "", //"" for "anonymous"
a7f9f050
BA
27 email: "", //unknown yet
28 notify: false, //email notifications
98f48579 29 sid: mysid,
c66a829b 30 };
98f48579
BA
31 if (this.state.user.id > 0)
32 {
33 fetch(params.serverUrl + "/whoami", {
34 method: "GET",
35 credentials: params.cors ? "include" : "omit",
36 }).then((res) => {
a7f9f050
BA
37 this.state.user.email = res.email;
38 this.state.user.notify = res.notify;
98f48579
BA
39 });
40 }
03608482 41 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + this.state.user.sid);
c66a829b
BA
42 // Settings initialized with values from localStorage
43 this.state.settings = {
44 bcolor: localStorage["bcolor"] || "lichess",
45 sound: parseInt(localStorage["sound"]) || 2,
46 hints: parseInt(localStorage["hints"]) || 1,
47 coords: !!eval(localStorage["coords"]),
48 highlight: !!eval(localStorage["highlight"]),
49 sqSize: parseInt(localStorage["sqSize"]),
50 };
51 const socketCloseListener = () => {
52 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid);
f6f2bef1 53 };
c66a829b
BA
54 this.state.conn.onclose = socketCloseListener;
55 const supportedLangs = ["en","es","fr"];
56 this.state.lang = localStorage["lang"] ||
57 supportedLangs.includes(navigator.language)
58 ? navigator.language
59 : "en";
60 this.setTranslations();
61 },
62 setTranslations: async function() {
7c3cd379 63 // Import translations from "./translations/$lang.js"
c66a829b
BA
64 const tModule = await import("@/translations/" + this.state.lang + ".js");
65 this.state.tr = tModule.translations;
66 },
67 setLanguage(lang) {
68 this.state.lang = lang;
69 this.setTranslations();
70 },
71};