|
1 |
| -import { useEffect, useState } from 'react' |
| 1 | +import { useEffect, useRef, useState, useTransition } from 'react' |
2 | 2 |
|
3 | 3 | let isUserDisabled = false
|
4 | 4 |
|
5 | 5 | export const useChatScroll = () => {
|
6 | 6 | // Todo: on long conversations this state update is not optimal. Ideally move it down the component tree.
|
7 | 7 | const [isAutoScrolling, setIsAutoScrolling] = useState(false)
|
8 | 8 |
|
| 9 | + const prevHeight = useRef(0) |
| 10 | + |
| 11 | + const [transitionPending, startTransition] = useTransition() |
| 12 | + |
9 | 13 | const autoScroll = () => {
|
10 |
| - if (isUserDisabled) return |
| 14 | + if (isUserDisabled || transitionPending) { |
| 15 | + console.log('skipped', isUserDisabled, transitionPending) |
| 16 | + return |
| 17 | + } |
11 | 18 |
|
12 |
| - window.scrollTo({ |
13 |
| - top: document.body.scrollHeight, |
14 |
| - }) |
| 19 | + const heightDiff = document.body.scrollHeight - prevHeight.current |
| 20 | + |
| 21 | + if (heightDiff > 0) { |
| 22 | + startTransition(() => { |
| 23 | + window.scrollTo({ |
| 24 | + top: document.body.scrollHeight, |
| 25 | + behavior: 'instant', |
| 26 | + }) |
| 27 | + prevHeight.current = document.body.scrollHeight |
| 28 | + }) |
| 29 | + } |
15 | 30 | }
|
16 | 31 |
|
17 | 32 | const beginAutoscroll = () => {
|
18 |
| - isUserDisabled = false |
19 |
| - setIsAutoScrolling(true) |
20 |
| - window.scrollTo({ |
21 |
| - top: document.body.scrollHeight, |
| 33 | + startTransition(() => { |
| 34 | + isUserDisabled = false |
| 35 | + setIsAutoScrolling(true) |
| 36 | + window.scrollTo({ |
| 37 | + top: document.body.scrollHeight, |
| 38 | + behavior: 'smooth', |
| 39 | + }) |
22 | 40 | })
|
23 | 41 | }
|
24 | 42 |
|
|
0 commit comments