diff --git a/src/index.js b/src/index.js index 91c9cc6..83494ee 100644 --- a/src/index.js +++ b/src/index.js @@ -32,3 +32,46 @@ document.addEventListener('DOMContentLoaded', () => { ); } }); + +// Persist #settings across links to same page +window.addEventListener('click', function (ev) { + if (window.location.hash.length == 0) { + return true; + } + if (ev.altKey || ev.ctrlKey || ev.metaKey || ev.shiftKey || ev.defaultPrevented) { + return true; + } + var a = null; + for (var n = ev.target; n.parentNode; n = n.parentNode) { + if (n.nodeName === 'A') { + a = n; + break; + } + } + if (!a || !a.href) { + return true; + } + // This expands the full URL even if the link is /relative: + var href = a.href; + // Split off any existing #fragment + href = href.split('#')[0]; + // Only activate if link is to current page (presumably with different querystring) + var currentHostAndPath = window.location.hostname; + if (window.location.port !== '') { + currentHostAndPath += ':' + window.location.port; + } + currentHostAndPath += window.location.pathname; + // Ignore http/s due to https://github.com/simonw/datasette/issues/333 + var linkedHostQuery = href.split('?')[1]; + var linkedHostAndPath = href.split('://')[1].split('?')[0]; + if (currentHostAndPath == linkedHostAndPath) { + // Cancel click, navigate to this + fragment instead + if (linkedHostQuery) { + linkedHostAndPath += '?' + linkedHostQuery; + } + ev.preventDefault(); + window.location = window.location.protocol + '//' + linkedHostAndPath + window.location.hash; + return false; + } + return true; +});