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