]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/router.js
Merge remote-tracking branch 'upstream/pull/5643'
[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   var escapeRegExp = /[-{}[\]+?.,\\^$|#\s]/g;
51   var optionalParam = /\((.*?)\)/g;
52   var namedParam = /(\(\?)?:\w+/g;
53   var splatParam = /\*\w+/g;
54
55   function Route(path, controller) {
56     var 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     var route = {};
65
66     route.match = function (path) {
67       return regexp.test(path);
68     };
69
70     route.run = function (action, path) {
71       var 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       params = params.concat(Array.prototype.slice.call(arguments, 2));
80
81       return (controller[action] || $.noop).apply(controller, params);
82     };
83
84     return route;
85   }
86
87   const routes = Object.entries(rts)
88     .map(([r, t]) => new Route(r, t));
89
90   routes.recognize = function (path) {
91     for (const route of this) {
92       if (route.match(path)) return route;
93     }
94   };
95
96   var currentPath = window.location.pathname.replace(/(.)\/$/, "$1") + window.location.search,
97       currentRoute = routes.recognize(currentPath),
98       currentHash = location.hash || OSM.formatHash(map);
99
100   var router = {};
101
102   function updateSecondaryNav() {
103     $("header nav.secondary > ul > li > a").each(function () {
104       var active = $(this).attr("href") === window.location.pathname;
105
106       $(this)
107         .toggleClass("text-secondary", !active)
108         .toggleClass("text-secondary-emphasis", active);
109     });
110   }
111
112   $(window).on("popstate", function (e) {
113     if (!e.originalEvent.state) return; // Is it a real popstate event or just a hash change?
114     var path = window.location.pathname + window.location.search,
115         route = routes.recognize(path);
116     if (path === currentPath) return;
117     currentRoute.run("unload", null, route === currentRoute);
118     currentPath = path;
119     currentRoute = route;
120     currentRoute.run("popstate", currentPath);
121     updateSecondaryNav();
122     map.setState(e.originalEvent.state, { animate: false });
123   });
124
125   router.route = function (url) {
126     var path = url.replace(/#.*/, ""),
127         route = routes.recognize(path);
128     if (!route) return false;
129     currentRoute.run("unload", null, route === currentRoute);
130     var state = OSM.parseHash(url);
131     map.setState(state);
132     window.history.pushState(state, document.title, url);
133     currentPath = path;
134     currentRoute = route;
135     currentRoute.run("pushstate", currentPath);
136     updateSecondaryNav();
137     return true;
138   };
139
140   router.replace = function (url) {
141     window.history.replaceState(OSM.parseHash(url), document.title, url);
142   };
143
144   router.stateChange = function (state) {
145     const url = state.center ? OSM.formatHash(state) : window.location;
146     window.history.replaceState(state, document.title, url);
147   };
148
149   router.updateHash = function () {
150     var hash = OSM.formatHash(map);
151     if (hash === currentHash) return;
152     currentHash = hash;
153     router.stateChange(OSM.parseHash(hash));
154   };
155
156   router.hashUpdated = function () {
157     var hash = location.hash;
158     if (hash === currentHash) return;
159     currentHash = hash;
160     var state = OSM.parseHash(hash);
161     map.setState(state);
162     router.stateChange(state, hash);
163   };
164
165   router.withoutMoveListener = function (callback) {
166     function disableMoveListener() {
167       map.off("moveend", router.updateHash);
168       map.once("moveend", function () {
169         map.on("moveend", router.updateHash);
170       });
171     }
172
173     map.once("movestart", disableMoveListener);
174     callback();
175     map.off("movestart", disableMoveListener);
176   };
177
178   router.load = function () {
179     var loadState = currentRoute.run("load", currentPath);
180     router.stateChange(loadState || {});
181   };
182
183   router.setCurrentPath = function (path) {
184     currentPath = path;
185     currentRoute = routes.recognize(currentPath);
186   };
187
188   map.on("moveend baselayerchange overlayadd overlayremove", router.updateHash);
189   $(window).on("hashchange", router.hashUpdated);
190
191   return router;
192 };