From bb432497becbe7b1d146f7ecf6b4218e7ec81dcd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Astori?= Date: Wed, 6 Sep 2017 00:56:11 -0400 Subject: [PATCH] Handle browser history when opening/closing image preview --- client/js/lounge.js | 2 ++ client/js/renderPreview.js | 26 ++++++++++++++++++++------ 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/client/js/lounge.js b/client/js/lounge.js index 27bbc960..08db54ec 100644 --- a/client/js/lounge.js +++ b/client/js/lounge.js @@ -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); diff --git a/client/js/renderPreview.js b/client/js/renderPreview.js index 6ece1b9d..b739b7e9 100644 --- a/client/js/renderPreview.js +++ b/client/js/renderPreview.js @@ -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); + } }