dees-domtools/ts/domtools.classes.scroller.ts

78 lines
2.1 KiB
TypeScript
Raw Normal View History

import type { DomTools } from './domtools.classes.domtools.js';
2022-03-16 13:39:50 +01:00
import * as plugins from './domtools.plugins.js';
2020-06-28 17:40:03 +00:00
export class Scroller {
public domtoolsInstance: DomTools;
constructor(
domtoolsInstanceArg: DomTools,
) {
this.domtoolsInstance = domtoolsInstanceArg;
}
private sweetScroller = new plugins.SweetScroll({
/* some options */
}); // TODO: switch to scroller class
public async scrollToElement(
elementArg: HTMLElement,
optionsArg: Parameters<typeof this.sweetScroller.toElement>[1]
) {
this.sweetScroller.toElement(elementArg, optionsArg);
await plugins.smartdelay.delayFor(optionsArg.duration);
}
public async detectNativeSmoothScroll() {
const done = plugins.smartpromise.defer<boolean>();
const sampleSize = 100;
const acceptableDeltaDifference = 3;
const minimumSmoothRatio = 0.75;
const eventDeltas: number[] = [];
function onWheel(event: WheelEvent) {
eventDeltas.push(event.deltaY);
if (eventDeltas.length >= sampleSize) {
window.removeEventListener('wheel', onWheel);
analyzeEvents();
}
}
function analyzeEvents() {
const totalDiffs = eventDeltas.length - 1;
let smallDiffCount = 0;
for (let i = 0; i < totalDiffs; i++) {
const diff = Math.abs(eventDeltas[i + 1] - eventDeltas[i]);
if (diff <= acceptableDeltaDifference) {
smallDiffCount++;
}
}
const smoothRatio = smallDiffCount / totalDiffs;
if (smoothRatio >= minimumSmoothRatio) {
console.log('Smooth scrolling detected.');
done.resolve(true);
} else {
console.log('Smooth scrolling NOT detected.');
done.resolve(false);
}
}
window.addEventListener('wheel', onWheel);
return done.promise;
}
public async enableLenisScroll(optionsArg?: { disableOnNativeSmoothScroll?: boolean }) {
const lenis = new plugins.Lenis({
autoRaf: true,
});
if (optionsArg?.disableOnNativeSmoothScroll) {
if (await this.detectNativeSmoothScroll()) {
lenis.destroy();
}
}
}
2020-07-15 18:12:27 +00:00
}