Skip to content

Commit 6c95189

Browse files
authored
fix: patch docusaurus scroll behavior to fix anchors not working (#5192)
1 parent 3423c22 commit 6c95189

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
diff --git a/node_modules/@docusaurus/core/lib/client/ClientLifecyclesDispatcher.js b/node_modules/@docusaurus/core/lib/client/ClientLifecyclesDispatcher.js
2+
index 062d7c1..ebb4a89 100644
3+
--- a/node_modules/@docusaurus/core/lib/client/ClientLifecyclesDispatcher.js
4+
+++ b/node_modules/@docusaurus/core/lib/client/ClientLifecyclesDispatcher.js
5+
@@ -16,7 +16,19 @@ export function dispatchLifecycleAction(lifecycleAction, ...args) {
6+
}
7+
function scrollAfterNavigation({ location, previousLocation, }) {
8+
if (!previousLocation) {
9+
- return; // no-op: use native browser feature
10+
+ // if there is a hash and the element is not in view after some time, scroll to it
11+
+ const { hash } = location;
12+
+ if (!hash) {
13+
+ return; // no hash, noop out of function
14+
+ }
15+
+ setTimeout(() => {
16+
+ const id = decodeURIComponent(hash.substring(1));
17+
+ const element = document.getElementById(id);
18+
+ if(!isElementInView(element)) {
19+
+ element?.scrollIntoView({ behavior: 'instant'});
20+
+ }
21+
+ }, 1000)
22+
+ return; // no previous location so don't continue
23+
}
24+
const samePathname = location.pathname === previousLocation.pathname;
25+
const sameHash = location.hash === previousLocation.hash;
26+
@@ -27,12 +39,17 @@ function scrollAfterNavigation({ location, previousLocation, }) {
27+
}
28+
const { hash } = location;
29+
if (!hash) {
30+
- window.scrollTo(0, 0);
31+
+ window.scrollTo(0, 0);
32+
}
33+
else {
34+
- const id = decodeURIComponent(hash.substring(1));
35+
- const element = document.getElementById(id);
36+
- element?.scrollIntoView();
37+
+ const id = decodeURIComponent(hash.substring(1));
38+
+ const element = document.getElementById(id);
39+
+ element?.scrollIntoView();
40+
+ setTimeout(() => {
41+
+ if(!isElementInView(element)) {
42+
+ element?.scrollIntoView({ behavior: 'instant'});
43+
+ }
44+
+ }, 1000)
45+
}
46+
}
47+
function ClientLifecyclesDispatcher({ children, location, previousLocation, }) {
48+
@@ -44,4 +61,13 @@ function ClientLifecyclesDispatcher({ children, location, previousLocation, }) {
49+
}, [previousLocation, location]);
50+
return children;
51+
}
52+
+function isElementInView(el) {
53+
+ const rect = el.getBoundingClientRect();
54+
+ return (
55+
+ rect.top >= 0 &&
56+
+ rect.left >= 0 &&
57+
+ rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
58+
+ rect.right <= (window.innerWidth || document.documentElement.clientWidth)
59+
+ )
60+
+}
61+
export default ClientLifecyclesDispatcher;

0 commit comments

Comments
 (0)