Parameters adjustments + cosmetics
[vchess.git] / client / src / router.js
1 import Vue from "vue";
2 import Router from "vue-router";
3 import Hall from "./views/Hall.vue";
4
5 Vue.use(Router);
6
7 function loadView(view) {
8 return () => import(/* webpackChunkName: "view-[request]" */ `@/views/${view}.vue`)
9 }
10
11 import { ajax } from "@/utils/ajax";
12 import { store } from "@/store";
13
14 const router = new Router({
15 routes: [
16 {
17 path: "/",
18 name: "hall",
19 component: Hall,
20 },
21 {
22 path: "/variants",
23 name: "variants",
24 component: loadView("Variants"),
25 },
26 {
27 path: "/variants/:vname([a-zA-Z0-9]+)",
28 name: "rules",
29 component: loadView("Rules"),
30 },
31 {
32 path: "/authenticate/:token",
33 name: "authenticate",
34 beforeEnter: (to, from, next) => {
35 ajax(
36 "/authenticate",
37 "GET",
38 {token: to.params["token"]},
39 (res) => {
40 if (!res.errmsg) //if not already logged in
41 {
42 store.state.user.id = res.id;
43 store.state.user.name = res.name;
44 store.state.user.email = res.email;
45 store.state.user.notify = res.notify;
46 localStorage["myname"] = res.name;
47 localStorage["myid"] = res.id;
48 }
49 // TODO: I don't like these 2 lines, "next('/')" should be enough
50 window.location = "/";
51 next();
52 }
53 );
54 },
55 component: Hall,
56 //redirect: "/", //problem: redirection before end of AJAX request
57 },
58 {
59 path: "/game/:id",
60 name: "game",
61 component: loadView("Game"),
62 },
63 {
64 path: "/about",
65 name: "about",
66 component: loadView("About"),
67 },
68 // TODO: myGames, problemId: https://router.vuejs.org/guide/essentials/dynamic-matching.html
69 ]
70 });
71
72 router.beforeEach((to, from, next) => {
73 window.scrollTo(0, 0);
74 if (!!store.state.conn) //uninitialized at first page
75 {
76 // Notify WebSockets server (TODO: path or fullPath?)
77 store.state.conn.send(JSON.stringify({code: "pagechange", page: to.path}));
78 }
79 next();
80 // TODO?: redirect to current game (through GameStorage.getCurrent()) if any?
81 // (and if the URL doesn't already match it) (use next("/game/GID"))
82 //https://router.vuejs.org/guide/advanced/navigation-guards.html#global-before-guards
83 });
84
85 export default router;