1
0
mirror of https://github.com/barthuijgen/factorio-sites.git synced 2024-11-24 08:52:36 +02:00

feat: attempt at preserve scroll functionality

This commit is contained in:
Bart 2021-04-25 23:07:50 +02:00 committed by Bart
parent 1df38cf52f
commit 6af3698389
3 changed files with 35 additions and 1 deletions

View File

@ -60,7 +60,7 @@ export const Header: React.FC = (props) => {
<MenuItem href="/user/blueprints">My blueprints</MenuItem>
<MenuItem href="/user/edit">Account</MenuItem>
<MenuItem href="/about">About</MenuItem>
<MenuItem href={`/api/logout?redirect=${router.pathname}`}>Logout</MenuItem>
<MenuItem href={`/api/logout?redirect=${router.asPath}`}>Logout</MenuItem>
</>
) : (
<>

View File

@ -10,6 +10,7 @@ import { Header } from "../components/Header";
import { AuthContext, AuthContextProps } from "../providers/auth";
import { useFetch } from "../hooks/fetch";
import { CF_WEB_ANALYTICS, PUBLIC_URL } from "../utils/env";
import { addPreserveScrollListeners } from "../utils/nextjs-preserve-scroll";
const globalStyles = css`
@font-face {
@ -66,6 +67,7 @@ if (typeof window !== "undefined") {
Router.events.on("routeChangeStart", () => NProgress.start());
Router.events.on("routeChangeComplete", () => NProgress.done());
Router.events.on("routeChangeError", () => NProgress.done());
addPreserveScrollListeners();
}
const BlueprintsApp = ({

View File

@ -0,0 +1,32 @@
import Router from "next/router";
export function addPreserveScrollListeners() {
if (typeof window === "undefined") return;
const _window = (window as unknown) as { _pop_state_pos: { x: number; y: number } | null };
const debug = process.env.NODE_ENV === "development";
Router.events.on("routeChangeStart", () => {
// Store scroll location in history on route changes
const pos = { x: window.pageXOffset, y: window.pageYOffset };
if (debug) console.log("store pos", pos, "in", window.history.state);
window.history.replaceState({ ...window.history.state, _pos: pos }, "");
});
Router.events.on("routeChangeComplete", () => {
// If a pop state (back navigation) happened, restore scroll position
if (_window._pop_state_pos) {
const pos = _window._pop_state_pos;
setTimeout(() => {
if (debug) console.log("popstate restore scrollTo", pos.x, pos.y);
window.scrollTo(pos.x, pos.y);
}, 50);
_window._pop_state_pos = null;
}
});
window.addEventListener("popstate", (event) => {
if (debug) console.log("popstate", event.state);
_window._pop_state_pos = event.state._pos || null;
});
}