From 05ea4f012af2d0ac01b6fd9a126c9ebd411d08e1 Mon Sep 17 00:00:00 2001 From: Torsten Dittmann Date: Tue, 11 Oct 2022 18:36:28 +0200 Subject: [PATCH] fix: pagination store popstate --- src/lib/stores/pagination.ts | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/src/lib/stores/pagination.ts b/src/lib/stores/pagination.ts index 9e4f8e751..13e9e3fd4 100644 --- a/src/lib/stores/pagination.ts +++ b/src/lib/stores/pagination.ts @@ -1,4 +1,4 @@ -import { goto } from '$app/navigation'; +import { afterNavigate, goto } from '$app/navigation'; import { page } from '$app/stores'; import { get, writable } from 'svelte/store'; @@ -8,14 +8,17 @@ export function createPersistenPagination(limit: number) { const offset = current * limit - limit; const { subscribe, set } = writable(offset < 0 ? 0 : offset); - subscribe((n) => { - const { pathname, searchParams } = get(page).url; + let keepHistory = false; + const apply = (n: number) => { + const { pathname, searchParams, href } = get(page).url; const newPage = n / limit + 1; + if (newPage > 1) { searchParams.set('page', newPage.toString()); } else { searchParams.delete('page'); } + let target = pathname; const hasParams = Array.from(searchParams.keys()).length > 0; @@ -24,11 +27,30 @@ export function createPersistenPagination(limit: number) { target += `?${searchParams.toString()}`; } + if (keepHistory) { + keepHistory = false; + return; + } + + if (href.endsWith(target)) { + return; + } + goto(target, { noscroll: true }); + }; + + afterNavigate(({ type, to }) => { + if (type === 'popstate') { + const target = +(to.url.searchParams.get('page') ?? 1); + keepHistory = true; + set(target * limit - limit); + } }); + subscribe(apply); + return { subscribe, set