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).
6 For browsers without pushState, it falls back to full page loads, which all
7 of the above pages support.
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)`).
13 Route controller objects can define three methods that are called at defined
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
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`.
24 * The `unload` method is called on the exiting route controller when navigating
25 via pushState or popstate to another route.
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.
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`:
34 OSM.router.route('/way/1234');
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.
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.
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;
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 : "([^/]+)";
60 .replace(splatParam, "(.*?)") + "(?:\\?.*)?$");
64 route.match = function (path) {
65 return regexp.test(path);
68 route.run = async function (action, path, ...args) {
72 params = regexp.exec(path).map(function (param, i) {
73 return (i > 0 && param) ? decodeURIComponent(param) : param;
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));
83 return controllerInstance[action]?.(...params, ...args);
89 const routes = Object.entries(rts)
90 .map(([path, controller]) => new Route(path, controller));
92 routes.recognize = path => routes.find(route => route.match(path));
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();
101 function updateSecondaryNav() {
102 $("header ul.nav > li > a").each(function () {
103 const active = new URL($(this).attr("href"), location.href).pathname === location.pathname;
106 .toggleClass("active", active)
107 .toggleClass("text-secondary", !active)
108 .toggleClass("text-secondary-emphasis", active);
112 function transition(path, beforeEnter = () => {}) {
113 const route = routes.recognize(path);
114 if (!route) return false;
115 routingInProgress = routingInProgress
118 await currentRoute.run("unload", null, route === currentRoute);
121 currentRoute = route;
122 await currentRoute.run("load", currentPath);
123 updateSecondaryNav();
125 return routingInProgress;
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 }));
136 router.route = function (url) {
137 const path = url.replace(/#.*/, "");
138 const state = OSM.parseHash(url);
139 return Boolean(transition(path, () => {
141 window.history.pushState(state, document.title, url);
145 router.replace = function (url) {
146 window.history.replaceState(OSM.parseHash(url), document.title, url);
149 router.stateChange = function (state) {
150 const url = state.center ? OSM.formatHash(state) : location;
151 window.history.replaceState(state, document.title, url);
154 router.updateHash = function () {
155 const hash = OSM.formatHash(map);
156 if (hash === currentHash) return;
158 router.stateChange(OSM.parseHash(hash));
161 router.hashUpdated = function () {
162 const hash = location.hash;
163 if (hash === currentHash) return;
165 const state = OSM.parseHash(hash);
167 router.stateChange(state, hash);
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);
178 map.once("movestart", disableMoveListener);
180 map.off("movestart", disableMoveListener);
183 router.load = async function () {
184 const loadState = await currentRoute.run("init", currentPath);
185 router.stateChange(loadState || {});
188 router.setCurrentPath = function (path) {
190 currentRoute = routes.recognize(currentPath);
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");
199 link.hash = location.hash;
200 document.body.appendChild(link);
201 link.dispatchEvent(clickEvent);
202 document.body.removeChild(link);
205 for (const e of ["moveend", "baselayerchange", "overlayadd", "overlayremove"]) {
206 map.on(e, router.updateHash);
208 $(window).on("hashchange", router.hashUpdated);