On the way to multi-tabs support
[vchess.git] / client / src / store.js
1 import { ajax } from "./utils/ajax";
2 import { getRandString } from "./utils/alea";
3
4 // Global store: see https://medium.com/fullstackio/managing-state-in-vue-js-23a0352b1c87
5 export const store =
6 {
7 state: {
8 variants: [],
9 tr: {},
10 user: {},
11 settings: {},
12 lang: "",
13 },
14 socketCloseListener: null,
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 // Quick user setup using local storage:
24 this.state.user = {
25 id: localStorage["myid"] || 0,
26 name: localStorage["myname"] || "", //"" for "anonymous"
27 email: "", //unknown yet
28 notify: false, //email notifications
29 sid: mysid,
30 };
31 // Slow verification through the server:
32 // NOTE: still superficial identity usurpation possible, but difficult.
33 ajax("/whoami", "GET", res => {
34 this.state.user.id = res.id;
35 this.state.user.name = res.name;
36 this.state.user.email = res.email;
37 this.state.user.notify = res.notify;
38 });
39 // Settings initialized with values from localStorage
40 this.state.settings = {
41 bcolor: localStorage.getItem("bcolor") || "lichess",
42 sound: parseInt(localStorage.getItem("sound")) || 1,
43 hints: localStorage.getItem("hints") == "true",
44 highlight: localStorage.getItem("highlight") == "true",
45 };
46 const supportedLangs = ["en","es","fr"];
47 this.state.lang = localStorage["lang"] ||
48 (supportedLangs.includes(navigator.language)
49 ? navigator.language
50 : "en");
51 this.setTranslations();
52 },
53 updateSetting: function(propName, value) {
54 this.state.settings[propName] = value;
55 localStorage.setItem(propName, value);
56 },
57 setTranslations: async function() {
58 // Import translations from "./translations/$lang.js"
59 const tModule = await import("@/translations/" + this.state.lang + ".js");
60 this.state.tr = tModule.translations;
61 },
62 setLanguage(lang) {
63 this.state.lang = lang;
64 this.setTranslations();
65 },
66 };