-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathAutoScrollArea.tsx
More file actions
64 lines (53 loc) · 1.39 KB
/
AutoScrollArea.tsx
File metadata and controls
64 lines (53 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import { css } from '@emotion/react'
import { ScrollArea, ScrollAreaProps } from '@radix-ui/themes'
import { ReactNode, UIEvent, useRef } from 'react'
import { useAutoScroll } from '@/hooks/useAutoScroll'
interface AutoScrollAreaProps extends Omit<ScrollAreaProps, 'onScroll'> {
tail?: boolean
items?: number
children?: ReactNode
onScrollBack?: () => void
}
export function AutoScrollArea({
tail = false,
items,
children,
onScrollBack,
...props
}: AutoScrollAreaProps) {
const ref = useAutoScroll(items, tail)
const scrollTop = useRef<number>(0)
const handleMount = (el: HTMLDivElement | null) => {
ref.current = el
if (el === null) {
return
}
scrollTop.current = el.scrollTop
}
const handleScroll = ({ currentTarget: target }: UIEvent<HTMLDivElement>) => {
if (!tail) {
return
}
// If the current scroll position is less than the previous one, the user scrolled up.
if (target.scrollTop < scrollTop.current) {
const isAtBottom =
target.scrollHeight - target.scrollTop <= target.clientHeight + 10
if (!isAtBottom) {
onScrollBack?.()
}
}
scrollTop.current = target.scrollTop
}
return (
<ScrollArea {...props} onScroll={handleScroll}>
<div
ref={handleMount}
css={css`
height: 100%;
`}
>
{children}
</div>
</ScrollArea>
)
}