Skip to content

Commit

Permalink
fix(plus): scroll to anchor hook (#10364)
Browse files Browse the repository at this point in the history
When navigating to a page via anchor link, scroll to the anchor via JS.
We need this for non SSRed pages (mainly plus).

Correct scroll-margins is only supported Firefox (via :target) fully.
For some reason Blink and WebKit seem to not set :target consitently.
To work around this we set scroll-margin for section[id], too.
  • Loading branch information
fiji-flo authored Jan 23, 2024
1 parent fbe235e commit 20db7d1
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
6 changes: 4 additions & 2 deletions client/src/app.scss
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,13 @@
}
}

:target {
:target,
section[id] {
scroll-margin-top: var(--sticky-header-with-actions-height);
}

.sticky-header-container.without-actions ~ * :target {
.sticky-header-container.without-actions ~ * :target,
.sticky-header-container.without-actions ~ * section[id] {
scroll-margin-top: var(--sticky-header-without-actions-height);
}

Expand Down
14 changes: 14 additions & 0 deletions client/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -255,3 +255,17 @@ export function useIsIntersecting(
}, [node, options]);
return isIntersectingState;
}

export const useScrollToAnchor = () => {
const scrolledRef = React.useRef(false);
const { hash } = useLocation();
React.useEffect(() => {
if (hash && !scrolledRef.current) {
const element = document.getElementById(hash.replace("#", ""));
if (element) {
element.scrollIntoView({ behavior: "instant" });
scrolledRef.current = true;
}
}
});
};
2 changes: 2 additions & 0 deletions client/src/plus/offer-overview/index.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { useScrollToAnchor } from "../../hooks";
import OfferHero from "./offer-hero";
import OfferOverviewFeatures from "./offer-overview-feature";
import OfferOverviewSubscribe from "./offer-overview-subscribe";

function OfferOverview() {
useScrollToAnchor();
return (
<div className="offer-overview">
<OfferHero />
Expand Down
2 changes: 2 additions & 0 deletions client/src/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import "./index.scss";
import { Manage } from "./manage";
import Newsletter from "./newsletter";
import { ManageAIHelp } from "./ai-help";
import { useScrollToAnchor } from "../hooks";

const OfflineSettings = React.lazy(() => import("./offline-settings"));

export function Settings() {
const pageTitle = "Settings";
useScrollToAnchor();
return (
<>
<OfflineStatusBar />
Expand Down

0 comments on commit 20db7d1

Please sign in to comment.