Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions src/lib/components/Carousel.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
<script lang="ts">
let carousel: HTMLElement;

export let gap = 32;
let scroll = 0;
let touchStart = 0;
let touchEnd = 0;

function calculateScrollAmount(prev = false) {
const direction = prev ? -1 : 1;
const carouselSize = carousel?.clientWidth;
const childSize = (carousel.childNodes[0] as HTMLUListElement)?.clientWidth + gap;

scroll = scroll || carouselSize;

const numberOfItems = Math.floor(carouselSize / childSize);
const overflow = scroll % childSize;
const amount = numberOfItems * childSize - overflow * direction;
scroll += amount * direction;
return amount * direction;
}

function next() {
carousel.scrollBy({
left: calculateScrollAmount(),
behavior: 'smooth'
});
}
function prev() {
carousel.scrollBy({
left: calculateScrollAmount(true),
behavior: 'smooth'
});
}

function handleTouchStart(e: TouchEvent) {
touchStart = e.touches[0].clientX;
}
function handleTouchMove(e: TouchEvent) {
touchEnd = e.touches[0].clientX;
}

function handleTouchEnd() {
if (touchEnd > touchStart) {
prev();
} else {
next();
}
}
</script>

<div class="u-flex u-main-space-between u-flex-wrap">
<slot name="header" />
<div class="u-flex u-gap-12 u-cross-end u-margin-block-start-8">
<button class="aw-icon-button" aria-label="Move carousel backward" on:click={() => prev()}>
<span class="icon-arrow-left" aria-hidden="true" />
</button>
<button class="aw-icon-button" aria-label="Move carousel forward" on:click={() => next()}>
<span class="icon-arrow-right" aria-hidden="true" />
</button>
</div>
</div>
<ul
class="aw-grid-articles aw-u-gap-32 u-margin-block-start-32 carousel"
bind:this={carousel}
on:touchstart={handleTouchStart}
on:touchmove={handleTouchMove}
on:touchend={handleTouchEnd}
>
<slot />
</ul>

<style lang="scss">
.carousel {
grid-auto-flow: column;
grid-auto-columns: minmax(17.5rem, 1fr);
overflow-x: hidden;
}
</style>
1 change: 1 addition & 0 deletions src/lib/components/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ export { default as Newsletter } from './Newsletter.svelte';
export { default as Tooltip } from './Tooltip.svelte';
export { default as Spline } from './Spline.svelte';
export { default as Article } from './Article.svelte';
export { default as Carousel } from './Carousel.svelte';
Loading