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