]> git.openstreetmap.org Git - rails.git/blob - app/assets/javascripts/index/history.js
50d3f70b9f1e332ddab03aab08ee4f4ec9eb7f78
[rails.git] / app / assets / javascripts / index / history.js
1 //= require jquery-simulate/jquery.simulate
2
3 OSM.History = function (map) {
4   const page = {};
5
6   $("#sidebar_content")
7     .on("click", ".changeset_more a", loadMoreChangesets)
8     .on("mouseover", "[data-changeset]", function () {
9       highlightChangeset($(this).data("changeset").id);
10     })
11     .on("mouseout", "[data-changeset]", function () {
12       unHighlightChangeset($(this).data("changeset").id);
13     });
14
15   const group = L.featureGroup()
16     .on("mouseover", function (e) {
17       highlightChangeset(e.layer.id);
18     })
19     .on("mouseout", function (e) {
20       unHighlightChangeset(e.layer.id);
21     })
22     .on("click", function (e) {
23       clickChangeset(e.layer.id, e.originalEvent);
24     });
25
26   group.getLayerId = function (layer) {
27     return layer.id;
28   };
29
30   let changesetIntersectionObserver;
31
32   function disableChangesetIntersectionObserver() {
33     if (changesetIntersectionObserver) {
34       changesetIntersectionObserver.disconnect();
35       changesetIntersectionObserver = null;
36     }
37   }
38
39   function enableChangesetIntersectionObserver() {
40     disableChangesetIntersectionObserver();
41     if (!window.IntersectionObserver) return;
42
43     let ignoreIntersectionEvents = true;
44
45     changesetIntersectionObserver = new IntersectionObserver((entries) => {
46       if (ignoreIntersectionEvents) {
47         ignoreIntersectionEvents = false;
48         return;
49       }
50
51       let closestTargetToTop,
52           closestDistanceToTop = Infinity,
53           closestTargetToBottom,
54           closestDistanceToBottom = Infinity;
55
56       for (const entry of entries) {
57         if (entry.isIntersecting) continue;
58
59         const distanceToTop = entry.rootBounds.top - entry.boundingClientRect.bottom;
60         const distanceToBottom = entry.boundingClientRect.top - entry.rootBounds.bottom;
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       if (closestTargetToTop && closestDistanceToTop < closestDistanceToBottom) {
72         const id = $(closestTargetToTop).data("changeset")?.id;
73         if (id) {
74           OSM.router.replace(location.pathname + "?" + new URLSearchParams({ before: id }) + location.hash);
75         }
76       } else if (closestTargetToBottom) {
77         const id = $(closestTargetToBottom).data("changeset")?.id;
78         if (id) {
79           OSM.router.replace(location.pathname + "?" + new URLSearchParams({ after: id }) + location.hash);
80         }
81       }
82     }, { root: $("#sidebar")[0] });
83
84     $("#sidebar_content .changesets ol").children().each(function () {
85       changesetIntersectionObserver.observe(this);
86     });
87   }
88
89   function highlightChangeset(id) {
90     const layer = group.getLayer(id);
91     if (layer) layer.setStyle({ fillOpacity: 0.3, color: "#FF6600", weight: 3 });
92     $("#changeset_" + id).addClass("selected");
93   }
94
95   function unHighlightChangeset(id) {
96     const layer = group.getLayer(id);
97     if (layer) layer.setStyle({ fillOpacity: 0, color: "#FF9500", weight: 2 });
98     $("#changeset_" + id).removeClass("selected");
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
109   function displayMoreChangesets(div, html) {
110     const sidebar = $("#sidebar")[0];
111     const previousScrollHeightMinusTop = sidebar.scrollHeight - sidebar.scrollTop;
112
113     const oldList = $("#sidebar_content .changesets ol");
114
115     div.replaceWith(html);
116
117     const prevNewList = oldList.prevAll("ol");
118     if (prevNewList.length) {
119       prevNewList.next(".changeset_more").remove();
120       prevNewList.children().prependTo(oldList);
121       prevNewList.remove();
122
123       // restore scroll position only if prepending
124       sidebar.scrollTop = sidebar.scrollHeight - previousScrollHeightMinusTop;
125     }
126
127     const nextNewList = oldList.nextAll("ol");
128     if (nextNewList.length) {
129       nextNewList.prev(".changeset_more").remove();
130       nextNewList.children().appendTo(oldList);
131       nextNewList.remove();
132     }
133   }
134
135   function loadFirstChangesets() {
136     const data = new URLSearchParams();
137
138     disableChangesetIntersectionObserver();
139
140     if (location.pathname === "/history") {
141       data.set("bbox", map.getBounds().wrap().toBBoxString());
142       const feedLink = $("link[type=\"application/atom+xml\"]"),
143             feedHref = feedLink.attr("href").split("?")[0];
144       feedLink.attr("href", feedHref + "?" + data);
145     }
146
147     setListFetchData(data, location);
148
149     fetch(location.pathname + "?" + data)
150       .then(response => response.text())
151       .then(function (html) {
152         displayFirstChangesets(html);
153         enableChangesetIntersectionObserver();
154
155         if (data.has("before")) {
156           const [firstItem] = $("#sidebar_content .changesets ol").children().first();
157           firstItem?.scrollIntoView();
158         } else if (data.has("after")) {
159           const [lastItem] = $("#sidebar_content .changesets ol").children().last();
160           lastItem?.scrollIntoView(false);
161         } else {
162           const [sidebar] = $("#sidebar");
163           sidebar.scrollTop = 0;
164         }
165
166         updateMap();
167       });
168   }
169
170   function loadMoreChangesets(e) {
171     e.preventDefault();
172     e.stopPropagation();
173
174     const div = $(this).parents(".changeset_more");
175
176     div.find(".pagination").addClass("invisible");
177     div.find("[hidden]").prop("hidden", false);
178
179     const data = new URLSearchParams();
180
181     if (location.pathname === "/history") {
182       data.set("bbox", map.getBounds().wrap().toBBoxString());
183     }
184
185     const url = new URL($(this).attr("href"), location);
186     setListFetchData(data, url);
187
188     fetch(url.pathname + "?" + data)
189       .then(response => response.text())
190       .then(function (html) {
191         displayMoreChangesets(div, html);
192         enableChangesetIntersectionObserver();
193
194         updateMap();
195       });
196   }
197
198   function setListFetchData(data, url) {
199     const params = new URLSearchParams(url.search);
200
201     data.set("list", "1");
202
203     if (params.has("before")) {
204       data.set("before", params.get("before"));
205     }
206     if (params.has("after")) {
207       data.set("after", params.get("after"));
208     }
209   }
210
211   function reloadChangesetsBecauseOfMapMovement() {
212     OSM.router.replace("/history" + window.location.hash);
213     loadFirstChangesets();
214   }
215
216   let changesets = [];
217
218   function updateBounds() {
219     group.clearLayers();
220
221     for (const changeset of changesets) {
222       const bottomLeft = map.project(L.latLng(changeset.bbox.minlat, changeset.bbox.minlon)),
223             topRight = map.project(L.latLng(changeset.bbox.maxlat, changeset.bbox.maxlon)),
224             width = topRight.x - bottomLeft.x,
225             height = bottomLeft.y - topRight.y,
226             minSize = 20; // Min width/height of changeset in pixels
227
228       if (width < minSize) {
229         bottomLeft.x -= ((minSize - width) / 2);
230         topRight.x += ((minSize - width) / 2);
231       }
232
233       if (height < minSize) {
234         bottomLeft.y += ((minSize - height) / 2);
235         topRight.y -= ((minSize - height) / 2);
236       }
237
238       changeset.bounds = L.latLngBounds(map.unproject(bottomLeft),
239                                         map.unproject(topRight));
240     }
241
242     changesets.sort(function (a, b) {
243       return b.bounds.getSize() - a.bounds.getSize();
244     });
245
246     for (const changeset of changesets) {
247       const rect = L.rectangle(changeset.bounds,
248                                { weight: 2, color: "#FF9500", opacity: 1, fillColor: "#FFFFAF", fillOpacity: 0 });
249       rect.id = changeset.id;
250       rect.addTo(group);
251     }
252   }
253
254   function updateMap() {
255     changesets = $("[data-changeset]").map(function (index, element) {
256       return $(element).data("changeset");
257     }).get().filter(function (changeset) {
258       return changeset.bbox;
259     });
260
261     updateBounds();
262
263     if (location.pathname !== "/history") {
264       const bounds = group.getBounds();
265       if (bounds.isValid()) map.fitBounds(bounds);
266     }
267   }
268
269   page.pushstate = page.popstate = function (path) {
270     OSM.loadSidebarContent(path, page.load);
271   };
272
273   page.load = function () {
274     map.addLayer(group);
275
276     if (location.pathname === "/history") {
277       map.on("moveend", reloadChangesetsBecauseOfMapMovement);
278     }
279
280     map.on("zoomend", updateBounds);
281
282     loadFirstChangesets();
283   };
284
285   page.unload = function () {
286     map.removeLayer(group);
287     map.off("moveend", reloadChangesetsBecauseOfMapMovement);
288     map.off("zoomend", updateBounds);
289     disableChangesetIntersectionObserver();
290   };
291
292   return page;
293 };