Attempt to clarify installation instructions a little
[vchess.git] / client / src / store.js
index 2728aaf..f8b6b24 100644 (file)
-import { ajax } from "./utils/ajax";
+// NOTE: do not use ajax() here because ajax.js requires the store
+import params from "./parameters"; //for server URL
 import { getRandString } from "./utils/alea";
-import params from "./parameters"; //for socket connection
+import { delCookie } from "./utils/cookie";
 
-// Global store: see https://medium.com/fullstackio/managing-state-in-vue-js-23a0352b1c87
-export const store =
-{
+// Global store: see
+// https://medium.com/fullstackio/managing-state-in-vue-js-23a0352b1c87
+export const store = {
   state: {
     variants: [],
     tr: {},
     user: {},
-    conn: null,
     settings: {},
-    lang: "",
+    lang: ""
   },
-  socketCloseListener: null,
-  initialize(page) {
-    ajax("/variants", "GET", res => { this.state.variants = res.variantArray; });
-    let mysid = localStorage["mysid"];
-    if (!mysid)
-    {
+  initialize() {
+    const headers = {
+      "Content-Type": "application/json;charset=UTF-8",
+      "X-Requested-With": "XMLHttpRequest"
+    };
+    fetch(
+      params.serverUrl + "/allvarslist",
+      {
+        method: "GET",
+        headers: headers
+      }
+    )
+    .then(res => res.json())
+    .then(json => {
+      if (!Array.isArray(json.variantArray)) {
+        alert("Variants loading failed: reload the page");
+        return;
+      }
+      this.state.variants = json.variantArray
+        .sort((v1,v2) => v1.name.localeCompare(v2.name));
+    });
+    let mysid = localStorage.getItem("mysid");
+    // Assign mysid only once (until next time user clear browser data)
+    if (!mysid) {
       mysid = getRandString();
-      localStorage["mysid"] = mysid; //done only once (unless user clear browser data)
+      localStorage.setItem("mysid", mysid);
     }
+    // Quick user setup using local storage:
     this.state.user = {
-      id: localStorage["myid"] || 0,
-      name: localStorage["myname"] || "", //"" for "anonymous"
+      id: parseInt(localStorage.getItem("myid") || "0", 10),
+      name: localStorage.getItem("myname") || "", //"" for "anonymous"
       email: "", //unknown yet
       notify: false, //email notifications
-      sid: mysid,
+      sid: mysid
     };
-    if (this.state.user.id > 0)
-    {
-      ajax("/whoami", "GET", res => {
-        this.state.user.email = res.email;
-        this.state.user.notify = res.notify;
-      });
-    }
-    this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid +
-      "&page=" + encodeURIComponent(page));
+    // Slow verification through the server:
+    fetch(
+      params.serverUrl + "/whoami",
+      {
+        method: "GET",
+        headers: headers,
+        credentials: params.credentials
+      }
+    )
+    .then(res => res.json())
+    .then(json => {
+      if (!json.id) {
+        // Removed, or wrong token
+        if (this.state.user.id > 0) {
+          this.state.user.id = 0;
+          localStorage.removeItem("myid");
+        }
+        if (!!this.state.user.name) {
+          this.state.user.name = "";
+          localStorage.removeItem("myname");
+        }
+        if (document.cookie.indexOf("token") >= 0) delCookie("token");
+      }
+      else {
+        if (this.state.user.id != json.id) {
+          this.state.user.id = json.id;
+          localStorage.setItem("myid", json.id);
+        }
+        if (this.state.user.name != json.name) {
+          this.state.user.name = json.name;
+          localStorage.setItem("myname", json.name);
+        }
+        this.state.user.email = json.email;
+        this.state.user.notify = json.notify;
+      }
+    });
     // Settings initialized with values from localStorage
-    this.state.settings = {
-      bcolor: localStorage["bcolor"] || "lichess",
-      sound: parseInt(localStorage["sound"]) || 2,
-      hints: parseInt(localStorage["hints"]) || 1,
-      coords: !!eval(localStorage["coords"]),
-      highlight: !!eval(localStorage["highlight"]),
-      sqSize: parseInt(localStorage["sqSize"]),
+    const getItemDefault = (item, defaut) => {
+      const value = localStorage.getItem(item);
+      if (!value) return defaut;
+      return value == "true";
     };
-    this.socketCloseListener = () => {
-      // Next line may fail at first, but should retry and eventually success (TODO?)
-      this.state.conn = new WebSocket(params.socketUrl + "/?sid=" + mysid);
+    this.state.settings = {
+      bcolor: localStorage.getItem("bcolor") || "lichess",
+      sound: getItemDefault("sound", true),
+      hints: getItemDefault("hints", true),
+      highlight: getItemDefault("highlight", true),
+      gotonext: getItemDefault("gotonext", true),
+      scrollmove: getItemDefault("scrollmove", false)
     };
-    this.state.conn.onclose = this.socketCloseListener;
-    const supportedLangs = ["en","es","fr"];
-    this.state.lang = localStorage["lang"] ||
-      supportedLangs.includes(navigator.language)
-        ? navigator.language
-        : "en";
+    const supportedLangs = ["en", "es", "fr"];
+    const navLanguage = navigator.language.substr(0, 2);
+    this.state.lang =
+      localStorage["lang"] ||
+      (supportedLangs.includes(navLanguage) ? navLanguage : "en");
     this.setTranslations();
   },
+  updateSetting: function(propName, value) {
+    this.state.settings[propName] = value;
+    localStorage.setItem(propName, value);
+  },
   setTranslations: async function() {
     // Import translations from "./translations/$lang.js"
     const tModule = await import("@/translations/" + this.state.lang + ".js");
@@ -67,5 +117,5 @@ export const store =
   setLanguage(lang) {
     this.state.lang = lang;
     this.setTranslations();
-  },
+  }
 };