]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/router.js
Bump the dependencies group with 6 updates
[rails.git] / app / assets / javascripts / router.js
1 /*
2   OSM.Router implements pushState-based navigation for the main page and
3   other pages that use a sidebar+map based layout (export, search results,
4   history, and browse pages).
5
6   For browsers without pushState, it falls back to full page loads, which all
7   of the above pages support.
8
9   The router is initialized with a set of routes: a mapping of URL path templates
10   to route controller objects. Path templates can contain placeholders
11   (`/note/:id`) and optional segments (`/:type/:id(/history)`).
12
13   Route controller objects can define three methods that are called at defined
14   times during routing:
15
16      * The `init` method is called by the router when a path which matches the
17        route's path template is loaded via a normal full page load. It is passed
18        as arguments the URL path plus any matching arguments for placeholders
19        in the path template.
20
21      * The `load` method is called when a supported and matching page is
22        loaded via pushState or popstate. It is passed the same arguments as `init`.
23
24      * The `unload` method is called on the exiting route controller when navigating
25        via pushState or popstate to another route.
26
27    Note that while `init` is not called by the router for pushState-based loads,
28    it's frequently useful for route controllers to call it manually inside their
29    definition of the `load` method.
30
31    An instance of OSM.Router is assigned to `OSM.router`. To navigate to a new page
32    via pushState (with automatic full-page load fallback), call `OSM.router.route`:
33
34        OSM.router.route('/way/1234');
35
36    If `route` is passed a path that matches one of the path templates, it performs
37    the appropriate actions and returns true. Otherwise it returns false.
38
39    OSM.Router also handles updating the hash portion of the URL containing transient
40    map state such as the position and zoom level. Some route controllers may wish to
41    temporarily suppress updating the hash (for example, to omit the hash on pages
42    such as `/way/1234` unless the map is moved). This can be done by using
43    `OSM.router.withoutMoveListener` to run a block of code that may update
44    move the map without the hash changing.
45  */
46 OSM.Router = function (map, rts) {
47   const escapeRegExp = /[-{}[\]+?.,\\^$|#\s]/g;
48   const optionalParam = /\((.*?)\)/g;
49   const namedParam = /(\(\?)?:\w+/g;
50   const splatParam = /\*\w+/g;
51
52   function Route(path, controller) {
53     let controllerInstance = null;
54     const regexp = new RegExp("^" +
55       path.replace(escapeRegExp, "\\$&")
56         .replace(optionalParam, "(?:$1)?")
57         .replace(namedParam, function (match, optional) {
58           return optional ? match : "([^/]+)";
59         })
60         .replace(splatParam, "(.*?)") + "(?:\\?.*)?$");
61
62     const route = {};
63
64     route.match = function (path) {
65       return regexp.test(path);
66     };
67
68     route.run = async function (action, path, ...args) {
69       let params = [];
70
71       if (path) {
72         params = regexp.exec(path).map(function (param, i) {
73           return (i > 0 && param) ? decodeURIComponent(param) : param;
74         });
75       }
76
77       if (!controllerInstance) {
78         const moduleName = typeof controller === "string" ? "index_" + controller : controller.module;
79         const select = controller.part || (m => m.default);
80         controllerInstance = await import(OSM.MODULE_PATHS[moduleName]).then(select).then(m => m(map));
81       }
82
83       return controllerInstance[action]?.(...params, ...args);
84     };
85
86     return route;
87   }
88
89   const routes = Object.entries(rts)
90     .map(([path, controller]) => new Route(path, controller));
91
92   routes.recognize = path => routes.find(route => route.match(path));
93
94   let currentPath = location.pathname.replace(/(.)\/$/, "$1") + location.search,
95       currentRoute = routes.recognize(currentPath),
96       currentHash = location.hash || OSM.formatHash(map);
97   let routingInProgress = Promise.resolve();
98
99   const router = {};
100
101   function updateSecondaryNav() {
102     $("header ul.nav > li > a").each(function () {
103       const active = new URL($(this).attr("href"), location.href).pathname === location.pathname;
104
105       $(this)
106         .toggleClass("active", active)
107         .toggleClass("text-secondary", !active)
108         .toggleClass("text-secondary-emphasis", active);
109     });
110   }
111
112   function transition(path, beforeEnter = () => {}) {
113     const route = routes.recognize(path);
114     if (!route) return false;
115     routingInProgress = routingInProgress
116       .catch(() => {})
117       .then(async () => {
118         await currentRoute.run("unload", null, route === currentRoute);
119         beforeEnter();
120         currentPath = path;
121         currentRoute = route;
122         await currentRoute.run("load", currentPath);
123         updateSecondaryNav();
124       });
125     return routingInProgress;
126   }
127
128   addEventListener("popstate", function ({ state }) {
129     if (!state) return; // Is it a real popstate event or just a hash change?
130     const path = location.pathname + location.search;
131     if (path === currentPath) return;
132     const done = transition(path);
133     if (done) done.then(() => map.setState(state, { animate: false }));
134   });
135
136   router.route = function (url) {
137     const path = url.replace(/#.*/, "");
138     const state = OSM.parseHash(url);
139     return Boolean(transition(path, () => {
140       map.setState(state);
141       window.history.pushState(state, document.title, url);
142     }));
143   };
144
145   router.replace = function (url) {
146     window.history.replaceState(OSM.parseHash(url), document.title, url);
147   };
148
149   router.stateChange = function (state) {
150     const url = state.center ? OSM.formatHash(state) : location;
151     window.history.replaceState(state, document.title, url);
152   };
153
154   router.updateHash = function () {
155     const hash = OSM.formatHash(map);
156     if (hash === currentHash) return;
157     currentHash = hash;
158     router.stateChange(OSM.parseHash(hash));
159   };
160
161   router.hashUpdated = function () {
162     const hash = location.hash;
163     if (hash === currentHash) return;
164     currentHash = hash;
165     const state = OSM.parseHash(hash);
166     map.setState(state);
167     router.stateChange(state, hash);
168   };
169
170   router.withoutMoveListener = function (callback) {
171     function disableMoveListener() {
172       map.off("moveend", router.updateHash);
173       map.once("moveend", function () {
174         map.on("moveend", router.updateHash);
175       });
176     }
177
178     map.once("movestart", disableMoveListener);
179     callback();
180     map.off("movestart", disableMoveListener);
181   };
182
183   router.load = async function () {
184     const loadState = await currentRoute.run("init", currentPath);
185     router.stateChange(loadState || {});
186   };
187
188   router.setCurrentPath = function (path) {
189     currentPath = path;
190     currentRoute = routes.recognize(currentPath);
191   };
192
193   router.click = function (event, href) {
194     const eventOptions = {};
195     for (const key in event) eventOptions[key] = event[key];
196     const clickEvent = new (event.constructor)("click", eventOptions);
197     const link = document.createElement("a");
198     link.href = href;
199     link.hash = location.hash;
200     document.body.appendChild(link);
201     link.dispatchEvent(clickEvent);
202     document.body.removeChild(link);
203   };
204
205   for (const e of ["moveend", "baselayerchange", "overlayadd", "overlayremove"]) {
206     map.on(e, router.updateHash);
207   }
208   $(window).on("hashchange", router.hashUpdated);
209
210   return router;
211 };