UNPKG

svelte-ux

Version:

- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`

51 lines (50 loc) 2.02 kB
import { writable } from 'svelte/store'; export default function paginationStore(props) { var _a, _b, _c; const page = (_a = props === null || props === void 0 ? void 0 : props.page) !== null && _a !== void 0 ? _a : 1; const perPage = (_b = props === null || props === void 0 ? void 0 : props.perPage) !== null && _b !== void 0 ? _b : 25; const total = (_c = props === null || props === void 0 ? void 0 : props.total) !== null && _c !== void 0 ? _c : 0; const state = writable(createState(page, perPage, total)); return { subscribe: state.subscribe, nextPage() { state.update((state) => createState(state.page + 1, state.perPage, state.total)); }, prevPage() { state.update((state) => createState(state.page - 1, state.perPage, state.total)); }, firstPage() { state.update((state) => createState(1, state.perPage, state.total)); }, lastPage() { state.update((state) => createState(Math.ceil(state.total / state.perPage), state.perPage, state.total)); }, setPage(page) { state.update((state) => createState(page, state.perPage, state.total)); }, setPerPage(perPage) { state.update((state) => createState(state.page, perPage, state.total)); }, setTotal(total) { state.update((state) => createState(state.page, state.perPage, total)); }, }; } function createState(page, perPage, total) { const totalPages = Math.ceil(total / perPage); return { page, perPage, total, from: (page - 1) * perPage + 1, to: Math.min(total, page * perPage), totalPages, isFirst: page === 1, isLast: page === totalPages || totalPages === 0, hasPrevious: totalPages > 1 && page > 1, hasNext: page < totalPages, slice(items) { return items.slice((page - 1) * perPage, page * perPage); }, }; }