]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/directions.js
Fix next page boundary condition for user notes
[rails.git] / app / assets / javascripts / index / directions.js
1 //= require ./directions-endpoint
2 //= require ./directions-route-output
3 //= require_self
4 //= require_tree ./directions
5
6 OSM.Directions = function (map) {
7   let controller = null; // the AbortController for the current route request if a route request is in progress
8   let lastLocation = [];
9   let chosenEngine;
10
11   let sidebarReadyPromise = null;
12
13   const routeOutput = OSM.DirectionsRouteOutput(map);
14
15   const endpointDragCallback = function (dragging) {
16     if (!routeOutput.isVisible()) return;
17     if (dragging && !chosenEngine.draggable) return;
18     if (dragging && controller) return;
19
20     getRoute(false, !dragging);
21   };
22   const endpointChangeCallback = function () {
23     getRoute(true, true);
24   };
25
26   const endpoints = [
27     OSM.DirectionsEndpoint(map, $("input[name='route_from']"), { icon: "play", color: "var(--marker-green)" }, endpointDragCallback, endpointChangeCallback),
28     OSM.DirectionsEndpoint(map, $("input[name='route_to']"), { icon: "stop", color: "var(--marker-red)" }, endpointDragCallback, endpointChangeCallback)
29   ];
30
31   const expiry = new Date();
32   expiry.setYear(expiry.getFullYear() + 10);
33
34   const modeGroup = $(".routing_modes");
35   const select = $("select#routing_engines");
36
37   $(".directions_form .reverse_directions").on("click", function () {
38     const coordFrom = endpoints[0].latlng,
39           coordTo = endpoints[1].latlng;
40     let routeFrom = "",
41         routeTo = "";
42     if (coordFrom) {
43       routeFrom = coordFrom.lat + "," + coordFrom.lng;
44     }
45     if (coordTo) {
46       routeTo = coordTo.lat + "," + coordTo.lng;
47     }
48     endpoints[0].swapCachedReverseGeocodes(endpoints[1]);
49
50     OSM.router.route("/directions?" + new URLSearchParams({
51       route: routeTo + ";" + routeFrom
52     }));
53   });
54
55   $(".directions_form .btn-close").on("click", function (e) {
56     e.preventDefault();
57     $(".search_form input[name='query']").val(endpoints[1].value);
58     OSM.router.route("/" + OSM.formatHash(map));
59   });
60
61   function setEngine(id) {
62     const engines = OSM.Directions.engines;
63     const desired = engines.find(engine => engine.id === id);
64     if (!desired || (chosenEngine && chosenEngine.id === id)) return;
65     chosenEngine = desired;
66
67     const modes = engines
68       .filter(engine => engine.provider === chosenEngine.provider)
69       .map(engine => engine.mode);
70     modeGroup
71       .find("input[id]")
72       .prop("disabled", function () {
73         return !modes.includes(this.value);
74       })
75       .prop("checked", function () {
76         return this.value === chosenEngine.mode;
77       });
78
79     const providers = engines
80       .filter(engine => engine.mode === chosenEngine.mode)
81       .map(engine => engine.provider);
82     select
83       .find("option[value]")
84       .prop("disabled", function () {
85         return !providers.includes(this.value);
86       });
87     select.val(chosenEngine.provider);
88   }
89
90   function getRoute(fitRoute, reportErrors) {
91     // Cancel any route that is already in progress
92     if (controller) controller.abort();
93
94     const points = endpoints.map(p => p.latlng);
95
96     if (!points[0] || !points[1]) return;
97     $("header").addClass("closed");
98
99     OSM.router.replace("/directions?" + new URLSearchParams({
100       engine: chosenEngine.id,
101       route: points.map(p => `${p.lat},${p.lng}`).join(";")
102     }));
103
104     $("#directions_loader").prop("hidden", false);
105     $("#directions_error").prop("hidden", true).empty();
106     $("#directions_route").prop("hidden", true);
107     map.setSidebarOverlaid(false);
108     controller = new AbortController();
109     chosenEngine.getRoute(points, controller.signal).then(async function (route) {
110       await sidebarLoaded();
111       $("#directions_route").prop("hidden", false);
112       routeOutput.write(route);
113       if (fitRoute) {
114         routeOutput.fit();
115       }
116     }).catch(async function (error) {
117       if (error.name === "AbortError") return;
118       await sidebarLoaded();
119       routeOutput.remove();
120       if (reportErrors) {
121         $("#directions_error")
122           .prop("hidden", false)
123           .html("<div class=\"alert alert-danger\">" + OSM.i18n.t("javascripts.directions.errors.no_route") + "</div>");
124       }
125     }).finally(function () {
126       $("#directions_loader").prop("hidden", true);
127       controller = null;
128     });
129   }
130
131   function closeButtonListener(e) {
132     e.stopPropagation();
133     routeOutput.remove();
134     sidebarReadyPromise = null;
135     map.setSidebarOverlaid(true);
136     // TODO: collapse width of sidebar back to previous
137   }
138
139   setEngine("fossgis_osrm_car");
140   setEngine(Cookies.get("_osm_directions_engine"));
141
142   modeGroup.on("change", "input[name='modes']", function (e) {
143     setEngine(chosenEngine.provider + "_" + e.target.value);
144     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
145     getRoute(true, true);
146   });
147
148   select.on("change", function (e) {
149     setEngine(e.target.value + "_" + chosenEngine.mode);
150     Cookies.set("_osm_directions_engine", chosenEngine.id, { secure: true, expires: expiry, path: "/", samesite: "lax" });
151     getRoute(true, true);
152   });
153
154   $(".directions_form").on("submit", function (e) {
155     e.preventDefault();
156     getRoute(true, true);
157   });
158
159   $(".routing_marker_column span").on("dragstart", function (e) {
160     const dt = e.originalEvent.dataTransfer;
161     dt.effectAllowed = "move";
162     const jqthis = $(this);
163     dt.setData("text", JSON.stringify(jqthis.data()));
164     if (dt.setDragImage) {
165       const img = jqthis.clone()
166         .appendTo(document.body);
167       img.find("svg")
168         .toggleClass("position-absolute bottom-100 end-100")
169         .attr({ width: "25", height: "40" });
170       dt.setDragImage(img.get(0), 12, 21);
171       setTimeout(() => img.remove(), 0);
172     }
173   });
174
175   function sendstartinglocation({ latlng: { lat, lng } }) {
176     map.fire("startinglocation", { latlng: [lat, lng] });
177   }
178
179   function startingLocationListener({ latlng }) {
180     if (endpoints[0].value) return;
181     endpoints[0].setValue(latlng.join(", "));
182   }
183
184   map.on("locationfound", ({ latlng: { lat, lng } }) =>
185     lastLocation = [lat, lng]
186   ).on("locateactivate", () => {
187     map.once("startinglocation", startingLocationListener);
188   });
189
190   function initializeFromParams() {
191     const params = new URLSearchParams(location.search),
192           route = (params.get("route") || "").split(";");
193
194     if (params.has("engine")) setEngine(params.get("engine"));
195
196     endpoints[0].setValue(params.get("from") || route[0] || lastLocation.join(", "));
197     endpoints[1].setValue(params.get("to") || route[1] || "");
198   }
199
200   function enableListeners() {
201     $("#sidebar .sidebar-close-controls button").on("click", closeButtonListener);
202
203     $("#map").on("dragend dragover", function (e) {
204       e.preventDefault();
205     });
206
207     $("#map").on("drop", function (e) {
208       e.preventDefault();
209       const oe = e.originalEvent;
210       const dragData = JSON.parse(oe.dataTransfer.getData("text"));
211       const type = dragData.type;
212       const pt = L.DomEvent.getMousePosition(oe, map.getContainer()); // co-ordinates of the mouse pointer at present
213       pt.y += 20;
214       const ll = map.containerPointToLatLng(pt);
215       const llWithPrecision = OSM.cropLocation(ll, map.getZoom());
216       endpoints[type === "from" ? 0 : 1].setValue(llWithPrecision.join(", "));
217     });
218
219     map.on("locationfound", sendstartinglocation);
220
221     endpoints[0].enableListeners();
222     endpoints[1].enableListeners();
223   }
224
225   const page = {};
226
227   function sidebarLoaded() {
228     if ($("#directions_route").length) {
229       sidebarReadyPromise = null;
230       return Promise.resolve();
231     }
232     if (sidebarReadyPromise) return sidebarReadyPromise;
233     sidebarReadyPromise = new Promise(resolve => OSM.loadSidebarContent("/directions", resolve));
234     return sidebarReadyPromise;
235   }
236
237   page.pushstate = page.popstate = page.load = function () {
238     initializeFromParams();
239
240     $(".search_form").hide();
241     $(".directions_form").show();
242
243     sidebarLoaded().then(enableListeners);
244
245     map.setSidebarOverlaid(!endpoints[0].latlng || !endpoints[1].latlng);
246   };
247
248   page.unload = function () {
249     $(".search_form").show();
250     $(".directions_form").hide();
251
252     $("#sidebar .sidebar-close-controls button").off("click", closeButtonListener);
253     $("#map").off("dragend dragover drop");
254     map.off("locationfound", sendstartinglocation);
255
256     endpoints[0].disableListeners();
257     endpoints[1].disableListeners();
258
259     endpoints[0].clearValue();
260     endpoints[1].clearValue();
261
262     routeOutput.remove();
263
264     sidebarReadyPromise = null;
265   };
266
267   return page;
268 };
269
270 OSM.Directions.engines = [];
271
272 OSM.Directions.addEngine = function (engine, supportsHTTPS) {
273   if (location.protocol === "http:" || supportsHTTPS) {
274     engine.id = engine.provider + "_" + engine.mode;
275     OSM.Directions.engines.push(engine);
276   }
277 };