Files
archived-linsa/web/hooks/use-active-item-scroll.ts
Aslam 21084cd3f3 fix(link): Keybind, scroll behaviour, restrict drag to vertical (#176)
* chore: expose scrollActiveElementIntoView

* feat(utils): editable element

* fix: memoize exceptionRefs, use animation frame and check editable element

* fix: improve btn on mobile

* chore(drps): bump framer motion version

* fix(link): big fix

* chore: remove comment code

* feat: touch device
2024-09-21 19:37:29 +07:00

32 lines
952 B
TypeScript

import { useEffect, useRef, useCallback } from "react"
type ElementRef<T extends HTMLElement> = T | null
type ElementRefs<T extends HTMLElement> = ElementRef<T>[]
interface ActiveItemScrollOptions {
activeIndex: number | null
}
export function useActiveItemScroll<T extends HTMLElement>(options: ActiveItemScrollOptions) {
const { activeIndex } = options
const elementRefs = useRef<ElementRefs<T>>([])
const scrollActiveElementIntoView = useCallback((index: number) => {
const activeElement = elementRefs.current[index]
activeElement?.focus()
// activeElement?.scrollIntoView({ block: "nearest" })
}, [])
useEffect(() => {
if (activeIndex !== null) {
scrollActiveElementIntoView(activeIndex)
}
}, [activeIndex, scrollActiveElementIntoView])
const setElementRef = useCallback((element: ElementRef<T>, index: number) => {
elementRefs.current[index] = element
}, [])
return { setElementRef, scrollActiveElementIntoView }
}