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