Skip to content

Commit

Permalink
Fix page 'scroll to element' behaviour when URL hash is present
Browse files Browse the repository at this point in the history
  • Loading branch information
allmarkedup committed Oct 24, 2024
1 parent 3dc85f1 commit 1d3256a
Show file tree
Hide file tree
Showing 4 changed files with 54 additions and 6 deletions.
6 changes: 4 additions & 2 deletions app/components/lookbook/ui/app/router/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,14 @@ export default AlpineComponent("router", (sseEndpoint = null) => {
},

async loadPage(url, updateHistory = true) {
const [urlPath, urlHash] = url.toString().split("#");
this.$dispatch("page-load:start");
const result = await this.updateDOM(url, "main", {
const result = await this.updateDOM(urlPath, "main", {
headers: { "X-Lookbook-Frame": "main" },
});
if (updateHistory) {
history.pushState({}, "", result.url);
const fullUrl = urlHash ? `${result.url}#${urlHash}` : result.url;
history.pushState({}, "", fullUrl);
}
this.lastUpdate = Date.now();
this.routerLogger.debug(`Page loaded`);
Expand Down
7 changes: 6 additions & 1 deletion app/components/lookbook/ui/pages/page/page.html.erb
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
<%= render component_tag(class: {"with-footer": footer?}) do %>
<%= render component_tag(
class: {"with-footer": footer?},
x: {
data: "page",
"@page-load:complete.document": "scrollToTarget"
}) do %>
<article class="page-content-wrapper">
<div class="page-content">
<% if header? %>
Expand Down
18 changes: 18 additions & 0 deletions app/components/lookbook/ui/pages/page/page.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import AlpineComponent from "@js/alpine/component";

export default AlpineComponent("page", () => {
return {
init() {
setTimeout(() => this.scrollToTarget(), 1);
},

scrollToTarget() {
if (location.hash?.startsWith("#")) {
const scrollTarget = this.$root.querySelector(location.hash);
if (scrollTarget) {
scrollTarget.scrollIntoView({ behavior: "smooth" });
}
}
},
};
});
29 changes: 26 additions & 3 deletions public/lookbook-assets/app.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 1d3256a

Please sign in to comment.