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