373aa288e85fc51af391bc086fd74f05e09ec08e
[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 state: {
7 variants: [],
8 tr: {},
9 user: {},
10 settings: {},
11 lang: ""
12 },
13 socketCloseListener: null,
14 initialize() {
15 ajax("/variants", "GET", res => {
16 this.state.variants = res.variantArray;
17 });
18 let mysid = localStorage.getItem("mysid");
19 if (!mysid) {
20 mysid = getRandString();
21 localStorage.setItem("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.getItem("myid") || 0,
26 name: localStorage.getItem("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 const storedId = localStorage.getItem("myid");
36 if (res.id > 0 && !storedId)
37 //user cleared localStorage
38 localStorage.setItem("myid", res.id);
39 else if (res.id == 0 && !!storedId)
40 //user cleared cookie
41 localStorage.removeItem("myid");
42 this.state.user.name = res.name;
43 const storedName = localStorage.getItem("myname");
44 if (!!res.name && !storedName)
45 //user cleared localStorage
46 localStorage.setItem("myname", res.name);
47 else if (!res.name && !!storedName)
48 //user cleared cookie
49 localStorage.removeItem("myname");
50 this.state.user.email = res.email;
51 this.state.user.notify = res.notify;
52 });
53 // Settings initialized with values from localStorage
54 this.state.settings = {
55 bcolor: localStorage.getItem("bcolor") || "lichess",
56 sound: parseInt(localStorage.getItem("sound")) || 1,
57 hints: localStorage.getItem("hints") == "true",
58 highlight: localStorage.getItem("highlight") == "true"
59 };
60 const supportedLangs = ["en", "es", "fr"];
61 this.state.lang =
62 localStorage["lang"] ||
63 (supportedLangs.includes(navigator.language) ? navigator.language : "en");
64 this.setTranslations();
65 },
66 updateSetting: function(propName, value) {
67 this.state.settings[propName] = value;
68 localStorage.setItem(propName, value);
69 },
70 setTranslations: async function() {
71 // Import translations from "./translations/$lang.js"
72 const tModule = await import("@/translations/" + this.state.lang + ".js");
73 this.state.tr = tModule.translations;
74 },
75 setLanguage(lang) {
76 this.state.lang = lang;
77 this.setTranslations();
78 }
79 };