78 lines
2.1 KiB
TypeScript
78 lines
2.1 KiB
TypeScript
import type { DomTools } from './domtools.classes.domtools.js';
|
|
import * as plugins from './domtools.plugins.js';
|
|
|
|
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();
|
|
}
|
|
}
|
|
}
|
|
}
|