File size: 1,683 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { progress } from '../../progress'

import type { OnScrollCallback } from './index'

const SCROLL_KEYS = {
  x: {
    length: 'Width',
    position: 'Left',
  },
  y: {
    length: 'Height',
    position: 'Top',
  },
} as const

/**
 * Whilst user's may not need the scrollLength, it's easier to return
 * the whole state we're storing and let them pick what they want.
 */
export interface ScrollAxis {
  current: number
  progress: number
  scrollLength: number
}

export interface ScrollInfo {
  time: number
  x: ScrollAxis
  y: ScrollAxis
}

/**
 * Why use a class? More extensible in the future.
 */
export class ScrollHandler {
  protected callback: OnScrollCallback
  protected container: HTMLElement
  protected info: ScrollInfo

  constructor(callback: OnScrollCallback, container: HTMLElement) {
    this.callback = callback
    this.container = container

    this.info = {
      time: 0,
      x: this.createAxis(),
      y: this.createAxis(),
    }
  }

  private createAxis = (): ScrollAxis => ({
    current: 0,
    progress: 0,
    scrollLength: 0,
  })

  private updateAxis = (axisName: keyof Pick<ScrollInfo, 'x' | 'y'>) => {
    const axis = this.info[axisName]
    const { length, position } = SCROLL_KEYS[axisName]

    axis.current = this.container[`scroll${position}`]
    axis.scrollLength =
      this.container[`scroll${length}`] - this.container[`client${length}`]

    axis.progress = progress(0, axis.scrollLength, axis.current)
  }

  private update = () => {
    this.updateAxis('x')
    this.updateAxis('y')
  }

  private sendEvent = () => {
    this.callback(this.info)
  }

  advance = () => {
    this.update()
    this.sendEvent()
  }
}