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