32347119caedfef7dec35c302402422c2b82925f
[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 this.state.user = {
18 // id and name could be undefined
19 id: localStorage["myuid"],
20 name: localStorage["myname"],
21 };
22 // TODO: if there is a socket ID in localStorage, it means a live game was interrupted (and should resume)
23 const mysid = localStorage["mysid"] || getRandString();
24 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid);
25 // Settings initialized with values from localStorage
26 this.state.settings = {
27 bcolor: localStorage["bcolor"] || "lichess",
28 sound: parseInt(localStorage["sound"]) || 2,
29 hints: parseInt(localStorage["hints"]) || 1,
30 coords: !!eval(localStorage["coords"]),
31 highlight: !!eval(localStorage["highlight"]),
32 sqSize: parseInt(localStorage["sqSize"]),
33 };
34 const socketCloseListener = () => {
35 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid);
36 }
37 this.state.conn.onclose = socketCloseListener;
38 const supportedLangs = ["en","es","fr"];
39 this.state.lang = localStorage["lang"] ||
40 supportedLangs.includes(navigator.language)
41 ? navigator.language
42 : "en";
43 this.setTranslations();
44 },
45 setTranslations: async function() {
46 // Import translations from "./translations/$lang.js"
47 const tModule = await import("@/translations/" + this.state.lang + ".js");
48 this.state.tr = tModule.translations;
49 },
50 setLanguage(lang) {
51 this.state.lang = lang;
52 this.setTranslations();
53 },
54 };