Fixes on login/logout + challenges sending
[vchess.git] / client / src / store.js
1 import { ajax } from "./utils/ajax";
2 import { getRandString } from "./utils/alea";
3 import params from "./parameters"; //for socket connection
4
5 // Global store: see https://medium.com/fullstackio/managing-state-in-vue-js-23a0352b1c87
6 export const store =
7 {
8 state: {
9 variants: [],
10 tr: {},
11 user: {},
12 conn: null,
13 settings: {},
14 lang: "",
15 },
16 socketCloseListener: null,
17 initialize(page) {
18 ajax("/variants", "GET", res => { this.state.variants = res.variantArray; });
19 let mysid = localStorage["mysid"];
20 if (!mysid)
21 {
22 mysid = getRandString();
23 localStorage["mysid"] = mysid; //done only once (unless user clear browser data)
24 }
25 // Quick user setup using local storage:
26 this.state.user = {
27 id: localStorage["myid"] || 0,
28 name: localStorage["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 this.state.user.name = res.name;
38 this.state.user.email = res.email;
39 this.state.user.notify = res.notify;
40 });
41 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid +
42 "&page=" + encodeURIComponent(page));
43 // Settings initialized with values from localStorage
44 this.state.settings = {
45 bcolor: localStorage["bcolor"] || "lichess",
46 sound: parseInt(localStorage["sound"]) || 2,
47 hints: parseInt(localStorage["hints"]) || 1,
48 coords: !!eval(localStorage["coords"]),
49 highlight: !!eval(localStorage["highlight"]),
50 sqSize: parseInt(localStorage["sqSize"]),
51 };
52 this.socketCloseListener = () => {
53 // Next line may fail at first, but should retry and eventually success (TODO?)
54 this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid +
55 "&page=" + encodeURIComponent(page));
56 };
57 this.state.conn.onclose = this.socketCloseListener;
58 const supportedLangs = ["en","es","fr"];
59 this.state.lang = localStorage["lang"] ||
60 (supportedLangs.includes(navigator.language)
61 ? navigator.language
62 : "en");
63 this.setTranslations();
64 },
65 setTranslations: async function() {
66 // Import translations from "./translations/$lang.js"
67 const tModule = await import("@/translations/" + this.state.lang + ".js");
68 this.state.tr = tModule.translations;
69 },
70 setLanguage(lang) {
71 this.state.lang = lang;
72 this.setTranslations();
73 },
74 };