Skip to content

Commit

Permalink
docs: allow scroll with keys
Browse files Browse the repository at this point in the history
  • Loading branch information
shahednasser committed Dec 27, 2024
1 parent 65d0a30 commit a2e4c6a
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions www/packages/docs-ui/src/hooks/use-scroll-utils/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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}
Expand Down

0 comments on commit a2e4c6a

Please sign in to comment.