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