fix: pagination store popstate

This commit is contained in:
Torsten Dittmann committed 2022-10-11 18:36:28 +02:00
1 parent 1fb109108f
commit 05ea4f012a
1 file changed
+25 -3
+25 -3
View File
@@ -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<number>(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