diff --git a/src/CarouselChild.svelte b/src/CarouselChild.svelte index d886f25..83af966 100644 --- a/src/CarouselChild.svelte +++ b/src/CarouselChild.svelte @@ -8,6 +8,9 @@ const id = generateId() onMount(() => { store.setItem(id) + return () => { + store.removeItem(id) + } }) diff --git a/src/ImageCarousel.svelte b/src/ImageCarousel.svelte index 89de19b..8cb6181 100644 --- a/src/ImageCarousel.svelte +++ b/src/ImageCarousel.svelte @@ -7,6 +7,11 @@ * Enable Next/Prev arrows */ export let arrows = true; + + /** + * Infinite looping + */ + export let infinite = true; let contentContainerElement let children @@ -15,10 +20,10 @@ }) function handlePrevClick() { - store.prev() + store.prev({ infinite }) } function handleNextClick() { - store.next() + store.next({ infinite }) } diff --git a/src/store.js b/src/store.js index 999ad90..fe22800 100644 --- a/src/store.js +++ b/src/store.js @@ -1,5 +1,5 @@ import { writable } from 'svelte/store'; - +import { getNextItemIndexFn, getPrevItemIndexFn } from './utils/item-index' function createStore() { const { subscribe, set, update } = writable({ @@ -18,13 +18,17 @@ function createStore() { })) } - function next() { - // TODO: move to utils functions and cover eoth tests + function removeItem(id) { + update(store => ({ + ...store, + items: store.items.filter(item => item !== id) + })) + } + + function next({ infinite }) { update(store => { const currentItemIndex = store.items.findIndex(item => item === store.currentItemId) - // TODO: infinite - // const newCurrentItemIndex = currentItemIndex + 1 > store.items.length - 1 ? 0 : currentItemIndex + 1 - const newCurrentItemIndex = Math.min(currentItemIndex + 1, store.items.length - 1) + const newCurrentItemIndex = getNextItemIndexFn(infinite)(currentItemIndex, store.items) return { ...store, currentItemId: store.items[newCurrentItemIndex] @@ -32,10 +36,10 @@ function createStore() { }) } - function prev() { + function prev({ infinite }) { update(store => { const currentItemIndex = store.items.findIndex(item => item === store.currentItemId) - const newCurrentItemIndex = Math.max(0, currentItemIndex - 1) + const newCurrentItemIndex = getPrevItemIndexFn(infinite)(currentItemIndex, store.items) return { ...store, currentItemId: store.items[newCurrentItemIndex] @@ -46,6 +50,7 @@ function createStore() { return { subscribe, setItem, + removeItem, next, prev }; diff --git a/src/stories/ImageCarouselView.svelte b/src/stories/ImageCarouselView.svelte index 232bea7..3d7b131 100644 --- a/src/stories/ImageCarouselView.svelte +++ b/src/stories/ImageCarouselView.svelte @@ -5,11 +5,19 @@ /** * Enable Next/Previos arrows */ - export let arrows = true; + export let arrows = true; + + /** + * Infinite looping + */ + export let infinite = true;