summaryrefslogtreecommitdiffhomepage
path: root/packages/ui/src/hooks/create-auto-scroll.tsx
blob: 3bba7aec656449ac0ce8705d906814598d03d315 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
import { batch, createEffect } from "solid-js"
import { createStore } from "solid-js/store"
import { createResizeObserver } from "@solid-primitives/resize-observer"

export interface AutoScrollOptions {
  working: () => boolean
  onUserInteracted?: () => void
}

export function createAutoScroll(options: AutoScrollOptions) {
  let scrollRef: HTMLElement | undefined
  const [store, setStore] = createStore({
    contentRef: undefined as HTMLElement | undefined,
    lastScrollTop: 0,
    lastScrollHeight: 0,
    lastContentWidth: 0,
    autoScrolled: false,
    userScrolled: false,
    reflowing: false,
  })

  function scrollToBottom() {
    if (!scrollRef || store.userScrolled || !options.working()) return
    setStore("autoScrolled", true)
    const targetHeight = scrollRef.scrollHeight
    scrollRef.scrollTo({ top: targetHeight, behavior: "smooth" })

    // Wait for scroll to complete before clearing autoScrolled
    const checkScrollComplete = () => {
      if (!scrollRef) {
        setStore("autoScrolled", false)
        return
      }
      const atBottom = scrollRef.scrollTop + scrollRef.clientHeight >= scrollRef.scrollHeight - 10
      const reachedTarget = scrollRef.scrollTop >= targetHeight - scrollRef.clientHeight - 10
      if (atBottom || reachedTarget) {
        batch(() => {
          setStore("lastScrollTop", scrollRef?.scrollTop ?? 0)
          setStore("lastScrollHeight", scrollRef?.scrollHeight ?? 0)
          setStore("autoScrolled", false)
        })
      } else {
        requestAnimationFrame(checkScrollComplete)
      }
    }
    requestAnimationFrame(checkScrollComplete)
  }

  function handleScroll() {
    if (!scrollRef || store.autoScrolled) return

    const scrollTop = scrollRef.scrollTop
    const scrollHeight = scrollRef.scrollHeight

    if (store.reflowing) {
      batch(() => {
        setStore("lastScrollTop", scrollTop)
        setStore("lastScrollHeight", scrollHeight)
      })
      return
    }

    const scrollHeightChanged = Math.abs(scrollHeight - store.lastScrollHeight) > 10
    const scrollTopDelta = scrollTop - store.lastScrollTop

    // Handle reflow-caused scroll position changes
    if (scrollHeightChanged && scrollTopDelta < 0) {
      const heightRatio = store.lastScrollHeight > 0 ? scrollHeight / store.lastScrollHeight : 1
      const expectedScrollTop = store.lastScrollTop * heightRatio
      if (Math.abs(scrollTop - expectedScrollTop) < 100) {
        batch(() => {
          setStore("lastScrollTop", scrollTop)
          setStore("lastScrollHeight", scrollHeight)
        })
        return
      }
    }

    // Handle reset to top while working
    const reset = scrollTop <= 0 && store.lastScrollTop > 0 && options.working() && !store.userScrolled
    if (reset) {
      batch(() => {
        setStore("lastScrollTop", scrollTop)
        setStore("lastScrollHeight", scrollHeight)
      })
      requestAnimationFrame(scrollToBottom)
      return
    }

    // Detect intentional scroll up
    const scrolledUp = scrollTop < store.lastScrollTop - 50 && !scrollHeightChanged
    if (scrolledUp && options.working()) {
      setStore("userScrolled", true)
      options.onUserInteracted?.()
    }

    batch(() => {
      setStore("lastScrollTop", scrollTop)
      setStore("lastScrollHeight", scrollHeight)
    })
  }

  function handleInteraction() {
    if (options.working()) {
      setStore("userScrolled", true)
      options.onUserInteracted?.()
    }
  }

  // Reset userScrolled when work completes
  createEffect(() => {
    if (!options.working()) setStore("userScrolled", false)
  })

  // Handle content resize
  createResizeObserver(
    () => store.contentRef,
    ({ width }) => {
      const widthChanged = Math.abs(width - store.lastContentWidth) > 5
      if (widthChanged && store.lastContentWidth > 0) {
        setStore("reflowing", true)
        requestAnimationFrame(() => {
          requestAnimationFrame(() => {
            setStore("reflowing", false)
            if (options.working() && !store.userScrolled) {
              scrollToBottom()
            }
          })
        })
      } else if (!store.reflowing) {
        scrollToBottom()
      }
      setStore("lastContentWidth", width)
    },
  )

  return {
    scrollRef: (el: HTMLElement | undefined) => {
      scrollRef = el
    },
    contentRef: (el: HTMLElement | undefined) => setStore("contentRef", el),
    handleScroll,
    handleInteraction,
    scrollToBottom,
    userScrolled: () => store.userScrolled,
  }
}