summaryrefslogtreecommitdiffhomepage
path: root/packages/app/src/pages/session/scroll-spy.ts
blob: 6ef4c844c41c149be4366c13444a047c51e8ed85 (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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
type Visible = {
  id: string
  ratio: number
  top: number
}

type Offset = {
  id: string
  top: number
}

type Input = {
  onActive: (id: string) => void
  raf?: (cb: FrameRequestCallback) => number
  caf?: (id: number) => void
  IntersectionObserver?: typeof globalThis.IntersectionObserver
  ResizeObserver?: typeof globalThis.ResizeObserver
  MutationObserver?: typeof globalThis.MutationObserver
}

export const pickVisibleId = (list: Visible[], line: number) => {
  if (list.length === 0) return

  const sorted = [...list].sort((a, b) => {
    if (b.ratio !== a.ratio) return b.ratio - a.ratio

    const da = Math.abs(a.top - line)
    const db = Math.abs(b.top - line)
    if (da !== db) return da - db

    return a.top - b.top
  })

  return sorted[0]?.id
}

export const pickOffsetId = (list: Offset[], cutoff: number) => {
  if (list.length === 0) return

  let lo = 0
  let hi = list.length - 1
  let out = 0

  while (lo <= hi) {
    const mid = (lo + hi) >> 1
    const top = list[mid]?.top
    if (top === undefined) break

    if (top <= cutoff) {
      out = mid
      lo = mid + 1
      continue
    }

    hi = mid - 1
  }

  return list[out]?.id
}

export const createScrollSpy = (input: Input) => {
  const raf = input.raf ?? requestAnimationFrame
  const caf = input.caf ?? cancelAnimationFrame
  const CtorIO = input.IntersectionObserver ?? globalThis.IntersectionObserver
  const CtorRO = input.ResizeObserver ?? globalThis.ResizeObserver
  const CtorMO = input.MutationObserver ?? globalThis.MutationObserver

  let root: HTMLDivElement | undefined
  let io: IntersectionObserver | undefined
  let ro: ResizeObserver | undefined
  let mo: MutationObserver | undefined
  let frame: number | undefined
  let active: string | undefined
  let dirty = true

  const node = new Map<string, HTMLElement>()
  const id = new WeakMap<HTMLElement, string>()
  const visible = new Map<string, { ratio: number; top: number }>()
  let offset: Offset[] = []

  const schedule = () => {
    if (frame !== undefined) return
    frame = raf(() => {
      frame = undefined
      update()
    })
  }

  const refreshOffset = () => {
    const el = root
    if (!el) {
      offset = []
      dirty = false
      return
    }

    const base = el.getBoundingClientRect().top
    offset = [...node].map(([next, item]) => ({
      id: next,
      top: item.getBoundingClientRect().top - base + el.scrollTop,
    }))
    offset.sort((a, b) => a.top - b.top)
    dirty = false
  }

  const update = () => {
    const el = root
    if (!el) return

    const line = el.getBoundingClientRect().top + 100
    const next =
      pickVisibleId(
        [...visible].map(([k, v]) => ({
          id: k,
          ratio: v.ratio,
          top: v.top,
        })),
        line,
      ) ??
      (() => {
        if (dirty) refreshOffset()
        return pickOffsetId(offset, el.scrollTop + 100)
      })()

    if (!next || next === active) return
    active = next
    input.onActive(next)
  }

  const observe = () => {
    const el = root
    if (!el) return

    io?.disconnect()
    io = undefined
    if (CtorIO) {
      try {
        io = new CtorIO(
          (entries) => {
            for (const entry of entries) {
              const item = entry.target
              if (!(item instanceof HTMLElement)) continue
              const key = id.get(item)
              if (!key) continue

              if (!entry.isIntersecting || entry.intersectionRatio <= 0) {
                visible.delete(key)
                continue
              }

              visible.set(key, {
                ratio: entry.intersectionRatio,
                top: entry.boundingClientRect.top,
              })
            }

            schedule()
          },
          {
            root: el,
            threshold: [0, 0.25, 0.5, 0.75, 1],
          },
        )
      } catch {
        io = undefined
      }
    }

    if (io) {
      for (const item of node.values()) io.observe(item)
    }

    ro?.disconnect()
    ro = undefined
    if (CtorRO) {
      ro = new CtorRO(() => {
        dirty = true
        schedule()
      })
      ro.observe(el)
      for (const item of node.values()) ro.observe(item)
    }

    mo?.disconnect()
    mo = undefined
    if (CtorMO) {
      mo = new CtorMO(() => {
        dirty = true
        schedule()
      })
      mo.observe(el, { subtree: true, childList: true, characterData: true })
    }

    dirty = true
    schedule()
  }

  const setContainer = (el?: HTMLDivElement) => {
    if (root === el) return

    root = el
    visible.clear()
    active = undefined
    observe()
  }

  const register = (el: HTMLElement, key: string) => {
    const prev = node.get(key)
    if (prev && prev !== el) {
      io?.unobserve(prev)
      ro?.unobserve(prev)
    }

    node.set(key, el)
    id.set(el, key)
    if (io) io.observe(el)
    if (ro) ro.observe(el)
    dirty = true
    schedule()
  }

  const unregister = (key: string) => {
    const item = node.get(key)
    if (!item) return

    io?.unobserve(item)
    ro?.unobserve(item)
    node.delete(key)
    visible.delete(key)
    dirty = true
    schedule()
  }

  const markDirty = () => {
    dirty = true
    schedule()
  }

  const clear = () => {
    for (const item of node.values()) {
      io?.unobserve(item)
      ro?.unobserve(item)
    }

    node.clear()
    visible.clear()
    offset = []
    active = undefined
    dirty = true
  }

  const destroy = () => {
    if (frame !== undefined) caf(frame)
    frame = undefined
    clear()
    io?.disconnect()
    ro?.disconnect()
    mo?.disconnect()
    io = undefined
    ro = undefined
    mo = undefined
    root = undefined
  }

  return {
    setContainer,
    register,
    unregister,
    onScroll: schedule,
    markDirty,
    clear,
    destroy,
    getActiveId: () => active,
  }
}