Skip to content

Commit

Permalink
Use explicit class instead of :target
Browse files Browse the repository at this point in the history
Turbo Drive breaks the browser's back / forward buttons when navigating
to a history entry that was not added by Turbo Drive.  (The URL in the
address bar changes, but the page itself does not.)  Therefore, this
commit abandons working around Turbo Drive to fix `:target` behavior,
and adds an explicit `.target` class in response to navigation events
instead.
  • Loading branch information
jonathanhefner committed Oct 21, 2023
1 parent 11f7ba4 commit 77d955d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 19 deletions.
2 changes: 1 addition & 1 deletion lib/rdoc/generator/template/rails/resources/css/main.css
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ html {
white-space: pre-wrap;
}

:target .method__signature code::before {
.target .method__signature code::before {
content: " ";

position: absolute;
Expand Down
34 changes: 16 additions & 18 deletions lib/rdoc/generator/template/rails/resources/js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,24 +56,22 @@ document.addEventListener("turbo:click", ({ target }) => {
addEventListener("turbo:render", function() {
document.getElementById("results").scrollTop = scrollTop
})
})()
})();


// Turbo Drive interferes with the browser designating the `:target` element for
// CSS. See https://github.com/hotwired/turbo/issues/592.
//
// Therefore, disable Turbo Drive for intra-page link clicks...
document.addEventListener("turbo:click", event => {
const targetUrl = new URL(event.detail.url);
if (targetUrl.hash && targetUrl.href === new URL(targetUrl.hash, location).href) {
event.preventDefault();
}
});
// ...and, if appropriate, trigger an intra-page navigation after `turbo:load`.
document.addEventListener("turbo:load", event => {
if (location.hash) {
const a = document.createElement("a");
a.href = location;
a.click();
}
});
// CSS (see https://github.com/hotwired/turbo/issues/592), so add an explicit
// class instead.
(function() {
const retarget = (url) => {
document.querySelector(".target")?.classList?.remove("target");
if (url.hash) {
document.getElementById(url.hash.substring(1))?.classList?.add("target");
}
};

// Unlike normal navigation, Turbo Drive fires the `hashchange` _before_
// `location` is changed, so we must use the `newURL` property.
window.addEventListener("hashchange", ({ newURL }) => retarget(new URL(newURL)));
document.addEventListener("turbo:load", event => retarget(location));
})();

0 comments on commit 77d955d

Please sign in to comment.