]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/router.js
8661f95dccc918ee95d18fd54d0242281445f2e5
[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 calling
46    `OSM.router.moveListenerOff` and `OSM.router.moveListenerOn`.
47  */
48 OSM.Router = function(map, rts) {
49   var escapeRegExp  = /[\-{}\[\]+?.,\\\^$|#\s]/g;
50   var optionalParam = /\((.*?)\)/g;
51   var namedParam    = /(\(\?)?:\w+/g;
52   var splatParam    = /\*\w+/g;
53
54   function Route(path, controller) {
55     var regexp = new RegExp('^' +
56       path.replace(escapeRegExp, '\\$&')
57         .replace(optionalParam, '(?:$1)?')
58         .replace(namedParam, function(match, optional){
59           return optional ? match : '([^\/]+)';
60         })
61         .replace(splatParam, '(.*?)') + '(?:\\?.*)?$');
62
63     var route = {};
64
65     route.match = function(path) {
66       return regexp.test(path);
67     };
68
69     route.run = function(action, path) {
70       var params = [];
71
72       if (path) {
73         params = regexp.exec(path).map(function(param, i) {
74           return (i > 0 && param) ? decodeURIComponent(param) : param;
75         });
76       }
77
78       return (controller[action] || $.noop).apply(controller, params);
79     };
80
81     return route;
82   }
83
84   var routes = [];
85   for (var r in rts)
86     routes.push(Route(r, rts[r]));
87
88   routes.recognize = function(path) {
89     for (var i = 0; i < this.length; i++) {
90       if (this[i].match(path)) return this[i];
91     }
92   };
93
94   var currentPath = window.location.pathname + window.location.search,
95     currentRoute = routes.recognize(currentPath),
96     currentHash = location.hash || OSM.formatHash(map);
97
98   var router = {};
99
100   if (window.history && window.history.pushState) {
101     $(window).on('popstate', function(e) {
102       if (!e.originalEvent.state) return; // Is it a real popstate event or just a hash change?
103       var path = window.location.pathname + window.location.search;
104       if (path === currentPath) return;
105       currentRoute.run('unload');
106       currentPath = path;
107       currentRoute = routes.recognize(currentPath);
108       currentRoute.run('popstate', currentPath);
109       var state = e.originalEvent.state;
110       if (state.center) {
111         map.setView(state.center, state.zoom, {animate: false});
112         map.updateLayers(state.layers);
113       }
114     });
115
116     router.route = function (url) {
117       var path = url.replace(/#.*/, ''),
118         route = routes.recognize(path);
119       if (!route) return false;
120       window.history.pushState(OSM.parseHash(url) || {}, document.title, url);
121       currentRoute.run('unload');
122       currentPath = path;
123       currentRoute = route;
124       currentRoute.run('pushstate', currentPath);
125       return true;
126     };
127
128     router.stateChange = function(state) {
129       if (state.center) {
130         window.history.replaceState(state, document.title, OSM.formatHash(state));
131       } else {
132         window.history.replaceState(state, document.title, window.location);
133       }
134     };
135   } else {
136     router.route = function (url) {
137       window.location.assign(url);
138     };
139
140     router.stateChange = function(state) {
141       if (state.center) window.location.replace(OSM.formatHash(state));
142     };
143   }
144
145   router.updateHash = function() {
146     var hash = OSM.formatHash(map);
147     if (hash === currentHash) return;
148     currentHash = hash;
149     router.stateChange(OSM.parseHash(hash));
150   };
151
152   router.hashUpdated = function() {
153     var hash = location.hash;
154     if (hash === currentHash) return;
155     currentHash = hash;
156     var state = OSM.parseHash(hash);
157     if (!state) return;
158     map.setView(state.center, state.zoom);
159     map.updateLayers(state.layers);
160     router.stateChange(state, hash);
161   };
162
163   router.moveListenerOn = function() {
164     map.on('moveend', router.updateHash);
165   };
166
167   router.moveListenerOff = function() {
168     map.off('moveend', router.updateHash);
169   };
170
171   router.load = function() {
172     var loadState = currentRoute.run('load', currentPath);
173     router.stateChange(loadState || {});
174   };
175
176   map.on('moveend baselayerchange overlaylayerchange', router.updateHash);
177   $(window).on('hashchange', router.hashUpdated);
178
179   return router;
180 };