Some more cleaning + fixes
[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 // Assign mysid only once (until next time user clear browser data)
20 if (!mysid) {
21 mysid = getRandString();
22 localStorage.setItem("mysid", mysid);
23 }
24 // Quick user setup using local storage:
25 this.state.user = {
26 id: localStorage.getItem("myid") || 0,
27 name: localStorage.getItem("myname") || "", //"" for "anonymous"
28 email: "", //unknown yet
29 notify: false, //email notifications
30 sid: mysid
31 };
32 // Slow verification through the server:
33 // NOTE: still superficial identity usurpation possible, but difficult.
34 ajax("/whoami", "GET", res => {
35 this.state.user.id = res.id;
36 const storedId = localStorage.getItem("myid");
37 if (res.id > 0 && !storedId)
38 // User cleared localStorage
39 localStorage.setItem("myid", res.id);
40 else if (res.id == 0 && !!storedId)
41 // User cleared cookie
42 localStorage.removeItem("myid");
43 this.state.user.name = res.name;
44 const storedName = localStorage.getItem("myname");
45 if (!!res.name && !storedName)
46 // User cleared localStorage
47 localStorage.setItem("myname", res.name);
48 else if (!res.name && !!storedName)
49 // User cleared cookie
50 localStorage.removeItem("myname");
51 this.state.user.email = res.email;
52 this.state.user.notify = res.notify;
53 });
54 // Settings initialized with values from localStorage
55 this.state.settings = {
56 bcolor: localStorage.getItem("bcolor") || "lichess",
57 sound: parseInt(localStorage.getItem("sound")) || 1,
58 hints: localStorage.getItem("hints") == "true",
59 highlight: localStorage.getItem("highlight") == "true"
60 };
61 const supportedLangs = ["en", "es", "fr"];
62 this.state.lang =
63 localStorage["lang"] ||
64 (supportedLangs.includes(navigator.language) ? navigator.language : "en");
65 this.setTranslations();
66 },
67 updateSetting: function(propName, value) {
68 this.state.settings[propName] = value;
69 localStorage.setItem(propName, value);
70 },
71 setTranslations: async function() {
72 // Import translations from "./translations/$lang.js"
73 const tModule = await import("@/translations/" + this.state.lang + ".js");
74 this.state.tr = tModule.translations;
75 },
76 setLanguage(lang) {
77 this.state.lang = lang;
78 this.setTranslations();
79 }
80 };