Skip to content

Commit 63e3ed5

Browse files
committed
docs: add scroll to top button
Add ScrollToTop component that appears when the user scrolls down the page, allowing quick navigation back to the top of the document.
1 parent ef06eef commit 63e3ed5

2 files changed

Lines changed: 48 additions & 0 deletions

File tree

docs-website/src/App.res

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ let make = () => {
102102
{routes}
103103
<PageNavigation />
104104
</div>
105+
<ScrollToTop />
105106
</AppLayout>,
106107
]
107108
}
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
open Xote
2+
open Basefn
3+
4+
// Get scroll position
5+
let getScrollY: unit => float = %raw(`function() { return window.scrollY || 0 }`)
6+
7+
// Scroll to top
8+
let scrollToTop: unit => unit = %raw(`function() { window.scrollTo({ top: 0, behavior: 'smooth' }) }`)
9+
10+
// Add scroll listener
11+
let addScrollListener: (unit => unit) => unit => unit = %raw(`function(callback) {
12+
window.addEventListener('scroll', callback)
13+
return function() { window.removeEventListener('scroll', callback) }
14+
}`)
15+
16+
@jsx.component
17+
let make = () => {
18+
let isVisible = Signal.make(false)
19+
20+
let _ = Effect.run(() => {
21+
let cleanup = addScrollListener(() => {
22+
let scrollY = getScrollY()
23+
Signal.set(isVisible, scrollY > 300.0)
24+
})
25+
Some(cleanup)
26+
})
27+
28+
let handleClick = _ => {
29+
scrollToTop()
30+
}
31+
32+
Component.signalFragment(
33+
Computed.make(() => {
34+
if Signal.get(isVisible) {
35+
[
36+
<div style="position: fixed; bottom: 2rem; right: 2rem; z-index: 1000;">
37+
<Button variant={Secondary} onClick={handleClick}>
38+
<Icon name={ChevronUp} size={Md} />
39+
</Button>
40+
</div>,
41+
]
42+
} else {
43+
[]
44+
}
45+
}),
46+
)
47+
}

0 commit comments

Comments
 (0)