-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathhistory.js
More file actions
413 lines (341 loc) · 12.8 KB
/
Copy pathhistory.js
File metadata and controls
413 lines (341 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//= require ./history-changesets-layer
OSM.History = function (map) {
const page = {};
$("#sidebar_content")
.on("click", ".changeset_more a", loadMoreChangesets)
.on("mouseover", "[data-changeset]", function () {
toggleChangesetHighlight($(this).data("changeset").id, true);
})
.on("mouseout", "[data-changeset]", function () {
toggleChangesetHighlight($(this).data("changeset").id, false);
});
let inZoom = false;
map.on("zoomstart", () => inZoom = true);
map.on("zoomend", () => inZoom = false);
const changesetsLayer = new OSM.HistoryChangesetsLayer()
.on("mouseover", function (e) {
if (inZoom) return;
toggleChangesetHighlight(e.layer.id, true);
})
.on("mouseout", function (e) {
if (inZoom) return;
toggleChangesetHighlight(e.layer.id, false);
})
.on("requestscrolltochangeset", function (e) {
const [item] = $(`#changeset_${e.id}`);
item?.scrollIntoView({ block: "nearest", behavior: "smooth" });
});
let changesetIntersectionObserver;
function safeHistoryT(key, options) {
try {
return OSM.i18n.t(key, options);
} catch (e) {
return key;
}
}
function buildFetchErrorMessage(response) {
const status = response?.status;
const statusText = response?.statusText;
const parts = [];
if (status) parts.push(status);
if (statusText) parts.push(statusText);
return parts.join(" ") || safeHistoryT("javascripts.history.load_failed_unknown");
}
function fetchHtmlOrThrow(url) {
return fetch(url).then(response => {
if (response.ok) return response.text();
throw new Error(buildFetchErrorMessage(response));
});
}
function removeHistoryLoadError() {
$("#sidebar_content .history-load-error").remove();
}
function showHistoryLoadError(options) {
const { message, retry } = options;
const detail = String(message ?? "");
// Always resolve targets from the live DOM (Turbo may replace sidebar HTML after fetch starts).
const $changesets = $("#sidebar_content .changesets");
const $target = $changesets.length ? $changesets : $("#sidebar_content");
removeHistoryLoadError();
try {
const $alert = $("<div class='history-load-error alert alert-warning p-3 mb-3'>")
.attr("role", "alert")
.append(
$("<div class='d-flex align-items-start gap-2'>").append(
$("<div class='flex-grow-1'>").append(
$("<div class='fw-semibold mb-1'>").text(safeHistoryT("javascripts.history.load_failed_title")),
$("<div class='text-break'>").text(safeHistoryT("javascripts.history.load_failed_body", { message: detail }))
),
$("<button type='button' class='btn-close'>")
.attr("aria-label", safeHistoryT("javascripts.close"))
.on("click", function () {
$alert.remove();
})
),
$("<div class='mt-3 d-flex flex-wrap gap-2'>").append(
$("<button type='button' class='btn btn-primary btn-sm'>")
.text(safeHistoryT("javascripts.history.try_again"))
.on("click", function () {
$alert.remove();
retry?.();
}),
$("<button type='button' class='btn btn-outline-secondary btn-sm'>")
.text(safeHistoryT("javascripts.history.reload_page"))
.on("click", function () {
location.reload();
})
)
);
$target.prepend($alert);
} catch (e) {
$target.prepend(
$("<div class='history-load-error alert alert-warning p-3 mb-3'>")
.attr("role", "alert")
.text(detail || safeHistoryT("javascripts.history.load_failed_unknown"))
);
}
}
function disableChangesetIntersectionObserver() {
if (changesetIntersectionObserver) {
changesetIntersectionObserver.disconnect();
changesetIntersectionObserver = null;
}
}
function enableChangesetIntersectionObserver() {
disableChangesetIntersectionObserver();
if (!window.IntersectionObserver) return;
let keepInitialLocation = true;
let itemsInViewport = $();
changesetIntersectionObserver = new IntersectionObserver((entries) => {
let closestTargetToTop,
closestDistanceToTop = Infinity,
closestTargetToBottom,
closestDistanceToBottom = Infinity;
for (const entry of entries) {
const id = $(entry.target).data("changeset")?.id;
if (entry.isIntersecting) {
itemsInViewport = itemsInViewport.add(entry.target);
if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, 0);
continue;
} else {
itemsInViewport = itemsInViewport.not(entry.target);
}
const distanceToTop = entry.rootBounds.top - entry.boundingClientRect.bottom;
const distanceToBottom = entry.boundingClientRect.top - entry.rootBounds.bottom;
if (distanceToTop >= 0 && distanceToTop < closestDistanceToTop) {
closestDistanceToTop = distanceToTop;
closestTargetToTop = entry.target;
}
if (distanceToBottom >= 0 && distanceToBottom <= closestDistanceToBottom) {
closestDistanceToBottom = distanceToBottom;
closestTargetToBottom = entry.target;
}
}
itemsInViewport.first().prevAll().each(function () {
const id = $(this).data("changeset")?.id;
if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, 1);
});
itemsInViewport.last().nextAll().each(function () {
const id = $(this).data("changeset")?.id;
if (id) changesetsLayer.setChangesetSidebarRelativePosition(id, -1);
});
changesetsLayer.updateChangesetsOrder();
if (keepInitialLocation) {
keepInitialLocation = false;
return;
}
if (closestTargetToTop && closestDistanceToTop < closestDistanceToBottom) {
const id = $(closestTargetToTop).data("changeset")?.id;
if (id) {
OSM.router.replace(location.pathname + "?" + new URLSearchParams({ before: id }) + location.hash);
}
} else if (closestTargetToBottom) {
const id = $(closestTargetToBottom).data("changeset")?.id;
if (id) {
OSM.router.replace(location.pathname + "?" + new URLSearchParams({ after: id }) + location.hash);
}
}
}, { root: $("#sidebar")[0] });
$("#sidebar_content .changesets ol").children().each(function () {
changesetIntersectionObserver.observe(this);
});
}
function toggleChangesetHighlight(id, state) {
changesetsLayer.toggleChangesetHighlight(id, state);
$("#sidebar_content .changesets ol li").removeClass("selected");
if (state) {
$("#changeset_" + id).addClass("selected");
}
}
function displayFirstChangesets(html) {
$("#sidebar_content .changesets").html(html);
$("#sidebar_content .changesets ol")
.before($("<div class='changeset-color-hint-bar opacity-75 sticky-top changeset-above-sidebar-viewport'>"))
.after($("<div class='changeset-color-hint-bar opacity-75 sticky-bottom changeset-below-sidebar-viewport'>"));
if (location.pathname === "/history") {
setPaginationMapHashes();
}
}
function displayMoreChangesets(div, html) {
const sidebar = $("#sidebar")[0];
const previousScrollHeightMinusTop = sidebar.scrollHeight - sidebar.scrollTop;
const oldList = $("#sidebar_content .changesets ol");
div.replaceWith(html);
const prevNewList = oldList.prevAll("ol");
if (prevNewList.length) {
prevNewList.next(".changeset_more").remove();
prevNewList.children().prependTo(oldList);
prevNewList.remove();
// restore scroll position only if prepending
sidebar.scrollTop = sidebar.scrollHeight - previousScrollHeightMinusTop;
}
const nextNewList = oldList.nextAll("ol");
if (nextNewList.length) {
nextNewList.prev(".changeset_more").remove();
nextNewList.children().appendTo(oldList);
nextNewList.remove();
}
if (location.pathname === "/history") {
setPaginationMapHashes();
}
}
function setPaginationMapHashes() {
$("#sidebar .pagination a").each(function () {
$(this).prop("hash", OSM.formatHash(map));
});
}
function applyFirstChangesetsHtml(html, data, isHistory) {
displayFirstChangesets(html);
enableChangesetIntersectionObserver();
if (data.has("before")) {
const [firstItem] = $("#sidebar_content .changesets ol").children().first();
firstItem?.scrollIntoView();
} else if (data.has("after")) {
const [lastItem] = $("#sidebar_content .changesets ol").children().last();
lastItem?.scrollIntoView(false);
} else {
const [sidebar] = $("#sidebar");
sidebar.scrollTop = 0;
}
updateMap(isHistory);
}
function loadFirstChangesets() {
const data = new URLSearchParams();
const isHistory = location.pathname === "/history";
disableChangesetIntersectionObserver();
if (isHistory) {
setBboxFetchData(data);
const feedLink = $("link[type=\"application/atom+xml\"]"),
feedHref = feedLink.attr("href").split("?")[0];
feedLink.attr("href", feedHref + "?" + data);
}
setListFetchData(data, location);
const url = location.pathname + "?" + data;
fetchHtmlOrThrow(url)
.then(function (html) {
removeHistoryLoadError();
applyFirstChangesetsHtml(html, data, isHistory);
})
.catch(function (error) {
if (error.name === "AbortError") return;
showHistoryLoadError({
message: String(error?.message || error || ""),
retry: loadFirstChangesets
});
});
}
function loadMoreChangesets(e) {
e.preventDefault();
e.stopPropagation();
const div = $(this).parents(".changeset_more");
const isHistory = location.pathname === "/history";
div.find(".pagination").addClass("invisible");
div.find("[hidden]").prop("hidden", false);
const data = new URLSearchParams();
if (location.pathname === "/history") {
setBboxFetchData(data);
}
const url = new URL($(this).attr("href"), location);
setListFetchData(data, url);
const fetchUrl = url.pathname + "?" + data;
fetchHtmlOrThrow(fetchUrl)
.then(function (html) {
removeHistoryLoadError();
displayMoreChangesets(div, html);
enableChangesetIntersectionObserver();
updateMap(isHistory);
})
.catch(function (error) {
if (error.name === "AbortError") return;
div.find(".pagination").removeClass("invisible");
div.find("[hidden]").prop("hidden", true);
showHistoryLoadError({
message: String(error?.message || error || ""),
retry: function () {
div.find("a.page-link").first().trigger("click");
}
});
});
}
function setBboxFetchData(data) {
const crs = map.options.crs;
const sw = map.getBounds().getSouthWest();
const ne = map.getBounds().getNorthEast();
const swClamped = crs.unproject(crs.project(sw));
const neClamped = crs.unproject(crs.project(ne));
if (sw.lat >= swClamped.lat || ne.lat <= neClamped.lat || ne.lng - sw.lng < 360) {
data.set("bbox", map.getBounds().toBBoxString());
}
}
function setListFetchData(data, url) {
const params = new URLSearchParams(url.search);
data.set("list", "1");
if (params.has("before")) {
data.set("before", params.get("before"));
}
if (params.has("after")) {
data.set("after", params.get("after"));
}
}
function moveEndListener() {
if (location.pathname === "/history") {
OSM.router.replace("/history" + window.location.hash);
loadFirstChangesets();
} else {
$("#sidebar_content .changesets ol li").removeClass("selected");
changesetsLayer.updateChangesetsGeometry(map);
}
}
function zoomEndListener() {
$("#sidebar_content .changesets ol li").removeClass("selected");
changesetsLayer.updateChangesetsGeometry(map);
}
function updateMap(isHistory) {
const changesets = $("[data-changeset]").map(function (index, element) {
return $(element).data("changeset");
}).get().filter(function (changeset) {
return changeset.bbox;
});
changesetsLayer.updateChangesets(map, changesets);
if (!isHistory) {
const bounds = changesetsLayer.getBounds();
if (bounds.isValid()) map.fitBounds(bounds);
}
}
page.pushstate = page.popstate = function (path) {
OSM.loadSidebarContent(path, page.load);
};
page.load = function () {
map.addLayer(changesetsLayer);
map.on("moveend", moveEndListener);
map.on("zoomend", zoomEndListener);
loadFirstChangesets();
};
page.unload = function () {
map.removeLayer(changesetsLayer);
map.off("moveend", moveEndListener);
map.off("zoomend", zoomEndListener);
disableChangesetIntersectionObserver();
};
return page;
};