]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/router.js
Merge remote-tracking branch 'upstream/pull/6236'
[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     const regexp = new RegExp("^" +
57       path.replace(escapeRegExp, "\\$&")
58         .replace(optionalParam, "(?:$1)?")
59         .replace(namedParam, function (match, optional) {
60           return optional ? match : "([^/]+)";
61         })
62         .replace(splatParam, "(.*?)") + "(?:\\?.*)?$");
63
64     const route = {};
65
66     route.match = function (path) {
67       return regexp.test(path);
68     };
69
70     route.run = function (action, path, ...args) {
71       let params = [];
72
73       if (path) {
74         params = regexp.exec(path).map(function (param, i) {
75           return (i > 0 && param) ? decodeURIComponent(param) : param;
76         });
77       }
78
79       return controller[action]?.(...params, ...args);
80     };
81
82     return route;
83   }
84
85   const routes = Object.entries(rts)
86     .map(([r, t]) => new Route(r, t));
87
88   routes.recognize = function (path) {
89     for (const route of this) {
90       if (route.match(path)) return route;
91     }
92   };
93
94   let currentPath = location.pathname.replace(/(.)\/$/, "$1") + location.search,
95       currentRoute = routes.recognize(currentPath),
96       currentHash = location.hash || OSM.formatHash(map);
97
98   const router = {};
99
100   function updateSecondaryNav() {
101     $("header nav.secondary > ul > li > a").each(function () {
102       const active = $(this).attr("href") === location.pathname;
103
104       $(this)
105         .toggleClass("text-secondary", !active)
106         .toggleClass("text-secondary-emphasis", active);
107     });
108   }
109
110   $(window).on("popstate", function (e) {
111     if (!e.originalEvent.state) return; // Is it a real popstate event or just a hash change?
112     const path = location.pathname + location.search,
113           route = routes.recognize(path);
114     if (path === currentPath) return;
115     currentRoute.run("unload", null, route === currentRoute);
116     currentPath = path;
117     currentRoute = route;
118     currentRoute.run("popstate", currentPath);
119     updateSecondaryNav();
120     map.setState(e.originalEvent.state, { animate: false });
121   });
122
123   router.route = function (url) {
124     const path = url.replace(/#.*/, ""),
125           route = routes.recognize(path);
126     if (!route) return false;
127     currentRoute.run("unload", null, route === currentRoute);
128     const state = OSM.parseHash(url);
129     map.setState(state);
130     window.history.pushState(state, document.title, url);
131     currentPath = path;
132     currentRoute = route;
133     currentRoute.run("pushstate", currentPath);
134     updateSecondaryNav();
135     return true;
136   };
137
138   router.replace = function (url) {
139     window.history.replaceState(OSM.parseHash(url), document.title, url);
140   };
141
142   router.stateChange = function (state) {
143     const url = state.center ? OSM.formatHash(state) : location;
144     window.history.replaceState(state, document.title, url);
145   };
146
147   router.updateHash = function () {
148     const hash = OSM.formatHash(map);
149     if (hash === currentHash) return;
150     currentHash = hash;
151     router.stateChange(OSM.parseHash(hash));
152   };
153
154   router.hashUpdated = function () {
155     const hash = location.hash;
156     if (hash === currentHash) return;
157     currentHash = hash;
158     const state = OSM.parseHash(hash);
159     map.setState(state);
160     router.stateChange(state, hash);
161   };
162
163   router.withoutMoveListener = function (callback) {
164     function disableMoveListener() {
165       map.off("moveend", router.updateHash);
166       map.once("moveend", function () {
167         map.on("moveend", router.updateHash);
168       });
169     }
170
171     map.once("movestart", disableMoveListener);
172     callback();
173     map.off("movestart", disableMoveListener);
174   };
175
176   router.load = function () {
177     const loadState = currentRoute.run("load", currentPath);
178     router.stateChange(loadState || {});
179   };
180
181   router.setCurrentPath = function (path) {
182     currentPath = path;
183     currentRoute = routes.recognize(currentPath);
184   };
185
186   router.click = function (event, href) {
187     const eventOptions = {};
188     for (const key in event) eventOptions[key] = event[key];
189     const clickEvent = new (event.constructor)("click", eventOptions);
190     const link = document.createElement("a");
191     link.href = href;
192     document.body.appendChild(link);
193     link.dispatchEvent(clickEvent);
194     document.body.removeChild(link);
195   };
196
197   map.on("moveend baselayerchange overlayadd overlayremove", router.updateHash);
198   $(window).on("hashchange", router.hashUpdated);
199
200   return router;
201 };