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