Files

38 lines
1.7 KiB
JavaScript

// Keeps the editor from lingering in history once you leave it — while still
// letting the browser/Android Back button CANCEL an edit session.
//
// Opening the editor pushes a normal history entry, so Back exits the editor
// and returns to the page (the primary "back to cancel" gesture on mobile).
//
// Leaving the editor by CANCEL is the one transition we rewrite: the CANCEL
// link points back at the same page, so we replace the editor entry instead of
// pushing a second page entry on top of it. Without this, page -> edit -> CANCEL
// would leave [page, editor, page] and Back would walk straight back into the
// editor. SAVE does the equivalent from editor/main.js (replaceState + reload).
(function () {
function isEdit(loc) {
return new URLSearchParams(loc.search).has('edit');
}
document.addEventListener('click', function (e) {
if (e.defaultPrevented || e.button !== 0) return;
if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
var a = e.target.closest ? e.target.closest('a[href]') : null;
if (!a || a.target || a.hasAttribute('download')) return;
// Only act while inside the editor. Entering the editor stays a normal
// push so Back can cancel it.
if (!isEdit(window.location)) return;
var url = new URL(a.href, window.location.href);
if (url.origin !== window.location.origin) return;
if (url.pathname !== window.location.pathname) return;
// Leaving the editor to another page (e.g. a wikilink) keeps its normal
// push; only the same-page exit (CANCEL) is collapsed.
if (isEdit(url)) return;
e.preventDefault();
window.location.replace(url.href);
});
}());