docs: allow scroll with keys (#10752)

This commit is contained in:
Shahed Nasser
2024-12-27 11:12:23 +02:00
committed by GitHub
parent 65d0a300ce
commit 8839970295
@@ -20,6 +20,7 @@ import React, {
useState,
} from "react"
import { getScrolledTop as getScrolledTopUtil, isElmWindow } from "../../utils"
import { useKeyboardShortcut } from "../use-keyboard-shortcut"
type EventFunc = (...args: never[]) => unknown
@@ -141,6 +142,52 @@ export function ScrollControllerProvider({
const value = useScrollControllerContextValue({
scrollableSelector,
})
useKeyboardShortcut({
metakey: false,
shortcutKeys: ["ArrowUp", "ArrowDown", "PageUp", "PageDown", "Home", "End"],
action: (e) => {
// check that document or body are focused
const activeElement = document.activeElement
if (
isElmWindow(value.scrollableElement) ||
!value.scrollableElement ||
(activeElement !== document.body &&
activeElement !== document.documentElement)
) {
return
}
let newScroll = value.scrollableElement.scrollTop
const scrollThreshold = 50
const pageScrollAmount =
value.scrollableElement.clientHeight - scrollThreshold
switch (e.key) {
case "ArrowUp":
newScroll = -scrollThreshold
break
case "ArrowDown":
newScroll = scrollThreshold
break
case "PageUp":
newScroll = -pageScrollAmount
break
case "PageDown":
newScroll = pageScrollAmount
break
case "Home":
newScroll = -newScroll
break
case "End":
newScroll = value.scrollableElement.scrollHeight
}
value.scrollableElement?.scrollBy({
top: newScroll,
behavior: "smooth",
})
},
})
return (
<ScrollMonitorContext.Provider value={value}>
{children}