From ce25bc8dc925422ca439a97bb2d518adbe2db929 Mon Sep 17 00:00:00 2001 From: Arman Date: Mon, 30 May 2022 14:00:30 +0200 Subject: [PATCH 1/2] fix: refactored pagination function --- src/lib/components/pagination.svelte | 39 +++++++++++++--------------- 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/lib/components/pagination.svelte b/src/lib/components/pagination.svelte index e38adcf1ad..b20e9f77ca 100644 --- a/src/lib/components/pagination.svelte +++ b/src/lib/components/pagination.svelte @@ -13,6 +13,7 @@ offset = limit * (page - 1); currentPage = page; dispatch('change'); + pages = pagination(currentPage, totalPages); } } @@ -21,36 +22,32 @@ currentPage += 1; offset = limit * (currentPage - 1); dispatch('change'); + pages = pagination(currentPage, totalPages); } else if (direction === 'prev' && currentPage > 1) { currentPage -= 1; offset = limit * (currentPage - 1); dispatch('change'); + pages = pagination(currentPage, totalPages); } } let pages = pagination(currentPage, totalPages); - function pagination(current: number, total: number) { - let delta = 2, - left = current - delta, - right = current + delta + 1, - range = [], - rangeWithDots = []; - - for (let i = 1; i <= total; i++) { - if (i == 1 || i == total || (i >= left && i < right)) { - range.push(i); - } - } - - rangeWithDots = range.reduce((prev, current, index) => { - if (current - prev[index - 1] > delta) { - prev.push('...'); - } - prev.push(current); - return prev; - }, []); - return rangeWithDots; + function pagination(page: number, total: number) { + const pagesShown = 5; + const start = Math.max( + 1, + Math.min(page - Math.floor((pagesShown - 3) / 2), total - pagesShown + 2) + ); + const end = Math.min( + total, + Math.max(page + Math.floor((pagesShown - 2) / 2), pagesShown - 1) + ); + return [ + ...(start > 2 ? [1, '...'] : start > 1 ? [1] : []), + ...Array.from({ length: end + 1 - start }, (_, i) => i + start), + ...(end < total - 1 ? ['...', total] : end < total ? [total] : []) + ]; } From 41fd2a8c0310b4fd384fc93fac4c7cf05034bf65 Mon Sep 17 00:00:00 2001 From: Arman Date: Mon, 30 May 2022 15:00:36 +0200 Subject: [PATCH 2/2] fix: now component visible when there aren't pages --- src/lib/components/pagination.svelte | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/lib/components/pagination.svelte b/src/lib/components/pagination.svelte index b20e9f77ca..6c894b5b9c 100644 --- a/src/lib/components/pagination.svelte +++ b/src/lib/components/pagination.svelte @@ -90,4 +90,22 @@