]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/history.js
Clean OSM.formatHash calls
[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.updateChangesetsOrder();
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(map));
167     });
168   }
169
170   function loadFirstChangesets() {
171     const data = new URLSearchParams();
172
173     disableChangesetIntersectionObserver();
174
175     if (location.pathname === "/history") {
176       setBboxFetchData(data);
177       const feedLink = $("link[type=\"application/atom+xml\"]"),
178             feedHref = feedLink.attr("href").split("?")[0];
179       feedLink.attr("href", feedHref + "?" + data);
180     }
181
182     setListFetchData(data, location);
183
184     fetch(location.pathname + "?" + data)
185       .then(response => response.text())
186       .then(function (html) {
187         displayFirstChangesets(html);
188         enableChangesetIntersectionObserver();
189
190         if (data.has("before")) {
191           const [firstItem] = $("#sidebar_content .changesets ol").children().first();
192           firstItem?.scrollIntoView();
193         } else if (data.has("after")) {
194           const [lastItem] = $("#sidebar_content .changesets ol").children().last();
195           lastItem?.scrollIntoView(false);
196         } else {
197           const [sidebar] = $("#sidebar");
198           sidebar.scrollTop = 0;
199         }
200
201         updateMap();
202       });
203   }
204
205   function loadMoreChangesets(e) {
206     e.preventDefault();
207     e.stopPropagation();
208
209     const div = $(this).parents(".changeset_more");
210
211     div.find(".pagination").addClass("invisible");
212     div.find("[hidden]").prop("hidden", false);
213
214     const data = new URLSearchParams();
215
216     if (location.pathname === "/history") {
217       setBboxFetchData(data);
218     }
219
220     const url = new URL($(this).attr("href"), location);
221     setListFetchData(data, url);
222
223     fetch(url.pathname + "?" + data)
224       .then(response => response.text())
225       .then(function (html) {
226         displayMoreChangesets(div, html);
227         enableChangesetIntersectionObserver();
228
229         updateMap();
230       });
231   }
232
233   function setBboxFetchData(data) {
234     const crs = map.options.crs;
235     const sw = map.getBounds().getSouthWest();
236     const ne = map.getBounds().getNorthEast();
237     const swClamped = crs.unproject(crs.project(sw));
238     const neClamped = crs.unproject(crs.project(ne));
239
240     if (sw.lat >= swClamped.lat || ne.lat <= neClamped.lat || ne.lng - sw.lng < 360) {
241       data.set("bbox", map.getBounds().toBBoxString());
242     }
243   }
244
245   function setListFetchData(data, url) {
246     const params = new URLSearchParams(url.search);
247
248     data.set("list", "1");
249
250     if (params.has("before")) {
251       data.set("before", params.get("before"));
252     }
253     if (params.has("after")) {
254       data.set("after", params.get("after"));
255     }
256   }
257
258   function moveEndListener() {
259     if (location.pathname === "/history") {
260       OSM.router.replace("/history" + window.location.hash);
261       loadFirstChangesets();
262     } else {
263       $("#sidebar_content .changesets ol li").removeClass("selected");
264       changesetsLayer.updateChangesetsGeometry(map);
265     }
266   }
267
268   function zoomEndListener() {
269     $("#sidebar_content .changesets ol li").removeClass("selected");
270     changesetsLayer.updateChangesetsGeometry(map);
271   }
272
273   function updateMap() {
274     const changesets = $("[data-changeset]").map(function (index, element) {
275       return $(element).data("changeset");
276     }).get().filter(function (changeset) {
277       return changeset.bbox;
278     });
279
280     changesetsLayer.updateChangesets(map, changesets);
281
282     if (location.pathname !== "/history") {
283       const bounds = changesetsLayer.getBounds();
284       if (bounds.isValid()) map.fitBounds(bounds);
285     }
286   }
287
288   page.pushstate = page.popstate = function (path) {
289     OSM.loadSidebarContent(path, page.load);
290   };
291
292   page.load = function () {
293     map.addLayer(changesetsLayer);
294     map.on("moveend", moveEndListener);
295     map.on("zoomend", zoomEndListener);
296     loadFirstChangesets();
297   };
298
299   page.unload = function () {
300     map.removeLayer(changesetsLayer);
301     map.off("moveend", moveEndListener);
302     map.off("zoomend", zoomEndListener);
303     disableChangesetIntersectionObserver();
304   };
305
306   return page;
307 };