]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/history.js
Limit number of directions endpoint geocoding results to 1
[rails.git] / app / assets / javascripts / index / history.js
1 //= require jquery-simulate/jquery.simulate
2 //= require ./history-changesets-layer
3
4 OSM.History = function (map) {
5   const page = {};
6
7   $("#sidebar_content")
8     .on("click", ".changeset_more a", loadMoreChangesets)
9     .on("mouseover", "[data-changeset]", function () {
10       toggleChangesetHighlight($(this).data("changeset").id, true);
11     })
12     .on("mouseout", "[data-changeset]", function () {
13       toggleChangesetHighlight($(this).data("changeset").id, false);
14     });
15
16   let inZoom = false;
17   map.on("zoomstart", () => inZoom = true);
18   map.on("zoomend", () => inZoom = false);
19
20   const changesetsLayer = new OSM.HistoryChangesetsLayer()
21     .on("mouseover", function (e) {
22       if (inZoom) return;
23       toggleChangesetHighlight(e.layer.id, true);
24     })
25     .on("mouseout", function (e) {
26       if (inZoom) return;
27       toggleChangesetHighlight(e.layer.id, false);
28     })
29     .on("click", function (e) {
30       clickChangeset(e.layer.id, e.originalEvent);
31     });
32
33   let changesetIntersectionObserver;
34
35   function disableChangesetIntersectionObserver() {
36     if (changesetIntersectionObserver) {
37       changesetIntersectionObserver.disconnect();
38       changesetIntersectionObserver = null;
39     }
40   }
41
42   function enableChangesetIntersectionObserver() {
43     disableChangesetIntersectionObserver();
44     if (!window.IntersectionObserver) return;
45
46     let keepInitialLocation = true;
47     let itemsInViewport = $();
48
49     changesetIntersectionObserver = new IntersectionObserver((entries) => {
50       let closestTargetToTop,
51           closestDistanceToTop = Infinity,
52           closestTargetToBottom,
53           closestDistanceToBottom = Infinity;
54
55       for (const entry of entries) {
56         const id = $(entry.target).data("changeset")?.id;
57
58         if (entry.isIntersecting) {
59           itemsInViewport = itemsInViewport.add(entry.target);
60           if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, 0);
61           continue;
62         } else {
63           itemsInViewport = itemsInViewport.not(entry.target);
64         }
65
66         const distanceToTop = entry.rootBounds.top - entry.boundingClientRect.bottom;
67         const distanceToBottom = entry.boundingClientRect.top - entry.rootBounds.bottom;
68
69         if (distanceToTop >= 0 && distanceToTop < closestDistanceToTop) {
70           closestDistanceToTop = distanceToTop;
71           closestTargetToTop = entry.target;
72         }
73         if (distanceToBottom >= 0 && distanceToBottom <= closestDistanceToBottom) {
74           closestDistanceToBottom = distanceToBottom;
75           closestTargetToBottom = entry.target;
76         }
77       }
78
79       itemsInViewport.first().prevAll().each(function () {
80         const id = $(this).data("changeset")?.id;
81         if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, 1);
82       });
83       itemsInViewport.last().nextAll().each(function () {
84         const id = $(this).data("changeset")?.id;
85         if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, -1);
86       });
87
88       changesetsLayer.reorderChangesets();
89
90       if (keepInitialLocation) {
91         keepInitialLocation = false;
92         return;
93       }
94
95       if (closestTargetToTop && closestDistanceToTop < closestDistanceToBottom) {
96         const id = $(closestTargetToTop).data("changeset")?.id;
97         if (id) {
98           OSM.router.replace(location.pathname + "?" + new URLSearchParams({ before: id }) + location.hash);
99         }
100       } else if (closestTargetToBottom) {
101         const id = $(closestTargetToBottom).data("changeset")?.id;
102         if (id) {
103           OSM.router.replace(location.pathname + "?" + new URLSearchParams({ after: id }) + location.hash);
104         }
105       }
106     }, { root: $("#sidebar")[0] });
107
108     $("#sidebar_content .changesets ol").children().each(function () {
109       changesetIntersectionObserver.observe(this);
110     });
111   }
112
113   function toggleChangesetHighlight(id, state) {
114     changesetsLayer.toggleChangesetHighlight(id, state);
115     $("#changeset_" + id).toggleClass("selected", state);
116   }
117
118   function clickChangeset(id, e) {
119     $("#changeset_" + id).find("a.changeset_id").simulate("click", e);
120   }
121
122   function displayFirstChangesets(html) {
123     $("#sidebar_content .changesets").html(html);
124
125     $("#sidebar_content .changesets ol")
126       .before($("<div class='changeset-color-hint-bar opacity-75 sticky-top changeset-above-sidebar-viewport'>"))
127       .after($("<div class='changeset-color-hint-bar opacity-75 sticky-bottom changeset-below-sidebar-viewport'>"));
128
129     if (location.pathname === "/history") {
130       setPaginationMapHashes();
131     }
132   }
133
134   function displayMoreChangesets(div, html) {
135     const sidebar = $("#sidebar")[0];
136     const previousScrollHeightMinusTop = sidebar.scrollHeight - sidebar.scrollTop;
137
138     const oldList = $("#sidebar_content .changesets ol");
139
140     div.replaceWith(html);
141
142     const prevNewList = oldList.prevAll("ol");
143     if (prevNewList.length) {
144       prevNewList.next(".changeset_more").remove();
145       prevNewList.children().prependTo(oldList);
146       prevNewList.remove();
147
148       // restore scroll position only if prepending
149       sidebar.scrollTop = sidebar.scrollHeight - previousScrollHeightMinusTop;
150     }
151
152     const nextNewList = oldList.nextAll("ol");
153     if (nextNewList.length) {
154       nextNewList.prev(".changeset_more").remove();
155       nextNewList.children().appendTo(oldList);
156       nextNewList.remove();
157     }
158
159     if (location.pathname === "/history") {
160       setPaginationMapHashes();
161     }
162   }
163
164   function setPaginationMapHashes() {
165     $("#sidebar .pagination a").each(function () {
166       $(this).prop("hash", OSM.formatHash({
167         center: map.getCenter(),
168         zoom: map.getZoom()
169       }));
170     });
171   }
172
173   function loadFirstChangesets() {
174     const data = new URLSearchParams();
175
176     disableChangesetIntersectionObserver();
177
178     if (location.pathname === "/history") {
179       setBboxFetchData(data);
180       const feedLink = $("link[type=\"application/atom+xml\"]"),
181             feedHref = feedLink.attr("href").split("?")[0];
182       feedLink.attr("href", feedHref + "?" + data);
183     }
184
185     setListFetchData(data, location);
186
187     fetch(location.pathname + "?" + data)
188       .then(response => response.text())
189       .then(function (html) {
190         displayFirstChangesets(html);
191         enableChangesetIntersectionObserver();
192
193         if (data.has("before")) {
194           const [firstItem] = $("#sidebar_content .changesets ol").children().first();
195           firstItem?.scrollIntoView();
196         } else if (data.has("after")) {
197           const [lastItem] = $("#sidebar_content .changesets ol").children().last();
198           lastItem?.scrollIntoView(false);
199         } else {
200           const [sidebar] = $("#sidebar");
201           sidebar.scrollTop = 0;
202         }
203
204         updateMap();
205       });
206   }
207
208   function loadMoreChangesets(e) {
209     e.preventDefault();
210     e.stopPropagation();
211
212     const div = $(this).parents(".changeset_more");
213
214     div.find(".pagination").addClass("invisible");
215     div.find("[hidden]").prop("hidden", false);
216
217     const data = new URLSearchParams();
218
219     if (location.pathname === "/history") {
220       setBboxFetchData(data);
221     }
222
223     const url = new URL($(this).attr("href"), location);
224     setListFetchData(data, url);
225
226     fetch(url.pathname + "?" + data)
227       .then(response => response.text())
228       .then(function (html) {
229         displayMoreChangesets(div, html);
230         enableChangesetIntersectionObserver();
231
232         updateMap();
233       });
234   }
235
236   function setBboxFetchData(data) {
237     const crs = map.options.crs;
238     const sw = map.getBounds().getSouthWest();
239     const ne = map.getBounds().getNorthEast();
240     const swClamped = crs.unproject(crs.project(sw));
241     const neClamped = crs.unproject(crs.project(ne));
242
243     if (sw.lat >= swClamped.lat || ne.lat <= neClamped.lat || ne.lng - sw.lng < 360) {
244       data.set("bbox", map.getBounds().toBBoxString());
245     }
246   }
247
248   function setListFetchData(data, url) {
249     const params = new URLSearchParams(url.search);
250
251     data.set("list", "1");
252
253     if (params.has("before")) {
254       data.set("before", params.get("before"));
255     }
256     if (params.has("after")) {
257       data.set("after", params.get("after"));
258     }
259   }
260
261   function moveEndListener() {
262     if (location.pathname === "/history") {
263       OSM.router.replace("/history" + window.location.hash);
264       loadFirstChangesets();
265     } else {
266       changesetsLayer.updateChangesetLocations(map);
267     }
268   }
269
270   function zoomEndListener() {
271     changesetsLayer.updateChangesetShapes(map);
272   }
273
274   function updateMap() {
275     const changesets = $("[data-changeset]").map(function (index, element) {
276       return $(element).data("changeset");
277     }).get().filter(function (changeset) {
278       return changeset.bbox;
279     });
280
281     changesetsLayer.updateChangesets(map, changesets);
282
283     if (location.pathname !== "/history") {
284       const bounds = changesetsLayer.getBounds();
285       if (bounds.isValid()) map.fitBounds(bounds);
286     }
287   }
288
289   page.pushstate = page.popstate = function (path) {
290     OSM.loadSidebarContent(path, page.load);
291   };
292
293   page.load = function () {
294     map.addLayer(changesetsLayer);
295     map.on("moveend", moveEndListener);
296     map.on("zoomend", zoomEndListener);
297     loadFirstChangesets();
298   };
299
300   page.unload = function () {
301     map.removeLayer(changesetsLayer);
302     map.off("moveend", moveEndListener);
303     map.off("zoomend", zoomEndListener);
304     disableChangesetIntersectionObserver();
305   };
306
307   return page;
308 };