Skip to content

Commit

Permalink
feat: Add directional scroll behavior (#39)
Browse files Browse the repository at this point in the history
  • Loading branch information
manzt authored Aug 10, 2024
1 parent 92f995b commit e2a554c
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/clients/DataTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ export class DataTable extends MosaicClient {
this.#shadowRoot.appendChild(root);
this.#tableRoot = root;

addDirectionalScrollWithPreventDefault(this.#tableRoot);

// scroll event listener
this.#tableRoot.addEventListener("scroll", async () => {
let isAtBottom =
Expand Down Expand Up @@ -556,3 +558,44 @@ function asc(field: string): SQLExpression {
expr._expr[0] = expr._expr[0].replace("DESC", "ASC");
return expr;
}

/**
* Adds custom wheel behavior to an HTML element, allowing either horizontal or vertical scrolling based on the scroll input.
* Prevents default scrolling to stop event propagation to parent elements.
*
* @param {HTMLElement} root - The element to apply the scroll behavior to.
* @param {number} [scrollThreshold=10] - The minimum delta required to trigger horizontal or vertical scrolling.
*/
function addDirectionalScrollWithPreventDefault(
root: HTMLElement,
scrollThreshold: number = 10,
) {
let accumulatedDeltaX = 0;
let accumulatedDeltaY = 0;

root.addEventListener(
"wheel",
(event) => {
event.preventDefault();
accumulatedDeltaX += event.deltaX;
accumulatedDeltaY += event.deltaY;

if (Math.abs(accumulatedDeltaX) > Math.abs(accumulatedDeltaY)) {
// horizontal scrolling
if (Math.abs(accumulatedDeltaX) > scrollThreshold) {
root.scrollLeft += accumulatedDeltaX;
accumulatedDeltaX = 0;
accumulatedDeltaY = 0; // Reset Y to avoid unintentional vertical scrolling
}
} else {
// vertical scrolling
if (Math.abs(accumulatedDeltaY) > scrollThreshold) {
root.scrollTop += accumulatedDeltaY;
accumulatedDeltaX = 0; // Reset X to avoid unintentional horizontal scrolling
accumulatedDeltaY = 0;
}
}
},
{ passive: false },
);
}

0 comments on commit e2a554c

Please sign in to comment.