~cytrogen/masto-fe

ref: 5c79cd6cf732c348b3cf63e9e6c79d189e42d08d masto-fe/app/javascript/flavours/glitch/scroll.ts -rw-r--r-- 1.2 KiB
5c79cd6c — Cytrogen [chore] Add .gstack/ to gitignore 4 days ago
                                                                                
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
const easingOutQuint = (
  _x: number,
  t: number,
  b: number,
  c: number,
  d: number,
) => c * ((t = t / d - 1) * t * t * t * t + 1) + b;
const scroll = (
  node: Element,
  key: "scrollTop" | "scrollLeft",
  target: number,
) => {
  const startTime = Date.now();
  const offset = node[key];
  const gap = target - offset;
  const duration = 1000;
  let interrupt = false;

  const step = () => {
    const elapsed = Date.now() - startTime;
    const percentage = elapsed / duration;

    if (percentage > 1 || interrupt) {
      return;
    }

    node[key] = easingOutQuint(0, elapsed, offset, gap, duration);
    requestAnimationFrame(step);
  };

  step();

  return () => {
    interrupt = true;
  };
};

const isScrollBehaviorSupported =
  "scrollBehavior" in document.documentElement.style;

export const scrollRight = (node: Element, position: number) => {
  if (isScrollBehaviorSupported) {
    node.scrollTo({ left: position, behavior: "smooth" });
  } else {
    scroll(node, "scrollLeft", position);
  }
};

export const scrollTop = (node: Element) => {
  if (isScrollBehaviorSupported) {
    node.scrollTo({ top: 0, behavior: "smooth" });
  } else {
    scroll(node, "scrollTop", 0);
  }
};