summaryrefslogtreecommitdiffhomepage
path: root/packages/ui/src/hooks/create-auto-scroll.tsx
blob: 1fb2e0c813ff9fac8cd54d32fc84cd003125b867 (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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import { createEffect, onCleanup } 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,
    userScrolled: false,
  })

  let lastScrollTop = 0
  let isAutoScrolling = false
  let autoScrollTimeout: ReturnType<typeof setTimeout> | undefined
  let isMouseDown = false
  let cleanupListeners: (() => void) | undefined
  let scheduledScroll = false
  let scheduledForce = false

  function distanceFromBottom() {
    if (!scrollRef) return 0
    return scrollRef.scrollHeight - scrollRef.clientHeight - scrollRef.scrollTop
  }

  function startAutoScroll() {
    isAutoScrolling = true
    if (autoScrollTimeout) clearTimeout(autoScrollTimeout)
    autoScrollTimeout = setTimeout(() => {
      isAutoScrolling = false
    }, 1000)
  }

  function scrollToBottomNow() {
    if (!scrollRef || store.userScrolled || !options.working()) return

    const distance = distanceFromBottom()
    if (distance < 2) return

    const behavior = distance > 96 ? "auto" : "smooth"
    startAutoScroll()
    scrollRef.scrollTo({
      top: scrollRef.scrollHeight,
      behavior,
    })
  }

  function forceScrollToBottomNow() {
    if (!scrollRef) return

    if (store.userScrolled) setStore("userScrolled", false)

    const distance = distanceFromBottom()
    if (distance < 2) return

    startAutoScroll()
    scrollRef.scrollTo({
      top: scrollRef.scrollHeight,
      behavior: "auto",
    })
  }

  function scheduleScrollToBottom(force = false) {
    if (typeof requestAnimationFrame === "undefined") {
      if (force) {
        forceScrollToBottomNow()
        return
      }
      scrollToBottomNow()
      return
    }

    if (force) scheduledForce = true
    if (scheduledScroll) return

    scheduledScroll = true
    requestAnimationFrame(() => {
      scheduledScroll = false

      const shouldForce = scheduledForce
      scheduledForce = false

      if (shouldForce) {
        forceScrollToBottomNow()
        return
      }

      scrollToBottomNow()
    })
  }

  function scrollToBottom() {
    scheduleScrollToBottom(false)
  }

  function forceScrollToBottom() {
    scheduleScrollToBottom(true)
  }

  function handleScroll() {
    if (!scrollRef) return

    const { scrollTop, scrollHeight, clientHeight } = scrollRef
    const atBottom = Math.abs(scrollHeight - clientHeight - scrollTop) < 10

    if (isAutoScrolling) {
      if (atBottom) {
        isAutoScrolling = false
        if (autoScrollTimeout) clearTimeout(autoScrollTimeout)
      }
      lastScrollTop = scrollTop
      return
    }

    if (atBottom) {
      if (store.userScrolled) {
        setStore("userScrolled", false)
      }
      lastScrollTop = scrollTop
      return
    }

    const delta = scrollTop - lastScrollTop
    if (delta < 0) {
      if (isMouseDown && !store.userScrolled && options.working()) {
        setStore("userScrolled", true)
        options.onUserInteracted?.()
      }
    }

    lastScrollTop = scrollTop
  }

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

  function handleWheel(e: WheelEvent) {
    if (e.deltaY < 0 && !store.userScrolled && options.working()) {
      setStore("userScrolled", true)
      options.onUserInteracted?.()
    }
  }

  function handleTouchStart() {
    if (!store.userScrolled && options.working()) {
      setStore("userScrolled", true)
      options.onUserInteracted?.()
    }
  }

  function handleKeyDown(e: KeyboardEvent) {
    if (["ArrowUp", "PageUp", "Home"].includes(e.key)) {
      if (!store.userScrolled && options.working()) {
        setStore("userScrolled", true)
        options.onUserInteracted?.()
      }
    }
  }

  function handleMouseDown() {
    isMouseDown = true
    window.addEventListener("mouseup", handleMouseUp)
  }

  function handleMouseUp() {
    isMouseDown = false
    window.removeEventListener("mouseup", handleMouseUp)
  }

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

  // Ensure pinned-to-bottom stays pinned during heavy DOM updates
  createEffect(() => {
    const el = store.contentRef
    if (!el) return

    const observer = new MutationObserver(() => {
      if (store.userScrolled) return
      if (!options.working()) return
      scheduleScrollToBottom(false)
    })
    observer.observe(el, { childList: true, subtree: true, characterData: true })
    onCleanup(() => observer.disconnect())
  })

  // Handle content resize
  createResizeObserver(
    () => store.contentRef,
    () => {
      if (options.working() && !store.userScrolled) {
        scrollToBottom()
      }
    },
  )

  onCleanup(() => {
    if (autoScrollTimeout) clearTimeout(autoScrollTimeout)
    if (cleanupListeners) cleanupListeners()
  })

  return {
    scrollRef: (el: HTMLElement | undefined) => {
      if (cleanupListeners) {
        cleanupListeners()
        cleanupListeners = undefined
      }

      scrollRef = el
      if (el) {
        lastScrollTop = el.scrollTop
        el.style.overflowAnchor = "none"

        el.addEventListener("wheel", handleWheel, { passive: true })
        el.addEventListener("touchstart", handleTouchStart, { passive: true })
        el.addEventListener("keydown", handleKeyDown)
        el.addEventListener("mousedown", handleMouseDown)

        cleanupListeners = () => {
          el.removeEventListener("wheel", handleWheel)
          el.removeEventListener("touchstart", handleTouchStart)
          el.removeEventListener("keydown", handleKeyDown)
          el.removeEventListener("mousedown", handleMouseDown)
          window.removeEventListener("mouseup", handleMouseUp)
        }
      }
    },
    contentRef: (el: HTMLElement | undefined) => setStore("contentRef", el),
    handleScroll,
    handleInteraction,
    scrollToBottom,
    forceScrollToBottom,
    userScrolled: () => store.userScrolled,
  }
}