|
| 1 | +/** |
| 2 | + * Prevents scroll events from escaping the given root (e.g., your app wrapper) into the host page/iframe parent. |
| 3 | + * It stops propagation on wheel/touchmove at the root and only preventsDefault when attempting to scroll past edges. |
| 4 | + * Returns a cleanup function to remove listeners. |
| 5 | + */ |
| 6 | +export function preventBounceScroll(): () => void { |
| 7 | + const touchStartYById = new Map<number, number>() |
| 8 | + |
| 9 | + const isAtEdge = (el: HTMLElement, delta: number): boolean => { |
| 10 | + const atTop = el.scrollTop <= 0 |
| 11 | + const atBottom = el.scrollTop + el.clientHeight >= el.scrollHeight - 1 |
| 12 | + const scrollingDown = delta > 0 |
| 13 | + const scrollingUp = delta < 0 |
| 14 | + return (atTop && scrollingUp) || (atBottom && scrollingDown) |
| 15 | + } |
| 16 | + |
| 17 | + const onWheel = (e: WheelEvent): void => { |
| 18 | + // Keep the event inside the iframe/root |
| 19 | + e.stopPropagation() |
| 20 | + if (isAtEdge(document.documentElement, e.deltaY)) { |
| 21 | + e.preventDefault() |
| 22 | + } |
| 23 | + } |
| 24 | + |
| 25 | + const onTouchStart = (e: TouchEvent): void => { |
| 26 | + if (e.touches.length > 0) { |
| 27 | + const touch = e.touches[0] |
| 28 | + if (touch) { |
| 29 | + touchStartYById.set(touch.identifier, touch.clientY) |
| 30 | + } |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + const onTouchMove = (e: TouchEvent): void => { |
| 35 | + if (e.touches.length === 0) return |
| 36 | + const touch = e.touches[0] |
| 37 | + if (!touch) return |
| 38 | + const startY = touchStartYById.get(touch.identifier) ?? touch.clientY |
| 39 | + const deltaY = startY - touch.clientY // positive when moving up |
| 40 | + |
| 41 | + // Keep the event inside the iframe/root |
| 42 | + e.stopPropagation() |
| 43 | + if (isAtEdge(document.documentElement, deltaY)) { |
| 44 | + e.preventDefault() |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + document.documentElement.addEventListener("wheel", onWheel, { |
| 49 | + passive: false, |
| 50 | + capture: true, |
| 51 | + }) |
| 52 | + document.documentElement.addEventListener("touchstart", onTouchStart, { |
| 53 | + passive: true, |
| 54 | + capture: true, |
| 55 | + }) |
| 56 | + document.documentElement.addEventListener("touchmove", onTouchMove, { |
| 57 | + passive: false, |
| 58 | + capture: true, |
| 59 | + }) |
| 60 | + |
| 61 | + return () => { |
| 62 | + document.documentElement.removeEventListener("wheel", onWheel, { |
| 63 | + capture: true, |
| 64 | + } as EventListenerOptions) |
| 65 | + document.documentElement.removeEventListener("touchstart", onTouchStart, { |
| 66 | + capture: true, |
| 67 | + } as EventListenerOptions) |
| 68 | + document.documentElement.removeEventListener("touchmove", onTouchMove, { |
| 69 | + capture: true, |
| 70 | + } as EventListenerOptions) |
| 71 | + touchStartYById.clear() |
| 72 | + } |
| 73 | +} |
0 commit comments