]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Load note from edit link with remote control
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require leaflet.sidebar
3 //= require leaflet.sidebar-pane
4 //= require leaflet.locatecontrol/src/L.Control.Locate
5 //= require leaflet.layers
6 //= require leaflet.key
7 //= require leaflet.note
8 //= require leaflet.share
9 //= require leaflet.polyline
10 //= require leaflet.query
11 //= require leaflet.contextmenu
12 //= require index/contextmenu
13 //= require index/search
14 //= require index/browse
15 //= require index/export
16 //= require index/notes
17 //= require index/history
18 //= require index/note
19 //= require index/new_note
20 //= require index/directions
21 //= require index/changeset
22 //= require index/query
23 //= require router
24 //= require qs/dist/qs
25
26 $(document).ready(function () {
27   var loaderTimeout;
28
29   var map = new L.OSM.Map("map", {
30     zoomControl: false,
31     layerControl: false,
32     contextmenu: true,
33     worldCopyJump: true
34   });
35
36   OSM.loadSidebarContent = function (path, callback) {
37     var content_path = path;
38
39     map.setSidebarOverlaid(false);
40
41     clearTimeout(loaderTimeout);
42
43     loaderTimeout = setTimeout(function () {
44       $("#sidebar_loader").show();
45     }, 200);
46
47     // IE<10 doesn't respect Vary: X-Requested-With header, so
48     // prevent caching the XHR response as a full-page URL.
49     if (content_path.indexOf("?") >= 0) {
50       content_path += "&xhr=1";
51     } else {
52       content_path += "?xhr=1";
53     }
54
55     $("#sidebar_content")
56       .empty();
57
58     $.ajax({
59       url: content_path,
60       dataType: "html",
61       complete: function (xhr) {
62         clearTimeout(loaderTimeout);
63         $("#flash").empty();
64         $("#sidebar_loader").hide();
65
66         var content = $(xhr.responseText);
67
68         if (xhr.getResponseHeader("X-Page-Title")) {
69           var title = xhr.getResponseHeader("X-Page-Title");
70           document.title = decodeURIComponent(title);
71         }
72
73         $("head")
74           .find("link[type=\"application/atom+xml\"]")
75           .remove();
76
77         $("head")
78           .append(content.filter("link[type=\"application/atom+xml\"]"));
79
80         $("#sidebar_content").html(content.not("link[type=\"application/atom+xml\"]"));
81
82         if (callback) {
83           callback();
84         }
85       }
86     });
87   };
88
89   var params = OSM.mapParams();
90
91   map.attributionControl.setPrefix("");
92
93   map.updateLayers(params.layers);
94
95   map.on("baselayerchange", function (e) {
96     if (map.getZoom() > e.layer.options.maxZoom) {
97       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
98     }
99   });
100
101   var position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
102
103   L.OSM.zoom({ position: position })
104     .addTo(map);
105
106   var locate = L.control.locate({
107     position: position,
108     icon: "icon geolocate",
109     iconLoading: "icon geolocate",
110     strings: {
111       title: I18n.t("javascripts.map.locate.title"),
112       popup: function (options) {
113         return I18n.t("javascripts.map.locate." + options.unit + "Popup", { count: options.distance });
114       }
115     }
116   }).addTo(map);
117
118   var locateContainer = locate.getContainer();
119
120   $(locateContainer)
121     .removeClass("leaflet-control-locate leaflet-bar")
122     .addClass("control-locate")
123     .children("a")
124     .attr("href", "#")
125     .removeClass("leaflet-bar-part leaflet-bar-part-single")
126     .addClass("control-button");
127
128   var sidebar = L.OSM.sidebar("#map-ui")
129     .addTo(map);
130
131   L.OSM.layers({
132     position: position,
133     layers: map.baseLayers,
134     sidebar: sidebar
135   }).addTo(map);
136
137   L.OSM.key({
138     position: position,
139     sidebar: sidebar
140   }).addTo(map);
141
142   L.OSM.share({
143     "position": position,
144     "sidebar": sidebar,
145     "short": true
146   }).addTo(map);
147
148   L.OSM.note({
149     position: position,
150     sidebar: sidebar
151   }).addTo(map);
152
153   L.OSM.query({
154     position: position,
155     sidebar: sidebar
156   }).addTo(map);
157
158   L.control.scale()
159     .addTo(map);
160
161   OSM.initializeContextMenu(map);
162
163   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
164     OSM.initializeNotes(map);
165     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
166       map.addLayer(map.noteLayer);
167     }
168
169     OSM.initializeBrowse(map);
170     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
171       map.addLayer(map.dataLayer);
172     }
173
174     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
175       map.addLayer(map.gpsLayer);
176     }
177   }
178
179   var placement = $("html").attr("dir") === "rtl" ? "right" : "left";
180   $(".leaflet-control .control-button").tooltip({ placement: placement, container: "body" });
181
182   var expiry = new Date();
183   expiry.setYear(expiry.getFullYear() + 10);
184
185   map.on("moveend layeradd layerremove", function () {
186     updateLinks(
187       map.getCenter().wrap(),
188       map.getZoom(),
189       map.getLayersCode(),
190       map._object);
191
192     Cookies.set("_osm_location", OSM.locationCookie(map), { secure: true, expires: expiry, path: "/", samesite: "lax" });
193   });
194
195   if (Cookies.get("_osm_welcome") !== "hide") {
196     $(".welcome").addClass("visible");
197   }
198
199   $(".welcome .btn-close").on("click", function () {
200     $(".welcome").removeClass("visible");
201     Cookies.set("_osm_welcome", "hide", { secure: true, expires: expiry, path: "/", samesite: "lax" });
202   });
203
204   var bannerExpiry = new Date();
205   bannerExpiry.setYear(bannerExpiry.getFullYear() + 1);
206
207   $("#banner .btn-close").on("click", function (e) {
208     var cookieId = e.target.id;
209     $("#banner").hide();
210     e.preventDefault();
211     if (cookieId) {
212       Cookies.set(cookieId, "hide", { secure: true, expires: bannerExpiry, path: "/", samesite: "lax" });
213     }
214   });
215
216   if (OSM.MATOMO) {
217     map.on("layeradd", function (e) {
218       if (e.layer.options) {
219         var goal = OSM.MATOMO.goals[e.layer.options.keyid];
220
221         if (goal) {
222           $("body").trigger("matomogoal", goal);
223         }
224       }
225     });
226   }
227
228   if (params.bounds) {
229     map.fitBounds(params.bounds);
230   } else {
231     map.setView([params.lat, params.lon], params.zoom);
232   }
233
234   if (params.marker) {
235     L.marker([params.mlat, params.mlon]).addTo(map);
236   }
237
238   $("#homeanchor").on("click", function (e) {
239     e.preventDefault();
240
241     var data = $(this).data(),
242         center = L.latLng(data.lat, data.lon);
243
244     map.setView(center, data.zoom);
245     L.marker(center, { icon: OSM.getUserIcon() }).addTo(map);
246   });
247
248   function remoteEditHandler(bbox, object) {
249     var remoteEditHost = "http://127.0.0.1:8111",
250         osmHost = location.protocol + "//" + location.host,
251         query = {
252           left: bbox.getWest() - 0.0001,
253           top: bbox.getNorth() + 0.0001,
254           right: bbox.getEast() + 0.0001,
255           bottom: bbox.getSouth() - 0.0001
256         };
257
258     if (object && object.type !== "note") query.select = object.type + object.id; // can't select notes
259     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + Qs.stringify(query), function () {
260       if (object && object.type === "note") {
261         var noteQuery = { url: osmHost + OSM.apiUrl(object) };
262         sendRemoteEditCommand(remoteEditHost + "/import?" + Qs.stringify(noteQuery));
263       }
264     });
265
266     function sendRemoteEditCommand(url, callback) {
267       var iframe = $("<iframe>");
268       var timeoutId = setTimeout(function () {
269         alert(I18n.t("site.index.remote_failed"));
270         iframe.remove();
271       }, 5000);
272
273       iframe
274         .hide()
275         .appendTo("body")
276         .attr("src", url)
277         .on("load", function () {
278           clearTimeout(timeoutId);
279           iframe.remove();
280           if (callback) callback();
281         });
282     }
283
284     return false;
285   }
286
287   $("a[data-editor=remote]").click(function (e) {
288     var params = OSM.mapParams(this.search);
289     remoteEditHandler(map.getBounds(), params.object);
290     e.preventDefault();
291   });
292
293   if (OSM.params().edit_help) {
294     $("#editanchor")
295       .removeAttr("title")
296       .tooltip({
297         placement: "bottom",
298         title: I18n.t("javascripts.edit_help")
299       })
300       .tooltip("show");
301
302     $("body").one("click", function () {
303       $("#editanchor").tooltip("hide");
304     });
305   }
306
307   OSM.Index = function (map) {
308     var page = {};
309
310     page.pushstate = page.popstate = function () {
311       map.setSidebarOverlaid(true);
312       document.title = I18n.t("layouts.project_name.title");
313     };
314
315     page.load = function () {
316       var params = Qs.parse(location.search.substring(1));
317       if (params.query) {
318         $("#sidebar .search_form input[name=query]").value(params.query);
319       }
320       if (!("autofocus" in document.createElement("input"))) {
321         $("#sidebar .search_form input[name=query]").focus();
322       }
323       return map.getState();
324     };
325
326     return page;
327   };
328
329   OSM.Browse = function (map, type) {
330     var page = {};
331
332     page.pushstate = page.popstate = function (path, id) {
333       OSM.loadSidebarContent(path, function () {
334         addObject(type, id);
335       });
336     };
337
338     page.load = function (path, id) {
339       addObject(type, id, true);
340     };
341
342     function addObject(type, id, center) {
343       map.addObject({ type: type, id: parseInt(id, 10) }, function (bounds) {
344         if (!window.location.hash && bounds.isValid() &&
345             (center || !map.getBounds().contains(bounds))) {
346           OSM.router.withoutMoveListener(function () {
347             map.fitBounds(bounds);
348           });
349         }
350       });
351
352       $(".colour-preview-box").each(function () {
353         $(this).css("background-color", $(this).data("colour"));
354       });
355     }
356
357     page.unload = function () {
358       map.removeObject();
359     };
360
361     return page;
362   };
363
364   var history = OSM.History(map);
365
366   OSM.router = OSM.Router(map, {
367     "/": OSM.Index(map),
368     "/search": OSM.Search(map),
369     "/directions": OSM.Directions(map),
370     "/export": OSM.Export(map),
371     "/note/new": OSM.NewNote(map),
372     "/history/friends": history,
373     "/history/nearby": history,
374     "/history": history,
375     "/user/:display_name/history": history,
376     "/note/:id": OSM.Note(map),
377     "/node/:id(/history)": OSM.Browse(map, "node"),
378     "/way/:id(/history)": OSM.Browse(map, "way"),
379     "/relation/:id(/history)": OSM.Browse(map, "relation"),
380     "/changeset/:id": OSM.Changeset(map),
381     "/query": OSM.Query(map)
382   });
383
384   if (OSM.preferred_editor === "remote" && document.location.pathname === "/edit") {
385     remoteEditHandler(map.getBounds(), params.object);
386     OSM.router.setCurrentPath("/");
387   }
388
389   OSM.router.load();
390
391   $(document).on("click", "a", function (e) {
392     if (e.isDefaultPrevented() || e.isPropagationStopped()) {
393       return;
394     }
395
396     // Open links in a new tab as normal.
397     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
398       return;
399     }
400
401     // Ignore cross-protocol and cross-origin links.
402     if (location.protocol !== this.protocol || location.host !== this.host) {
403       return;
404     }
405
406     if (OSM.router.route(this.pathname + this.search + this.hash)) {
407       e.preventDefault();
408     }
409   });
410 });