]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index.js
Bump the dependencies group with 6 updates
[rails.git] / app / assets / javascripts / index.js
1 //= require_self
2 //= require numbered_pagination
3 //= require leaflet.sidebar
4 //= require leaflet.sidebar-pane
5 //= require leaflet.locate
6 //= require leaflet.layers
7 //= require leaflet.legend
8 //= require leaflet.note
9 //= require leaflet.share
10 //= require leaflet.query
11 //= require index/contextmenu
12 //= require index/initializations
13 //= require index/layers/data
14 //= require index/layers/notes
15 //= require router
16
17 OSM.initializations = [];
18
19 $(function () {
20   const map = new L.OSM.Map("map", {
21     zoomControl: false,
22     layerControl: false,
23     contextmenu: true,
24     worldCopyJump: true
25   });
26
27   OSM.loadSidebarContent = function (path) {
28     map.setSidebarOverlaid(false);
29
30     return new Promise((resolve, reject) => {
31       $("#sidebar_content_frame")
32         .one("turbo:frame-render", event => {
33           const response = event.originalEvent.detail.fetchResponse.response;
34
35           const title = response.headers.get("X-Page-Title");
36           if (title) document.title = decodeURIComponent(title);
37
38           if (response.ok) {
39             resolve();
40           } else {
41             reject(new Error(`HTTP Error ${response.status} ${response.statusText}`));
42           }
43         })
44         .prop("src", path);
45     });
46   };
47
48   $("#sidebar_content_frame")
49     .on("turbo:before-fetch-response", () => $("#flash").empty())
50     .on("turbo:before-frame-render", event => {
51       const atomSelector = "link[type='application/atom+xml']";
52       $("head").find(atomSelector).remove();
53       $("head").append(
54         $(event.originalEvent.detail.newFrame)
55           .find(atomSelector)
56           .detach());
57     });
58
59   const token = $("head").data("oauthToken");
60   if (token) OSM.oauth = { authorization: "Bearer " + token };
61
62   const params = OSM.mapParams();
63
64   map.attributionControl.setPrefix("");
65
66   map.updateLayers(params.layers);
67
68   map.on("baselayerchange", function (e) {
69     if (map.getZoom() > e.layer.options.maxZoom) {
70       map.setView(map.getCenter(), e.layer.options.maxZoom, { reset: true });
71     }
72   });
73
74   const sidebar = L.OSM.sidebar("#map-ui")
75     .addTo(map);
76
77   const position = $("html").attr("dir") === "rtl" ? "topleft" : "topright";
78
79   function addControlGroup(controls) {
80     for (const control of controls) control.addTo(map);
81
82     const firstContainer = controls[0].getContainer();
83     $(firstContainer).find(".control-button").first()
84       .addClass("control-button-first");
85
86     const lastContainer = controls[controls.length - 1].getContainer();
87     $(lastContainer).find(".control-button").last()
88       .addClass("control-button-last");
89   }
90
91   addControlGroup([
92     L.OSM.zoom({ position }),
93     L.OSM.locate({ position })
94   ]);
95
96   addControlGroup([
97     L.OSM.layers({
98       position,
99       sidebar,
100       layers: map.baseLayers
101     }),
102     L.OSM.legend({ position, sidebar }),
103     L.OSM.share({
104       position,
105       sidebar,
106       "short": true
107     })
108   ]);
109
110   addControlGroup([
111     L.OSM.note({ position, sidebar })
112   ]);
113
114   addControlGroup([
115     L.OSM.query({ position, sidebar })
116   ]);
117
118   L.control.scale()
119     .addTo(map);
120
121   OSM.initializations.forEach(func => func(map));
122
123   if (OSM.STATUS !== "api_offline" && OSM.STATUS !== "database_offline") {
124     OSM.initializeNotesLayer(map);
125     if (params.layers.indexOf(map.noteLayer.options.code) >= 0) {
126       map.addLayer(map.noteLayer);
127     }
128
129     OSM.initializeDataLayer(map);
130     if (params.layers.indexOf(map.dataLayer.options.code) >= 0) {
131       map.addLayer(map.dataLayer);
132     }
133
134     if (params.layers.indexOf(map.gpsLayer.options.code) >= 0) {
135       map.addLayer(map.gpsLayer);
136     }
137   }
138
139   $(".leaflet-control .control-button").tooltip({ placement: "left", container: "body" });
140
141   const expires = new Date();
142   const thisYear = expires.getFullYear();
143   expires.setFullYear(thisYear + 10);
144
145   const updateCookieAndLinks = function () {
146     updateLinks(
147       map.getCenter().wrap(),
148       map.getZoom(),
149       map.getLayersCode(),
150       map._object);
151
152     OSM.cookies.set("_osm_location", OSM.locationCookie(map), { expires });
153   };
154   for (const e of ["moveend", "baselayerchange", "overlayadd", "overlayremove"]) {
155     map.on(e, updateCookieAndLinks);
156   }
157
158   if (OSM.cookies.get("_osm_welcome") !== "hide") {
159     $(".welcome").addClass("d-md-block");
160   }
161
162   $(".welcome .btn-close").on("click", function () {
163     $(".welcome").removeClass("d-md-block");
164     OSM.cookies.set("_osm_welcome", "hide", { expires });
165   });
166
167   expires.setFullYear(thisYear + 1);
168
169   $("#banner .btn-close").on("click", function (e) {
170     const cookieId = e.target.id;
171     $("#banner").removeClass("d-md-block");
172     e.preventDefault();
173     if (cookieId) {
174       OSM.cookies.set(cookieId, "hide", { expires });
175     }
176   });
177
178   if (OSM.MATOMO) {
179     const matomoLayerHandler = function (e) {
180       if (e.layer.options) {
181         const goal = OSM.MATOMO.goals[e.layer.options.layerId];
182
183         if (goal) {
184           $("body").trigger("matomogoal", goal);
185         }
186       }
187     };
188     map.on("baselayerchange", matomoLayerHandler);
189     map.on("overlayadd", matomoLayerHandler);
190   }
191
192   if (params.bounds) {
193     map.fitBounds(params.bounds);
194   } else {
195     map.setView([params.lat, params.lon], params.zoom);
196   }
197
198   if (params.marker && params.mrad) {
199     L.circle([params.mlat, params.mlon], { radius: params.mrad }).addTo(map);
200   } else if (params.marker) {
201     L.marker([params.mlat, params.mlon], { icon: OSM.getMarker({ color: "var(--marker-blue)" }) }).addTo(map);
202   }
203
204   function remoteEditHandler(bbox, object) {
205     const remoteEditHost = "http://127.0.0.1:8111",
206           osmHost = location.protocol + "//" + location.host,
207           query = new URLSearchParams({
208             left: bbox.getWest() - 0.0001,
209             top: bbox.getNorth() + 0.0001,
210             right: bbox.getEast() + 0.0001,
211             bottom: bbox.getSouth() - 0.0001
212           });
213
214     if (object && object.type !== "note") query.set("select", object.type + object.id); // can't select notes
215     sendRemoteEditCommand(remoteEditHost + "/load_and_zoom?" + query)
216       .then(() => {
217         if (object && object.type === "note") {
218           const noteQuery = new URLSearchParams({ url: osmHost + OSM.apiUrl(object) });
219           sendRemoteEditCommand(remoteEditHost + "/import?" + noteQuery);
220         }
221       })
222       .catch(() => {
223         OSM.showAlert(OSM.i18n.t("javascripts.remote_edit.failed.title"),
224                       OSM.i18n.t("javascripts.remote_edit.failed.body"));
225       });
226
227     function sendRemoteEditCommand(url) {
228       return fetch(url, { mode: "no-cors", signal: AbortSignal.timeout(5000) });
229     }
230
231     return false;
232   }
233
234   $("a[data-editor=remote]").click(function (e) {
235     const params = OSM.mapParams(this.search);
236     remoteEditHandler(map.getBounds(), params.object);
237     e.preventDefault();
238   });
239
240   if (new URLSearchParams(location.search).get("edit_help")) {
241     $("#editanchor")
242       .removeAttr("title")
243       .tooltip({
244         placement: "bottom",
245         title: OSM.i18n.t("javascripts.edit_help")
246       })
247       .tooltip("show");
248
249     $("body").one("click", function () {
250       $("#editanchor").tooltip("hide");
251     });
252   }
253
254   OSM.router = OSM.Router(map, {
255     "/": "index",
256     "/search": "search",
257     "/directions": "directions",
258     "/export": "export",
259     "/note/new": "new_note",
260     "/history/friends": "history",
261     "/history/nearby": "history",
262     "/history": "history",
263     "/user/:display_name/history": "history",
264     "/note/:id": "note",
265     "/node/:id(/history)": { module: "index_element", part: m => m.mappedElement("node") },
266     "/node/:id/history/:version": { module: "index_element", part: m => m.mappedElement("node") },
267     "/way/:id(/history)": { module: "index_element", part: m => m.mappedElement("way") },
268     "/way/:id/history/:version": { module: "index_element", part: m => m.element("way") },
269     "/relation/:id(/history)": { module: "index_element", part: m => m.mappedElement("relation") },
270     "/relation/:id/history/:version": { module: "index_element", part: m => m.element("relation") },
271     "/changeset/:id": "changeset",
272     "/query": "query",
273     "/account/home": "home"
274   });
275
276   if (OSM.preferred_editor === "remote" && location.pathname === "/edit") {
277     remoteEditHandler(map.getBounds(), params.object);
278     OSM.router.setCurrentPath("/");
279   }
280
281   OSM.router.load();
282
283   $(document).on("click", "a", function (e) {
284     if (e.isDefaultPrevented() || e.isPropagationStopped() || $(e.target).data("turbo")) {
285       return;
286     }
287
288     // Open links in a new tab as normal.
289     if (e.which > 1 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) {
290       return;
291     }
292
293     // Open local anchor links as normal.
294     if ($(this).attr("href")?.startsWith("#")) {
295       return;
296     }
297
298     // Ignore cross-protocol and cross-origin links.
299     const url = new URL($(this).attr("href"), location);
300     if (location.protocol !== url.protocol || location.host !== url.host) {
301       return;
302     }
303
304     if (OSM.router.route(url.pathname + url.search + url.hash)) {
305       e.preventDefault();
306       if (url.pathname !== "/directions") {
307         $(".navbar-toggler:not(.collapsed)").trigger("click");
308       }
309     }
310   });
311
312   $(document).on("click", "#sidebar .sidebar-close-controls button", function () {
313     $(".search_form input[name=query]").val("");
314     OSM.router.route("/" + OSM.formatHash(map));
315   });
316 });