Merged in feat/LOY-495-Stays-Sidepeek-Scroll-to-Top (pull request #3279)

Feat/LOY-495 Scroll to Top Functionality in Previous Stays Sidepeek

* feat(LOY-495): enable scroll to top functionality for past stays sidepeek


Approved-by: Emma Zettervall
Approved-by: Matilda Landström
This commit is contained in:
Chuma Mcphoy (We Ahead)
2025-12-05 05:41:02 +00:00
parent d6623adf9f
commit aae5c4d33d
3 changed files with 57 additions and 12 deletions

View File

@@ -2,41 +2,53 @@ import { type RefObject, useEffect, useState } from "react"
interface UseScrollToTopProps {
threshold: number
/**
* Direct element reference. Use this when the element is conditionally
* rendered or when you need to reference a parent element via state.
* Takes precedence over elementRef if both are provided.
*/
element?: HTMLElement | null
/**
* Ref to the element. Use this when you have a direct ref attachment
* to the scrollable element.
*/
elementRef?: RefObject<HTMLElement | null>
refScrollable?: boolean
}
export function useScrollToTop({
threshold,
element,
elementRef,
refScrollable,
}: UseScrollToTopProps) {
const [showBackToTop, setShowBackToTop] = useState(false)
useEffect(() => {
const element =
refScrollable && elementRef?.current ? elementRef?.current : window
const targetElement = element ?? elementRef?.current
const scrollTarget = refScrollable && targetElement ? targetElement : window
function handleScroll() {
let position = window.scrollY
if (elementRef?.current) {
if (targetElement) {
position = refScrollable
? elementRef.current.scrollTop
: elementRef.current.getBoundingClientRect().top * -1
? targetElement.scrollTop
: targetElement.getBoundingClientRect().top * -1
}
setShowBackToTop(position > threshold)
}
element.addEventListener("scroll", handleScroll, { passive: true })
return () => element.removeEventListener("scroll", handleScroll)
}, [threshold, elementRef, refScrollable])
scrollTarget.addEventListener("scroll", handleScroll, { passive: true })
return () => scrollTarget.removeEventListener("scroll", handleScroll)
}, [threshold, element, elementRef, refScrollable])
function scrollToTop() {
if (elementRef?.current) {
const targetElement = element ?? elementRef?.current
if (targetElement) {
if (refScrollable) {
elementRef.current.scrollTo({ top: 0, behavior: "smooth" })
targetElement.scrollTo({ top: 0, behavior: "smooth" })
}
window.scrollTo({ top: elementRef.current.offsetTop, behavior: "smooth" })
window.scrollTo({ top: targetElement.offsetTop, behavior: "smooth" })
} else {
window.scrollTo({ top: 0, behavior: "smooth" })
}