Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

feat(docs): remember scroll position on reload/back/forward

Greg Richardsonc8befe680388
diff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsx
index 229131db7da..1ddc56fd1fa 100644
--- a/apps/docs/pages/_app.tsx
+++ b/apps/docs/pages/_app.tsx
@@ -68,6 +68,42 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
}
}, [router, handlePageTelemetry])
+ /**
+ * Save/restore scroll position when reloading or navigating back/forward.
+ *
+ * Required since scroll happens within a sub-container, not the page root.
+ */
+ useEffect(() => {
+ const storageKey = 'scroll-position'
+
+ const container = document.getElementById('docs-content-container')
+ if (!container) {
+ return
+ }
+
+ const previousScroll = Number(sessionStorage.getItem(storageKey))
+ const [entry] = window.performance.getEntriesByType('navigation')
+
+ // Only restore scroll position on reload and back/forward events
+ if (
+ previousScroll &&
+ entry &&
+ isPerformanceNavigationTiming(entry) &&
+ ['reload', 'back_forward'].includes(entry.type)
+ ) {
+ container.scrollTop = previousScroll
+ }
+
+ const handler = () => {
+ // Scroll stored in session storage, so only persisted per tab
+ sessionStorage.setItem(storageKey, container.scrollTop.toString())
+ }
+
+ window.addEventListener('beforeunload', handler)
+
+ return () => window.removeEventListener('beforeunload', handler)
+ }, [router])
+
useEffect(() => {
/**
* Send page telemetry on first page load
@@ -124,4 +160,14 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {
)
}
+/**
+ * Type guard that checks if a performance entry is a
+ * `PerformanceNavigationTiming`.
+ */
+function isPerformanceNavigationTiming(
+ entry: PerformanceEntry
+): entry is PerformanceNavigationTiming {
+ return entry.entryType === 'navigation'
+}
+
export default MyApp