Created
November 23, 2021 07:20
-
-
Save pwfisher/d3402412ae6d0f375d780db140f8e927 to your computer and use it in GitHub Desktop.
ScrollToHack: scrollTo override — disable calls without "allowed" arg or property. Next.js History.scrollRestoration debug tool.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { FC, useEffect } from 'react' | |
type ScrollToOptionsPlusAllowed = ScrollToOptions & { allowed: boolean } | |
/** | |
* Hack to completely disable Next.js emulation of History.scrollRestoration. | |
* Everywhere we want to scroll, we must add `allowed: true`. | |
* @see https://github.com/vercel/next.js/issues/20951#issuecomment-970710409 | |
*/ | |
export const ScrollToHack: FC = () => { | |
useEffect(() => { | |
const { scrollTo } = window | |
// @ts-ignore hackScrollTo unused | |
const hackScrollTo: { | |
(options?: ScrollToOptionsPlusAllowed | undefined): void | |
(x: number, y: number, allowed?: boolean): void | |
} = (x?: ScrollToOptionsPlusAllowed | number, y?: number, allowedArg?: boolean) => { | |
console.log('[hackScrollTo] start', { x, y }) | |
if (typeof x === 'number' && typeof y === 'number') { | |
if (allowedArg) scrollTo(x, y) | |
else console.log('[hackScrollTo] not allowedArg') | |
return | |
} | |
if (!x) return | |
const { allowed, behavior, left, top } = x as ScrollToOptionsPlusAllowed | |
console.log(x) | |
if (allowed) scrollTo({ behavior, left, top }) | |
else console.log('[hackScrollTo] not allowed') | |
} | |
// @ts-ignore hackScrollTo has extra "allowed" property | |
window.scrollTo = hackScrollTo | |
console.log('[ScrollToHack] replaced window.scrollTo') | |
return () => { | |
window.scrollTo = scrollTo | |
} | |
}, []) | |
return null | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment