Files
shared/packages/web-ui/src/lib/components/Pagination.svelte
T

100 lines
2.8 KiB
Svelte
Raw Normal View History

<script lang="ts">
import { ChevronFirst, ChevronLast, ChevronLeft, ChevronRight } from '@lucide/svelte';
const PAGE_SIZE_OPTIONS = [12, 24, 48, 96];
export type PaginationChange = {
page: number;
pageSize: number;
};
let {
page,
pageSize = 24,
pageLength = 0,
totalLength = 0,
onPaging
}: {
page: number;
pageSize?: number;
pageLength?: number;
totalLength?: number;
onPaging: (change: PaginationChange) => void;
} = $props();
const pageCount = $derived(Math.max(1, Math.ceil(totalLength / pageSize)));
const currentPage = $derived(Math.min(Math.max(1, page), pageCount));
const firstItemIndex = $derived(totalLength === 0 ? 0 : (currentPage - 1) * pageSize + 1);
const lastItemIndex = $derived(
totalLength === 0 ? 0 : Math.min(totalLength, (currentPage - 1) * pageSize + pageLength)
);
const hasPreviousPage = $derived(currentPage > 1);
const hasNextPage = $derived(currentPage < pageCount);
function goToPage(nextPage: number) {
onPaging({ page: Math.min(pageCount, Math.max(1, nextPage)), pageSize });
}
function changePageSize(event: Event) {
const nextPageSize = Number((event.currentTarget as HTMLSelectElement).value);
if (PAGE_SIZE_OPTIONS.includes(nextPageSize)) {
onPaging({ page: 1, pageSize: nextPageSize });
}
}
</script>
<nav class="sc-pagination" aria-label="Pagination">
<select
class="sc-pagination-page-size"
aria-label="Items per page"
value={String(pageSize)}
onchange={changePageSize}
>
{#each PAGE_SIZE_OPTIONS as option}
<option value={option}>{option}</option>
{/each}
</select>
<p class="sc-pagination-info">
{firstItemIndex.toLocaleString()}–{lastItemIndex.toLocaleString()} of {totalLength.toLocaleString()}
</p>
<div class="sc-pagination-controls">
<button
type="button"
class="sc-pagination-button"
aria-label="First page"
disabled={!hasPreviousPage}
onclick={() => goToPage(1)}
>
<ChevronFirst aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Previous page"
disabled={!hasPreviousPage}
onclick={() => goToPage(currentPage - 1)}
>
<ChevronLeft aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Next page"
disabled={!hasNextPage}
onclick={() => goToPage(currentPage + 1)}
>
<ChevronRight aria-hidden="true" size={16} />
</button>
<button
type="button"
class="sc-pagination-button"
aria-label="Last page"
disabled={!hasNextPage}
onclick={() => goToPage(pageCount)}
>
<ChevronLast aria-hidden="true" size={16} />
</button>
</div>
</nav>