All files / src/dom scroll-smoother.ts

0% Statements 0/46
0% Branches 0/20
0% Functions 0/13
0% Lines 0/46

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                                                                                                                                                                                                                                                               
import * as mathf from '../mathf/mathf';
import {Raf} from '../raf/raf';
import {DomWatcher} from './dom-watcher';
 
export interface ScrollSmootherConfig {
  lerp: number;
  damp: number;
  root: HTMLElement;
  onUpdate?: Function;
  topMode?: boolean;
}
 
/**
 * Yes, it's a class to scroll jack.  Technically, what this does it attempt to
 * add a smooth damp the scrollY position to make the "mouse" experience better.
 *
 *
 * Usage is simple:
 * ```
 * <body>
 *   <div id="root">...my website</div>
 * </body>
 *
 *
 * const scrollSmoother = new ScrollSmoother({
 *  lerp: 0.23,
 *  damp: 0.2444,
 *  root: document.getElementById('root'),
 *  topMode: true
 * })
 *
 * scrollSmoother.run();
 *
 *
 *
 * Optional callback
 * const scrollSmoother = new ScrollSmoother({
 *  lerp: 0.23
 *  damp: 0.2444,
 *  root: document.getElementById('root'),
 *  onUpdate: (currentY, targetY)=> {
 *    ...
 *  }
 * })
 *
 *
 * ```
 *
 *
 * What is this doing?
 * Basically, when it runs, it will position fix the "root" element and then offset it by
 * the amount of scroll.
 */
export class ScrollSmoother {
  private settings: ScrollSmootherConfig;
  private domWatcher: DomWatcher;
  private raf: Raf;
  private rootElement: HTMLElement | null = null;
  // The current lerped y position.
  private currentY = 0;
  // The target y position.
  private targetY = 0;
 
  /*
   * @type ResizeObserver https://developer.mozilla.org/en-US/docs/Web/API/ResizeObserver
   */
  private resizer: ResizeObserver;
 
  constructor(config: ScrollSmootherConfig) {
    this.settings = config;
    this.raf = new Raf(this.onRaf.bind(this));
    this.raf.setReadWriteMode(true);
 
    this.domWatcher = new DomWatcher();
 
    this.resizer = new window['ResizeObserver'](
      (entries: Array<ResizeObserverEntry>) => {
        for (const entry of entries) {
          this.resize(entry.contentRect.height);
        }
      }
    );
    this.resizer.observe(this.settings.root);
 
    this.domWatcher.add({
      element: window,
      on: 'scroll',
      eventOptions: {passive: true},
      callback: this.onWindowScroll.bind(this),
    });
 
    this.resize();
    this.targetY = window.scrollY;
    this.raf.write(() => {
      this.updateScrollPosition(1, 1);
      this.raf.start();
    });
  }
 
  public resize(height?: number) {
    this.raf.read(() => {
      if (!height) {
        this.rootElement = this.settings.root;
        height = this.rootElement.offsetHeight;
      }
      this.onElementResize(height);
    });
  }
 
  private onElementResize(height: number) {
    // document.body.style.height = 'auto';
 
    this.raf.write(() => {
      document.body.style.height = height + 'px';
      this.rootElement!.style.position = 'fixed';
      this.rootElement!.style.width = '100%';
    });
  }
 
  private onRaf() {
    // Cull unncessary updated based on a precision.
    // Use precision 0, since we don't need subpixels.
    this.raf.postWrite(() => {
      this.updateScrollPosition(
        this.settings.lerp || 1,
        this.settings.damp || 1
      );
    });
  }
 
  private onWindowScroll() {
    this.raf &&
      this.raf.read(() => {
        this.targetY = window.scrollY;
      });
  }
 
  private updateScrollPosition(lerp = 1, damp = 1) {
    const prev = this.currentY;
    const updated = mathf.damp(this.currentY, this.targetY, lerp, damp);
    // updated = updated >> 0;
    this.currentY = updated;
    if (prev === updated) {
      return;
    }
 
    if (this.settings.topMode) {
      this.rootElement!.style.top = `-${this.currentY}px`;
    } else {
      this.rootElement!.style.transform =
        `translateY(-${this.currentY}px) translateZ(0)`;
    }
 
    if (this.settings.onUpdate) {
      this.settings.onUpdate(this.currentY, this.targetY);
    }
  }
 
  public dispose(): void {
    this.domWatcher && this.domWatcher.dispose();
    this.raf && this.raf.dispose();
    document.body.style.height = '';
    this.rootElement!.style.position = '';
    this.rootElement!.style.width = '';
    this.resizer['unobserve'](this.settings.root);
  }
}