Add perPage, initialPage

This commit is contained in:
Vadim
2021-01-21 19:56:57 +03:00
parent 59f118641c
commit 2dcbd79f2c
4 changed files with 59 additions and 64 deletions

View File

@@ -1,15 +1,11 @@
import { writable } from 'svelte/store';
import { v4 as uuid } from 'uuid'
import { getNextItemIndexFn, getPrevItemIndexFn } from './utils/item-index'
// TODO: try to split writable store items
// or try to use immer
const initState = {
items: [],
// currentItemId: null,
currentItemIndex: null,
action: 'next'
}
function createStore() {
@@ -19,17 +15,6 @@ function createStore() {
set(initState)
}
function setItem(id = uuid()) {
update(store => ({
...store,
// currentItemId: id, // TODO: seems is not used at all, can be removed
items: [
...store.items,
id
]
}))
}
function setCurrentItemIndex(index) {
update(store => ({
...store,
@@ -37,49 +22,44 @@ function createStore() {
}))
}
function removeItem(id) {
update(store => ({
...store,
items: store.items.filter(item => item !== id)
}))
}
function next({ infinite, perPage }) {
function moveToPage({ pageIndex, pagesCount }) {
update(store => {
const currentItemIndex = store.currentItemIndex // store.items.findIndex(item => item === store.currentItemId)
// console.log('next old currentItemIndex', currentItemIndex)
const newCurrentItemIndex = getNextItemIndexFn(infinite)(currentItemIndex, Math.ceil(store.items.length / perPage))
// console.log('newCurrentItemIndex', newCurrentItemIndex)
return {
...store,
// currentItemId: store.items[newCurrentItemIndex],
currentItemIndex: newCurrentItemIndex,
action: 'next'
currentItemIndex: pageIndex < 0 ? 0 : Math.min(pageIndex, pagesCount - 1),
}
})
}
function prev({ infinite, perPage }) {
function next({ infinite, pagesCount }) {
update(store => {
const currentItemIndex = store.currentItemIndex // store.items.findIndex(item => item === store.currentItemId)
const newCurrentItemIndex = getPrevItemIndexFn(infinite)(currentItemIndex, Math.ceil(store.items.length / perPage))
const currentItemIndex = store.currentItemIndex
const newCurrentItemIndex = getNextItemIndexFn(infinite)(currentItemIndex, pagesCount)
return {
...store,
currentItemIndex: newCurrentItemIndex,
}
})
}
function prev({ infinite, pagesCount }) {
update(store => {
const currentItemIndex = store.currentItemIndex
const newCurrentItemIndex = getPrevItemIndexFn(infinite)(currentItemIndex, pagesCount)
return {
...store,
// currentItemId: store.items[newCurrentItemIndex],
currentItemIndex: newCurrentItemIndex,
action: 'prev'
}
})
}
return {
subscribe,
setItem,
removeItem,
next,
prev,
setCurrentItemIndex,
reset
reset,
moveToPage,
};
}