]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Restore autofocusing of the search field
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require leaflet.sidebar
3 //= require leaflet.locate
4 //= require leaflet.layers
5 //= require leaflet.key
6 //= require leaflet.note
7 //= require leaflet.share
8 //= require index/search
9 //= require index/browse
10 //= require index/export
11 //= require index/notes
12 //= require index/history
13 //= require index/note
14 //= require index/new_note
15 //= require router
16
17 (function() {
18   var loaderTimeout;
19
20   OSM.loadSidebarContent = function(path, callback) {
21     clearTimeout(loaderTimeout);
22
23     loaderTimeout = setTimeout(function() {
24       $('#sidebar_loader').show();
25     }, 200);
26
27     // IE<10 doesn't respect Vary: X-Requested-With header, so
28     // prevent caching the XHR response as a full-page URL.
29     if (path.indexOf('?') >= 0) {
30       path += '&xhr=1'
31     } else {
32       path += '?xhr=1'
33     }
34
35     $('#sidebar_content')
36       .empty();
37
38     $.ajax({
39       url: path,
40       dataType: "html",
41       complete: function(xhr) {
42         clearTimeout(loaderTimeout);
43         $('#flash').empty();
44         $('#sidebar_loader').hide();
45
46         var content = $(xhr.responseText);
47
48         if (xhr.getResponseHeader('X-Page-Title')) {
49           var title = xhr.getResponseHeader('X-Page-Title');
50           document.title = decodeURIComponent(escape(title));
51         }
52
53         $('head')
54           .find('link[type="application/atom+xml"]')
55           .remove();
56
57         $('head')
58           .append(content.filter('link[type="application/atom+xml"]'));
59
60         $('#sidebar_content').html(content.not('link[type="application/atom+xml"]'));
61
62         if (callback) {
63           callback();
64         }
65       }
66     });
67   };
68 })();
69
70 $(document).ready(function () {
71   var params = OSM.mapParams();
72
73   var map = new L.OSM.Map("map", {
74     zoomControl: false,
75     layerControl: false
76   });
77
78   map.attributionControl.setPrefix('');
79
80   map.updateLayers(params.layers);
81
82   map.on("baselayerchange", function (e) {
83     if (map.getZoom() > e.layer.options.maxZoom) {
84       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
85     }
86   });
87
88   var position = $('html').attr('dir') === 'rtl' ? 'topleft' : 'topright';
89
90   L.OSM.zoom({position: position})
91     .addTo(map);
92
93   L.control.locate({
94     position: position,
95     strings: {
96       title: I18n.t('javascripts.map.locate.title'),
97       popup: I18n.t('javascripts.map.locate.popup')
98     }
99   }).addTo(map);
100
101   var sidebar = L.OSM.sidebar('#map-ui')
102     .addTo(map);
103
104   L.OSM.layers({
105     position: position,
106     layers: map.baseLayers,
107     sidebar: sidebar
108   }).addTo(map);
109
110   L.OSM.key({
111     position: position,
112     sidebar: sidebar
113   }).addTo(map);
114
115   L.OSM.share({
116     position: position,
117     sidebar: sidebar,
118     short: true
119   }).addTo(map);
120
121   L.OSM.note({
122     position: position,
123     sidebar: sidebar
124   }).addTo(map);
125
126   L.control.scale()
127     .addTo(map);
128
129   if (OSM.STATUS != 'api_offline' && OSM.STATUS != 'database_offline') {
130     initializeNotes(map);
131     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
132       map.addLayer(map.noteLayer);
133     }
134
135     initializeBrowse(map);
136     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
137       map.addLayer(map.dataLayer);
138     }
139   }
140
141   $('.leaflet-control .control-button').tooltip({placement: 'left', container: 'body'});
142
143   var expiry = new Date();
144   expiry.setYear(expiry.getFullYear() + 10);
145
146   map.on('moveend layeradd layerremove', function() {
147     updateLinks(
148       map.getCenter().wrap(),
149       map.getZoom(),
150       map.getLayersCode(),
151       map._object);
152
153     $.cookie("_osm_location", cookieContent(map), { expires: expiry });
154   });
155
156   if ($.cookie('_osm_welcome') == 'hide') {
157     $('.welcome').hide();
158   }
159
160   $('.welcome .close').on('click', function() {
161     $('.welcome').hide();
162     $.cookie("_osm_welcome", 'hide', { expires: expiry });
163   });
164
165   if (OSM.PIWIK) {
166     map.on('layeradd', function (e) {
167       if (e.layer.options) {
168         var goal = OSM.PIWIK.goals[e.layer.options.keyid];
169
170         if (goal) {
171           $('body').trigger('piwikgoal', goal);
172         }
173       }
174     });
175   }
176
177   if (params.bounds) {
178     map.fitBounds(params.bounds);
179   } else {
180     map.setView([params.lat, params.lon], params.zoom);
181   }
182
183   var marker = L.marker([0, 0], {icon: getUserIcon()});
184
185   if (params.marker) {
186     marker.setLatLng([params.mlat, params.mlon]).addTo(map);
187   }
188
189   $("#homeanchor").on("click", function(e) {
190     e.preventDefault();
191
192     var data = $(this).data(),
193       center = L.latLng(data.lat, data.lon);
194
195     map.setView(center, data.zoom);
196     marker.setLatLng(center).addTo(map);
197   });
198
199   $("a[data-editor=remote]").click(function(e) {
200     var params = OSM.mapParams(this.search);
201     remoteEditHandler(map.getBounds(), params.object);
202     e.preventDefault();
203   });
204
205   if (OSM.params().edit_help) {
206     $('#editanchor')
207       .removeAttr('title')
208       .tooltip({
209         placement: 'bottom',
210         title: I18n.t('javascripts.edit_help')
211       })
212       .tooltip('show');
213
214     $('body').one('click', function() {
215       $('#editanchor').tooltip('hide');
216     });
217   }
218
219   OSM.Index = function(map) {
220     var page = {};
221
222     page.pushstate = function() {
223       $("#content").addClass("overlay-sidebar");
224       map.invalidateSize({pan: false})
225         .panBy([-350, 0], {animate: false});
226       document.title = I18n.t('layouts.project_name.title');
227     };
228
229     page.load = function() {
230       if (!("autofocus" in document.createElement("input"))) {
231         $(".search_form input[name=query]").focus();
232       }
233       return map.getState();
234     };
235
236     page.popstate = function() {
237       $("#content").addClass("overlay-sidebar");
238       map.invalidateSize({pan: false});
239       document.title = I18n.t('layouts.project_name.title');
240     };
241
242     page.unload = function() {
243       map.panBy([350, 0], {animate: false});
244       $("#content").removeClass("overlay-sidebar");
245       map.invalidateSize({pan: false});
246     };
247
248     return page;
249   };
250
251   OSM.Browse = function(map, type) {
252     var page = {};
253
254     page.pushstate = page.popstate = function(path, id) {
255       OSM.loadSidebarContent(path, function() {
256         addObject(type, id);
257       });
258     };
259
260     page.load = function(path, id) {
261       addObject(type, id, true);
262     };
263
264     function addObject(type, id, center) {
265       var bounds = map.addObject({type: type, id: parseInt(id)}, function(bounds) {
266         if (!window.location.hash && bounds.isValid()) {
267           OSM.router.moveListenerOff();
268           map.once('moveend', OSM.router.moveListenerOn);
269           if (center || !map.getBounds().contains(bounds)) map.fitBounds(bounds);
270         }
271       });
272     }
273
274     page.unload = function() {
275       map.removeObject();
276     };
277
278     return page;
279   };
280
281   var history = OSM.History(map);
282
283   OSM.router = OSM.Router(map, {
284     "/":                           OSM.Index(map),
285     "/search":                     OSM.Search(map),
286     "/export":                     OSM.Export(map),
287     "/note/new":                   OSM.NewNote(map),
288     "/history/friends":            history,
289     "/history/nearby":             history,
290     "/history":                    history,
291     "/user/:display_name/history": history,
292     "/note/:id":                   OSM.Note(map),
293     "/node/:id(/history)":         OSM.Browse(map, 'node'),
294     "/way/:id(/history)":          OSM.Browse(map, 'way'),
295     "/relation/:id(/history)":     OSM.Browse(map, 'relation'),
296     "/changeset/:id":              OSM.Browse(map, 'changeset')
297   });
298
299   if (OSM.preferred_editor == "remote" && document.location.pathname == "/edit") {
300     remoteEditHandler(map.getBounds(), params.object);
301     OSM.router.setCurrentPath("/");
302   }
303
304   OSM.router.load();
305
306   $(document).on("click", "a", function(e) {
307     if (e.isDefaultPrevented() || e.isPropagationStopped())
308       return;
309
310     // Open links in a new tab as normal.
311     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey)
312       return;
313
314     // Ignore cross-protocol and cross-origin links.
315     if (location.protocol !== this.protocol || location.host !== this.host)
316       return;
317
318     if (OSM.router.route(this.pathname + this.search + this.hash))
319       e.preventDefault();
320   });
321
322   $(".search_form").on("submit", function(e) {
323     e.preventDefault();
324     $("header").addClass("closed");
325     var query = $(this).find("input[name=query]").val();
326     if (query) {
327       OSM.router.route("/search?query=" + encodeURIComponent(query) + OSM.formatHash(map));
328     } else {
329       OSM.router.route("/" + OSM.formatHash(map));
330     }
331   });
332
333   $(".describe_location").on("click", function(e) {
334     e.preventDefault();
335     var precision = zoomPrecision(map.getZoom());
336     OSM.router.route("/search?query=" + encodeURIComponent(
337       map.getCenter().lat.toFixed(precision) + "," +
338       map.getCenter().lng.toFixed(precision)));
339   });
340 });