Apply store pattern to track global app state
[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
5export 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 // Fill modalWelcome, and import translations from "./translations/$lang.js"
47 document.getElementById("modalWelcome").innerHTML =
48 require("raw-loader!pug-plain-loader!@/welcome/" + this.state.lang + ".pug");
49 const tModule = await import("@/translations/" + this.state.lang + ".js");
50 this.state.tr = tModule.translations;
51 },
52 setLanguage(lang) {
53 this.state.lang = lang;
54 this.setTranslations();
55 },
56};