Skip to content

fix: add direction tracking to carousel component #1574

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
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
9 changes: 6 additions & 3 deletions src/lib/carousel/Carousel.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

const SLIDE_DURATION_RATIO = 0.25; // TODO: Expose one day?

let { children, slide, images, index = $bindable(0), slideDuration = 1000, transition, duration = 0, "aria-label": ariaLabel = "Draggable Carousel", disableSwipe = false, imgClass = "", class: className, onchange, divClass, ...restProps }: CarouselProps = $props();
let { children, thumbnail, slide, images, index = $bindable(0), slideDuration = 1000, transition, duration = 0, "aria-label": ariaLabel = "Draggable Carousel", disableSwipe = false, imgClass = "", class: className, onchange, divClass, ...restProps }: CarouselProps = $props();

const { set, subscribe, update } = writable<State>({ images, index: index ?? 0, forward: true, slideDuration, lastSlideChange: new Date() });

Expand Down Expand Up @@ -38,6 +38,7 @@

_state.index = _state.index >= images.length - 1 ? 0 : _state.index + 1;
_state.lastSlideChange = new Date();
_state.forward = true;
return { ..._state };
});
};
Expand All @@ -48,6 +49,7 @@

_state.index = _state.index <= 0 ? images.length - 1 : _state.index - 1;
_state.lastSlideChange = new Date();
_state.forward = false;
return { ..._state };
});
};
Expand All @@ -59,12 +61,12 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
let intervalId: any;

if (duration > 0) intervalId = setInterval(nextSlide, duration);
if (duration > 0) intervalId = setInterval(() => (forward ? nextSlide() : prevSlide()), duration);

return {
update: (duration: number) => {
clearInterval(intervalId);
if (duration > 0) intervalId = setInterval(nextSlide, duration);
if (duration > 0) intervalId = setInterval(() => (forward ? nextSlide() : prevSlide()), duration);
},
destroy: () => clearInterval(intervalId)
};
Expand Down Expand Up @@ -182,6 +184,7 @@
{@render children?.(index)}
</div>

{@render thumbnail?.()}
<!--
@component
[Go to docs](https://flowbite-svelte.com/)
Expand Down
16 changes: 15 additions & 1 deletion src/lib/carousel/Indicators.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,21 @@
<div class={base({ class: clsx(className) })} {...restProps}>
{#each $state.images as _, idx}
{@const selected = $state.index === idx}
<button onclick={() => ($state.index = idx)}>
<button
onclick={() => {
const len = $state.images.length;
const distance = (idx - $state.index + len) % len;
// Treat the shorter path as the intended direction; ties favour forward.
const isForward = distance !== 0 && distance <= len / 2;

state.update((_state) => {
_state.forward = isForward;
_state.index = idx;
_state.lastSlideChange = new Date();
return { ..._state };
});
}}
>
{#if children}
{@render children({ selected, index: idx })}
{:else}
Expand Down
42 changes: 30 additions & 12 deletions src/lib/carousel/Thumbnails.svelte
Original file line number Diff line number Diff line change
@@ -1,34 +1,53 @@
<script lang="ts">
import clsx from "clsx";
import { getContext } from "svelte";
import type { Writable } from "svelte/store";
import Thumbnail from "./Thumbnail.svelte";
import { thumbnails } from "./theme";
import type { ThumbnailsProps } from "$lib/types";
import type { State, ThumbnailsProps } from "$lib/types";

let { children, images = [], index = $bindable(), ariaLabel = "Click to view image", imgClass = "", throttleDelay = 650, class: className }: ThumbnailsProps = $props();
let { children, images, ariaLabel = "Click to view image", imgClass = "", throttleDelay = 650, class: className }: ThumbnailsProps = $props();

let lastClickedAt = new Date();

const state = getContext<Writable<State>>("state");

$effect(() => {
if (!images) {
images = $state.images;
}
});

const btnClick = (idx: number) => {
if (new Date().getTime() - lastClickedAt.getTime() < throttleDelay) {
console.warn("Thumbnail action throttled");
return;
}
if (idx === index) {

if (idx === $state.index) {
return;
}

index = idx;
const imageArray = images || $state.images;
const len = imageArray.length;
const distance = (idx - $state.index + len) % len; // 0‥len-1
// Treat the shorter path as the intended direction; ties favour forward.
const isForward = distance !== 0 && distance <= len / 2;

state.update((_state) => {
_state.forward = isForward;
_state.index = idx;
_state.lastSlideChange = new Date();
return { ..._state };
});

lastClickedAt = new Date();
};

$effect(() => {
index = (index + images.length) % images.length;
});
</script>

<div class={thumbnails({ class: clsx(className) })}>
{#each images as image, idx}
{@const selected = index === idx}
{#each images || $state.images as image, idx}
{@const selected = $state.index === idx}
<button onclick={() => btnClick(idx)} aria-label={ariaLabel}>
{#if children}
{@render children({ image, selected, imgClass, Thumbnail })}
Expand All @@ -46,8 +65,7 @@
[ThumbnailsProps](https://github.com/themesberg/flowbite-svelte/blob/main/src/lib/types.ts#L425)
## Props
@prop children
@prop images = []
@prop index = $bindable()
@prop images
@prop ariaLabel = "Click to view image"
@prop imgClass = ""
@prop throttleDelay = 650
Expand Down
4 changes: 2 additions & 2 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ export type State = {

export interface CarouselProps extends CarouselVariants, Omit<HTMLAttributes<HTMLDivElement>, "children" | "onchange"> {
children?: Snippet<[number]>;
thumbnail?: Snippet<[]>;
slide?: Snippet<[{ index: number; Slide: typeof Slide }]>;
images: HTMLImgAttributes[];
index?: number;
Expand Down Expand Up @@ -424,8 +425,7 @@ export interface ThumbnailProps extends HTMLImgAttributes {

export interface ThumbnailsProps extends Omit<HTMLAttributes<HTMLDivElement>, "children"> {
children?: Snippet<[{ image: HTMLImgAttributes; selected: boolean; imgClass: string; Thumbnail: Component }]>;
images: HTMLImgAttributes[];
index: number;
images?: HTMLImgAttributes[];
ariaLabel?: string;
imgClass?: string;
throttleDelay?: number;
Expand Down
1 change: 1 addition & 0 deletions src/routes/component-data/Carousel.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
},
"props": [
["children", ""],
["thumbnail", ""],
["slide", ""],
["images", ""],
["index", "$bindable(0)"],
Expand Down
18 changes: 11 additions & 7 deletions src/routes/docs/components/carousel.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ Show the carousel indicators by adding the internal `Indicators` component.

## Thumbnails

You can control the `Carousel` component externally by the `index` prop. Here is an example how to use the `Thumbnails` component to achieve that.
You can use the `Thumbnails` component as a child of the `Carousel` component to display thumbnail images. This component shares the same state store with the Carousel, so the thumbnails are always in sync with the current image.

```svelte example
<script lang="ts">
Expand All @@ -135,8 +135,10 @@ You can control the `Carousel` component externally by the `index` prop. Here is
<Carousel {images} bind:index>
<Controls />
<Indicators />
{#snippet thumbnail()}
<Thumbnails />
{/snippet}
</Carousel>
<Thumbnails {images} bind:index />
</div>
```

Expand Down Expand Up @@ -233,12 +235,14 @@ You can use `slide` snippet and internal component `Slide` to control the image
</Button>
{/snippet}
</Controls>
</Carousel>
<Thumbnails class="gap-3 bg-transparent" {images} bind:index>
{#snippet children({ image, selected, Thumbnail })}
<Thumbnail {selected} {...image} class="hover:outline-primary-500 rounded-md shadow-xl hover:outline {selected ? 'outline-primary-400 outline-4' : ''}" />
{#snippet thumbnail()}
<Thumbnails class="gap-3 bg-transparent">
{#snippet children({ image, selected, Thumbnail })}
<Thumbnail {selected} {...image} class="hover:outline-primary-500 rounded-md shadow-xl hover:outline {selected ? 'outline-primary-400 outline-4' : ''}" />
{/snippet}
</Thumbnails>
{/snippet}
</Thumbnails>
</Carousel>
</div>
```

Expand Down