Handle browser history when opening/closing image preview

This commit is contained in:
Jérémie Astori 2017-09-06 00:56:11 -04:00
parent a44eea61a1
commit bb432497be
No known key found for this signature in database
GPG Key ID: B9A4F245CD67BDE8
2 changed files with 22 additions and 6 deletions

View File

@ -336,6 +336,8 @@ $(function() {
state.clickTarget = `#footer button[data-target="${target}"]`;
}
state.clickTarget += ", #image-viewer";
if (history && history.pushState) {
if (data && data.replaceHistory && history.replaceState) {
history.replaceState(state, null, null);

View File

@ -92,10 +92,10 @@ function handleImageInPreview(content, container) {
const imageViewer = $("#image-viewer");
$("#chat").on("click", ".toggle-thumbnail", function() {
$("#chat").on("click", ".toggle-thumbnail", function(event, data) {
const link = $(this);
openImageViewer(link);
openImageViewer(link, {pushState: !data || data.pushState !== false});
// Prevent the link to open a new page since we're opening the image viewer,
// but keep it a link to allow for Ctrl/Cmd+click.
@ -103,8 +103,8 @@ $("#chat").on("click", ".toggle-thumbnail", function() {
return false;
});
imageViewer.on("click", function() {
closeImageViewer();
imageViewer.on("click", function(event, data) {
closeImageViewer({pushState: !data || data.pushState !== false});
});
$(document).keydown(function(e) {
@ -125,7 +125,7 @@ $(document).keydown(function(e) {
}
});
function openImageViewer(link) {
function openImageViewer(link, {pushState = true}) {
$(".previous-image").removeClass("previous-image");
$(".next-image").removeClass("next-image");
@ -166,6 +166,15 @@ function openImageViewer(link) {
imageViewer
.off("transitionend")
.addClass("opened");
// History management
if (pushState) {
const clickTarget =
`#${link.closest(".msg").attr("id")} ` +
`a[href="${link.attr("href")}"] ` +
"img";
history.pushState({clickTarget: clickTarget}, null, null);
}
}
imageViewer.on("click", ".previous-image-btn", function() {
@ -178,7 +187,7 @@ imageViewer.on("click", ".next-image-btn", function() {
return false;
});
function closeImageViewer() {
function closeImageViewer({pushState = true}) {
imageViewer
.removeClass("opened")
.one("transitionend", function() {
@ -186,4 +195,9 @@ function closeImageViewer() {
});
input.focus();
// History management
if (pushState) {
history.pushState({clickTarget: "#image-viewer"}, null, null);
}
}