# Carousel

Deretan slide berbasis CSS scroll snap dengan tombol sebelumnya dan berikutnya, titik opsional, dan navigasi panah. Tanpa autoplay.

- Kategori: Data
- Status: stable
- Registry: https://markas.jenderalcorp.com/r/carousel.json
- CLI: `npx markasui@latest add carousel`

## Kapan dipakai

Sekumpulan kecil item setara yang tidak perlu terlihat sekaligus, seperti langkah onboarding, testimoni, atau foto produk.

- Setiap slide harus satu elemen root
- Jangan taruh konten penting di carousel, karena banyak user tidak menggulir melewati slide pertama
- Pakai perView 2 atau 3 untuk kartu produk dan matikan showDots
- Jangan menambah autoplay

## Kode

### Blade

Simpan di `resources/views/components/markas/carousel.blade.php`. Dependensi: alpinejs.

```blade
@props([
    'label' => 'Carousel',
    'perView' => 1,
    'showDots' => false,
    'previousLabel' => 'Previous slide',
    'nextLabel' => 'Next slide',
    'slideLabel' => '{index} of {total}',
    'dotLabel' => 'Go to slide {index}',
])

@php
    $root = 'w-full';
    $viewport = 'relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden';
    $slideClass = 'min-w-0 shrink-0 snap-start';
    $perViews = [
        1 => 'basis-full',
        2 => 'basis-[calc((100%-1rem)/2)]',
        3 => 'basis-[calc((100%-2rem)/3)]',
    ];
    $controls = 'mt-3 flex items-center gap-2';
    $dots = 'flex items-center';
    $dot = 'group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary';
    $dotMark = 'h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none';
    $buttons = 'ml-auto flex items-center gap-2';
    $navButton = 'inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none';
    $icon = 'size-4';

    // Setiap named slot menjadi satu slide, sesuai urutan penulisan.
    $slides = array_values(array_filter(
        $__laravel_slots ?? [],
        fn ($value, $key) => $key !== '__default',
        ARRAY_FILTER_USE_BOTH,
    ));
    $total = count($slides);
    $format = fn (string $template, int $index) => str_replace(['{index}', '{total}'], [$index, $total], $template);
    // Same id on every render, so Livewire's morph (which matches elements by id) keeps the element. Pass `id` to set it.
    $idKey = 'markas-carousel|'.(isset($this) && $this instanceof \Livewire\Component ? $this->getId() : '').'|'.($attributes->get('wire:key') ?? $attributes->whereStartsWith('wire:model')->first() ?? $attributes->get('name')).'|';
    for ($idIndex = 0; $__env->hasRenderedOnce($idKey.$idIndex); $idIndex++);
    $__env->markAsRenderedOnce($idKey.$idIndex);
    $id = $attributes->get('id') ?? 'markas-carousel-'.hash('xxh32', $idKey.$idIndex);
    $viewportId = $id.'-viewport';
@endphp

<div
    x-data="{
        index: 0,
        atStart: true,
        atEnd: @js($total <= 1),
        {{-- Baca slide terdekat dan apakah viewport sudah di ujung kiri atau kanan. --}}
        sync() {
            const el = this.$refs.viewport;
            const items = Array.from(el.children);
            const left = el.scrollLeft;
            this.index = items.reduce((best, item, i) => Math.abs(item.offsetLeft - left) < Math.abs((items[best]?.offsetLeft ?? 0) - left) ? i : best, 0);
            this.atStart = left <= 1;
            this.atEnd = left + el.clientWidth >= el.scrollWidth - 1;
        },
        goTo(index) {
            const target = this.$refs.viewport.children[index];
            if (target) this.$refs.viewport.scrollTo({ left: target.offsetLeft });
        },
        step(direction) {
            const total = this.$refs.viewport.children.length;
            this.goTo(Math.min(Math.max(this.index + direction, 0), total - 1));
        },
    }"
    x-init="sync()"
    @keydown.right="if (! $event.defaultPrevented) { $event.preventDefault(); step(1); }"
    @keydown.left="if (! $event.defaultPrevented) { $event.preventDefault(); step(-1); }"
    {{ $attributes->merge(['id' => $id, 'role' => 'region', 'aria-roledescription' => 'carousel', 'aria-label' => $label])->class([$root]) }}
>
    <div x-ref="viewport" id="{{ $viewportId }}" tabindex="0" @scroll="sync()" class="{{ $viewport }}">
        @foreach ($slides as $index => $slide)
            <div role="group" aria-roledescription="slide" aria-label="{{ $format($slideLabel, $index + 1) }}" class="{{ $slideClass }} {{ $perViews[$perView] ?? $perViews[1] }}">{{ $slide }}</div>
        @endforeach
    </div>
    <div class="{{ $controls }}">
        @if ($showDots)
            <div class="{{ $dots }}">
                @foreach ($slides as $index => $slide)
                    <button
                        type="button"
                        aria-label="{{ $format($dotLabel, $index + 1) }}"
                        aria-controls="{{ $viewportId }}"
                        @if ($index === 0) aria-current="true" @endif
                        data-state="{{ $index === 0 ? 'active' : 'inactive' }}"
                        :aria-current="index === {{ $index }} ? 'true' : null"
                        :data-state="index === {{ $index }} ? 'active' : 'inactive'"
                        @click="goTo({{ $index }})"
                        class="{{ $dot }}"
                    ><span aria-hidden="true" class="{{ $dotMark }}"></span></button>
                @endforeach
            </div>
        @endif
        <div class="{{ $buttons }}">
            <button
                type="button"
                aria-label="{{ $previousLabel }}"
                aria-controls="{{ $viewportId }}"
                disabled
                :disabled="atStart"
                @click="step(-1)"
                class="{{ $navButton }}"
            >
                <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="m15 18-6-6 6-6" /></svg>
            </button>
            <button
                type="button"
                aria-label="{{ $nextLabel }}"
                aria-controls="{{ $viewportId }}"
                @if ($total <= 1) disabled @endif
                :disabled="atEnd"
                @click="step(1)"
                class="{{ $navButton }}"
            >
                <svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="{{ $icon }}"><path d="m9 18 6-6-6-6" /></svg>
            </button>
        </div>
    </div>
</div>
```

```blade
<x-markas.carousel
    label="Tur produk"
    show-dots
    previous-label="Slide sebelumnya"
    next-label="Slide berikutnya"
    slide-label="{index} dari {total}"
    dot-label="Ke slide {index}"
>
    <x-slot:rencana>
        <div class="h-40 rounded-xl bg-subtle p-5">Rencanakan minggu Anda</div>
    </x-slot:rencana>
    <x-slot:bagikan>
        <div class="h-40 rounded-xl bg-subtle p-5">Bagikan ke tim</div>
    </x-slot:bagikan>
</x-markas.carousel>
```

Butuh Alpine.js. Setiap named slot menjadi satu slide sesuai urutan penulisan. Untuk daftar, pakai `<x-slot :name="'slide-'.$index">` di dalam `@foreach`.

### React

Simpan di `src/components/markas/Carousel.tsx`. Tanpa dependensi tambahan.

```tsx
"use client";

import {
  Children,
  useCallback,
  useEffect,
  useId,
  useRef,
  useState,
  type ComponentProps,
  type KeyboardEvent,
} from "react";

const root = "w-full";
const viewport =
  "relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden";
const slideClass = "min-w-0 shrink-0 snap-start";
const perViews = {
  1: "basis-full",
  2: "basis-[calc((100%-1rem)/2)]",
  3: "basis-[calc((100%-2rem)/3)]",
};
const controls = "mt-3 flex items-center gap-2";
const dots = "flex items-center";
const dot =
  "group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const dotMark =
  "h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none";
const buttons = "ml-auto flex items-center gap-2";
const navButton =
  "inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const icon = "size-4";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

/** Isi placeholder {index} dan {total} pada label. */
export const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

type Position = { index: number; atStart: boolean; atEnd: boolean };

/** Baca slide terdekat dan apakah viewport sudah di ujung kiri atau kanan. */
function readPosition(viewportEl: HTMLElement): Position {
  const slides = Array.from(viewportEl.children) as HTMLElement[];
  const left = viewportEl.scrollLeft;
  const index = slides.reduce(
    (best, slide, i) =>
      Math.abs(slide.offsetLeft - left) <
      Math.abs((slides[best]?.offsetLeft ?? 0) - left)
        ? i
        : best,
    0,
  );
  return {
    index,
    atStart: left <= 1,
    atEnd: left + viewportEl.clientWidth >= viewportEl.scrollWidth - 1,
  };
}

export type CarouselProps = ComponentProps<"div"> & {
  label?: string;
  perView?: keyof typeof perViews;
  showDots?: boolean;
  previousLabel?: string;
  nextLabel?: string;
  slideLabel?: string;
  dotLabel?: string;
};

export function Carousel({
  label = "Carousel",
  perView = 1,
  showDots = false,
  previousLabel = "Previous slide",
  nextLabel = "Next slide",
  slideLabel = "{index} of {total}",
  dotLabel = "Go to slide {index}",
  id,
  className,
  children,
  onKeyDown,
  ...props
}: CarouselProps) {
  const generatedId = useId();
  const carouselId = id ?? generatedId;
  const viewportId = `${carouselId}-viewport`;
  const slides = Children.toArray(children);
  const total = slides.length;
  const viewportRef = useRef<HTMLDivElement>(null);
  const [position, setPosition] = useState<Position>({
    index: 0,
    atStart: true,
    atEnd: total <= 1,
  });

  const sync = useCallback(() => {
    if (viewportRef.current) setPosition(readPosition(viewportRef.current));
  }, []);

  useEffect(sync, [sync, total]);

  const goTo = (index: number) => {
    const viewportEl = viewportRef.current;
    const target = viewportEl?.children[index] as HTMLElement | undefined;
    if (viewportEl && target) viewportEl.scrollTo({ left: target.offsetLeft });
  };
  const step = (direction: 1 | -1) =>
    goTo(Math.min(Math.max(position.index + direction, 0), total - 1));

  const handleKeyDown = (event: KeyboardEvent<HTMLDivElement>) => {
    onKeyDown?.(event);
    const directions: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const direction = directions[event.key];
    if (direction === undefined || event.defaultPrevented) return;
    event.preventDefault();
    step(direction);
  };

  return (
    <div
      id={carouselId}
      role="region"
      aria-roledescription="carousel"
      aria-label={label}
      className={cx(root, className)}
      onKeyDown={handleKeyDown}
      {...props}
    >
      <div
        ref={viewportRef}
        id={viewportId}
        tabIndex={0}
        className={viewport}
        onScroll={sync}
      >
        {slides.map((slide, index) => (
          <div
            key={index}
            role="group"
            aria-roledescription="slide"
            aria-label={formatLabel(slideLabel, index + 1, total)}
            className={cx(slideClass, perViews[perView])}
          >
            {slide}
          </div>
        ))}
      </div>
      <div className={controls}>
        {showDots && (
          <div className={dots}>
            {slides.map((_, index) => (
              <button
                key={index}
                type="button"
                aria-label={formatLabel(dotLabel, index + 1, total)}
                aria-controls={viewportId}
                aria-current={index === position.index ? "true" : undefined}
                data-state={index === position.index ? "active" : "inactive"}
                className={dot}
                onClick={() => goTo(index)}
              >
                <span aria-hidden="true" className={dotMark} />
              </button>
            ))}
          </div>
        )}
        <div className={buttons}>
          <button
            type="button"
            aria-label={previousLabel}
            aria-controls={viewportId}
            disabled={position.atStart}
            className={navButton}
            onClick={() => step(-1)}
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              className={icon}
            >
              <path d="m15 18-6-6 6-6" />
            </svg>
          </button>
          <button
            type="button"
            aria-label={nextLabel}
            aria-controls={viewportId}
            disabled={position.atEnd}
            className={navButton}
            onClick={() => step(1)}
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              strokeWidth="1.5"
              strokeLinecap="round"
              strokeLinejoin="round"
              className={icon}
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}
```

```tsx
import { Carousel } from "@/components/markas/Carousel";

<Carousel
  label="Tur produk"
  showDots
  previousLabel="Slide sebelumnya"
  nextLabel="Slide berikutnya"
  slideLabel="{index} dari {total}"
  dotLabel="Ke slide {index}"
>
  <div className="h-40 rounded-xl bg-subtle p-5">Rencanakan minggu Anda</div>
  <div className="h-40 rounded-xl bg-subtle p-5">Bagikan ke tim</div>
</Carousel>;
```

### Vue

Simpan di `src/components/markas/Carousel.vue`. Tanpa dependensi tambahan.

```vue
<script setup lang="ts">
import {
  Comment,
  Fragment,
  Text,
  computed,
  onMounted,
  reactive,
  useId,
  useSlots,
  useTemplateRef,
  type VNode,
} from "vue";

const props = withDefaults(
  defineProps<{
    label?: string;
    perView?: 1 | 2 | 3;
    showDots?: boolean;
    previousLabel?: string;
    nextLabel?: string;
    slideLabel?: string;
    dotLabel?: string;
    id?: string;
  }>(),
  {
    label: "Carousel",
    perView: 1,
    showDots: false,
    previousLabel: "Previous slide",
    nextLabel: "Next slide",
    slideLabel: "{index} of {total}",
    dotLabel: "Go to slide {index}",
    id: undefined,
  },
);

const root = "w-full";
const viewport =
  "relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden";
const slideClass = "min-w-0 shrink-0 snap-start";
const perViews = {
  1: "basis-full",
  2: "basis-[calc((100%-1rem)/2)]",
  3: "basis-[calc((100%-2rem)/3)]",
};
const controls = "mt-3 flex items-center gap-2";
const dots = "flex items-center";
const dot =
  "group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const dotMark =
  "h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none";
const buttons = "ml-auto flex items-center gap-2";
const navButton =
  "inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const icon = "size-4";

const slots = useSlots();
const generatedId = useId();
const carouselId = computed(() => props.id ?? generatedId);
const viewportId = computed(() => `${carouselId.value}-viewport`);
const viewportEl = useTemplateRef<HTMLDivElement>("viewportRef");

/** Ratakan Fragment (v-for) dan buang komentar atau spasi kosong supaya tiap elemen menjadi satu slide. */
function flatten(nodes: VNode[]): VNode[] {
  return nodes.flatMap((node) => {
    if (node.type === Fragment) return flatten(node.children as VNode[]);
    if (node.type === Comment) return [];
    if (node.type === Text && String(node.children).trim() === "") return [];
    return [node];
  });
}

const slides = (): VNode[] => flatten(slots.default?.() ?? []);

const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

const position = reactive({ index: 0, atStart: true, atEnd: false });

/** Baca slide terdekat dan apakah viewport sudah di ujung kiri atau kanan. */
function sync() {
  const el = viewportEl.value;
  if (!el) return;
  const items = Array.from(el.children) as HTMLElement[];
  const left = el.scrollLeft;
  position.index = items.reduce(
    (best, item, i) =>
      Math.abs(item.offsetLeft - left) <
      Math.abs((items[best]?.offsetLeft ?? 0) - left)
        ? i
        : best,
    0,
  );
  position.atStart = left <= 1;
  position.atEnd = left + el.clientWidth >= el.scrollWidth - 1;
}

function goTo(index: number) {
  const el = viewportEl.value;
  const target = el?.children[index] as HTMLElement | undefined;
  if (el && target) el.scrollTo({ left: target.offsetLeft });
}

function step(direction: 1 | -1, total: number) {
  goTo(Math.min(Math.max(position.index + direction, 0), total - 1));
}

function onKeydown(event: KeyboardEvent) {
  const directions: Record<string, 1 | -1 | undefined> = {
    ArrowRight: 1,
    ArrowLeft: -1,
  };
  const direction = directions[event.key];
  if (direction === undefined || event.defaultPrevented) return;
  event.preventDefault();
  step(direction, viewportEl.value?.children.length ?? 0);
}

position.atEnd = slides().length <= 1;
onMounted(sync);
</script>

<template>
  <div
    :id="carouselId"
    role="region"
    aria-roledescription="carousel"
    :aria-label="props.label"
    :class="root"
    @keydown="onKeydown"
  >
    <div
      :id="viewportId"
      ref="viewportRef"
      tabindex="0"
      :class="viewport"
      @scroll="sync"
    >
      <div
        v-for="(slide, index) in slides()"
        :key="index"
        role="group"
        aria-roledescription="slide"
        :aria-label="formatLabel(props.slideLabel, index + 1, slides().length)"
        :class="[slideClass, perViews[props.perView]]"
      >
        <component :is="slide" />
      </div>
    </div>
    <div :class="controls">
      <div v-if="props.showDots" :class="dots">
        <button
          v-for="(_, index) in slides()"
          :key="index"
          type="button"
          :aria-label="formatLabel(props.dotLabel, index + 1, slides().length)"
          :aria-controls="viewportId"
          :aria-current="index === position.index ? 'true' : undefined"
          :data-state="index === position.index ? 'active' : 'inactive'"
          :class="dot"
          @click="goTo(index)"
        >
          <span aria-hidden="true" :class="dotMark" />
        </button>
      </div>
      <div :class="buttons">
        <button
          type="button"
          :aria-label="props.previousLabel"
          :aria-controls="viewportId"
          :disabled="position.atStart"
          :class="navButton"
          @click="step(-1, slides().length)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            :class="icon"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
        </button>
        <button
          type="button"
          :aria-label="props.nextLabel"
          :aria-controls="viewportId"
          :disabled="position.atEnd"
          :class="navButton"
          @click="step(1, slides().length)"
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            :class="icon"
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </button>
      </div>
    </div>
  </div>
</template>
```

```vue
<template>
  <Carousel
    label="Tur produk"
    show-dots
    previous-label="Slide sebelumnya"
    next-label="Slide berikutnya"
    slide-label="{index} dari {total}"
    dot-label="Ke slide {index}"
  >
    <div class="h-40 rounded-xl bg-subtle p-5">Rencanakan minggu Anda</div>
    <div class="h-40 rounded-xl bg-subtle p-5">Bagikan ke tim</div>
  </Carousel>
</template>
```

### Svelte

Simpan di `src/lib/components/markas/Carousel.svelte`. Tanpa dependensi tambahan.

```svelte
<script lang="ts" module>
  /** Fill the {index} and {total} placeholders in a label. */
  export const formatLabel = (template: string, index: number, total: number) =>
    template
      .replaceAll("{index}", String(index))
      .replaceAll("{total}", String(total));
</script>

<script lang="ts" generics="T">
  import type { Snippet } from "svelte";
  import type { HTMLAttributes } from "svelte/elements";

  const root = "w-full";
  const viewport =
    "relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden";
  const slideClass = "min-w-0 shrink-0 snap-start";
  const perViews = {
    1: "basis-full",
    2: "basis-[calc((100%-1rem)/2)]",
    3: "basis-[calc((100%-2rem)/3)]",
  };
  const controls = "mt-3 flex items-center gap-2";
  const dots = "flex items-center";
  const dot =
    "group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
  const dotMark =
    "h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none";
  const buttons = "ml-auto flex items-center gap-2";
  const navButton =
    "inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
  const icon = "size-4";

  type Props = Omit<HTMLAttributes<HTMLDivElement>, "children"> & {
    /** One slide per item, rendered by the slide snippet. */
    items: T[];
    slide: Snippet<[T, number]>;
    label?: string;
    perView?: keyof typeof perViews;
    showDots?: boolean;
    previousLabel?: string;
    nextLabel?: string;
    slideLabel?: string;
    dotLabel?: string;
  };

  let {
    items,
    slide,
    label = "Carousel",
    perView = 1,
    showDots = false,
    previousLabel = "Previous slide",
    nextLabel = "Next slide",
    slideLabel = "{index} of {total}",
    dotLabel = "Go to slide {index}",
    id,
    class: className,
    onkeydown,
    ...rest
  }: Props = $props();

  const generatedId = $props.id();
  const carouselId = $derived(id ?? generatedId);
  const viewportId = $derived(`${carouselId}-viewport`);
  const total = $derived(items.length);
  let viewportEl = $state<HTMLDivElement>();
  let index = $state(0);
  let atStart = $state(true);
  // svelte-ignore state_referenced_locally
  let atEnd = $state(items.length <= 1);

  /** Read the nearest slide and whether the viewport is at its left or right edge. */
  function sync() {
    const el = viewportEl;
    if (!el) return;
    const slides = Array.from(el.children) as HTMLElement[];
    const left = el.scrollLeft;
    index = slides.reduce(
      (best, item, i) =>
        Math.abs(item.offsetLeft - left) <
        Math.abs((slides[best]?.offsetLeft ?? 0) - left)
          ? i
          : best,
      0,
    );
    atStart = left <= 1;
    atEnd = left + el.clientWidth >= el.scrollWidth - 1;
  }

  $effect(() => {
    void total;
    sync();
  });

  function goTo(target: number) {
    const el = viewportEl;
    const slideEl = el?.children[target] as HTMLElement | undefined;
    if (el && slideEl) el.scrollTo({ left: slideEl.offsetLeft });
  }

  const step = (direction: 1 | -1) =>
    goTo(Math.min(Math.max(index + direction, 0), total - 1));

  function handleKeydown(
    event: KeyboardEvent & { currentTarget: HTMLDivElement },
  ) {
    onkeydown?.(event);
    const directions: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const direction = directions[event.key];
    if (direction === undefined || event.defaultPrevented) return;
    event.preventDefault();
    step(direction);
  }
</script>

<div
  id={carouselId}
  role="region"
  aria-roledescription="carousel"
  aria-label={label}
  class={[root, className]}
  onkeydown={handleKeydown}
  {...rest}
>
  <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
  <div
    bind:this={viewportEl}
    id={viewportId}
    tabindex="0"
    class={viewport}
    onscroll={sync}
  >
    {#each items as item, i (i)}
      <div
        role="group"
        aria-roledescription="slide"
        aria-label={formatLabel(slideLabel, i + 1, total)}
        class={[slideClass, perViews[perView]]}
      >
        {@render slide(item, i)}
      </div>
    {/each}
  </div>
  <div class={controls}>
    {#if showDots}
      <div class={dots}>
        {#each items as _, i (i)}
          <button
            type="button"
            aria-label={formatLabel(dotLabel, i + 1, total)}
            aria-controls={viewportId}
            aria-current={i === index ? "true" : undefined}
            data-state={i === index ? "active" : "inactive"}
            class={dot}
            onclick={() => goTo(i)}
          >
            <span aria-hidden="true" class={dotMark}></span>
          </button>
        {/each}
      </div>
    {/if}
    <div class={buttons}>
      <button
        type="button"
        aria-label={previousLabel}
        aria-controls={viewportId}
        disabled={atStart}
        class={navButton}
        onclick={() => step(-1)}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path d="m15 18-6-6 6-6" />
        </svg>
      </button>
      <button
        type="button"
        aria-label={nextLabel}
        aria-controls={viewportId}
        disabled={atEnd}
        class={navButton}
        onclick={() => step(1)}
      >
        <svg
          aria-hidden="true"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="1.5"
          stroke-linecap="round"
          stroke-linejoin="round"
          class={icon}
        >
          <path d="m9 18 6-6-6-6" />
        </svg>
      </button>
    </div>
  </div>
</div>
```

```svelte
<script lang="ts">
  import Carousel from "$lib/components/markas/Carousel.svelte";

  const slides = ["Plan your week", "Share with your team", "Track progress"];
</script>

<Carousel label="Product tour" showDots items={slides}>
  {#snippet slide(title, index)}
    <div class="h-40 rounded-xl bg-subtle p-5">{index + 1}. {title}</div>
  {/snippet}
</Carousel>
```

Svelte, Astro, dan Angular menerima slide sebagai `items` dan merender tiap item lewat snippet, function child, atau `ng-template`. Svelte membaca `{index}` di atribut biasa sebagai ekspresi, jadi tulis template label di dalam kurung kurawal: `slideLabel={"Slide {index} dari {total}"}`.

### Astro

Simpan di `src/components/markas/Carousel.astro`. Tanpa dependensi tambahan.

```astro
---
import type { HTMLAttributes } from "astro/types";

const root = "w-full";
const viewport =
  "relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden";
const slideClass = "min-w-0 shrink-0 snap-start";
const perViews = {
  1: "basis-full",
  2: "basis-[calc((100%-1rem)/2)]",
  3: "basis-[calc((100%-2rem)/3)]",
};
const controls = "mt-3 flex items-center gap-2";
const dots = "flex items-center";
const dot =
  "group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const dotMark =
  "h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none";
const buttons = "ml-auto flex items-center gap-2";
const navButton =
  "inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const icon = "size-4";

type Props = HTMLAttributes<"div"> & {
  /** One slide per item, rendered by the function child: (item, index) => markup. */
  items: unknown[];
  label?: string;
  perView?: keyof typeof perViews;
  showDots?: boolean;
  previousLabel?: string;
  nextLabel?: string;
  slideLabel?: string;
  dotLabel?: string;
};

const {
  items,
  label = "Carousel",
  perView = 1,
  showDots = false,
  previousLabel = "Previous slide",
  nextLabel = "Next slide",
  slideLabel = "{index} of {total}",
  dotLabel = "Go to slide {index}",
  id,
  class: className,
  ...rest
} = Astro.props;

/** Fill the {index} and {total} placeholders in a label. */
const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

const carouselId = id ?? `markas-carousel-${crypto.randomUUID().slice(0, 8)}`;
const viewportId = `${carouselId}-viewport`;
const total = items.length;
const slides = await Promise.all(
  items.map((item, index) => Astro.slots.render("default", [item, index])),
);
---

<markas-carousel class="contents">
  <div
    id={carouselId}
    role="region"
    aria-roledescription="carousel"
    aria-label={label}
    class:list={[root, className]}
    {...rest}
  >
    <div id={viewportId} tabindex="0" class={viewport} data-viewport>
      {
        slides.map((html, index) => (
          <div
            role="group"
            aria-roledescription="slide"
            aria-label={formatLabel(slideLabel, index + 1, total)}
            class:list={[slideClass, perViews[perView]]}
            set:html={html}
          />
        ))
      }
    </div>
    <div class={controls}>
      {
        showDots && (
          <div class={dots}>
            {slides.map((_, index) => (
              <button
                type="button"
                aria-label={formatLabel(dotLabel, index + 1, total)}
                aria-controls={viewportId}
                aria-current={index === 0 ? "true" : undefined}
                data-state={index === 0 ? "active" : "inactive"}
                data-dot={index}
                class={dot}
              >
                <span aria-hidden="true" class={dotMark} />
              </button>
            ))}
          </div>
        )
      }
      <div class={buttons}>
        <button
          type="button"
          aria-label={previousLabel}
          aria-controls={viewportId}
          disabled
          data-step="-1"
          class={navButton}
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            class={icon}
          >
            <path d="m15 18-6-6 6-6"></path>
          </svg>
        </button>
        <button
          type="button"
          aria-label={nextLabel}
          aria-controls={viewportId}
          disabled={total <= 1}
          data-step="1"
          class={navButton}
        >
          <svg
            aria-hidden="true"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            class={icon}
          >
            <path d="m9 18 6-6-6-6"></path>
          </svg>
        </button>
      </div>
    </div>
  </div>
</markas-carousel>

<script>
  // Each carousel keeps its own position, so it is a custom element: it also works for
  // markup added later and for pages reached through view transitions.
  class MarkasCarousel extends HTMLElement {
    private index = 0;
    private ready = false;

    connectedCallback() {
      if (this.ready) return;
      this.ready = true;
      const viewport = this.querySelector<HTMLElement>("[data-viewport]");
      if (!viewport) return;
      viewport.addEventListener("scroll", () => this.sync(viewport));
      this.addEventListener("click", (event) => {
        const button = (event.target as Element).closest<HTMLElement>(
          "[data-dot], [data-step]",
        );
        if (button?.dataset.dot !== undefined)
          this.goTo(viewport, Number(button.dataset.dot));
        else if (button?.dataset.step !== undefined)
          this.step(viewport, Number(button.dataset.step));
      });
      this.addEventListener("keydown", (event) => {
        const directions: Record<string, number | undefined> = {
          ArrowRight: 1,
          ArrowLeft: -1,
        };
        const direction = directions[event.key];
        if (direction === undefined || event.defaultPrevented) return;
        event.preventDefault();
        this.step(viewport, direction);
      });
      this.sync(viewport);
    }

    /** Read the nearest slide and whether the viewport is at its left or right edge. */
    private sync(viewport: HTMLElement) {
      const slides = Array.from(viewport.children) as HTMLElement[];
      const left = viewport.scrollLeft;
      this.index = slides.reduce(
        (best, slide, i) =>
          Math.abs(slide.offsetLeft - left) <
          Math.abs((slides[best]?.offsetLeft ?? 0) - left)
            ? i
            : best,
        0,
      );
      this.querySelectorAll<HTMLElement>("[data-dot]").forEach((dot) => {
        const active = Number(dot.dataset.dot) === this.index;
        dot.dataset.state = active ? "active" : "inactive";
        if (active) dot.setAttribute("aria-current", "true");
        else dot.removeAttribute("aria-current");
      });
      const atStart = left <= 1;
      const atEnd = left + viewport.clientWidth >= viewport.scrollWidth - 1;
      this.querySelectorAll<HTMLButtonElement>("[data-step]").forEach(
        (button) => {
          button.disabled = button.dataset.step === "-1" ? atStart : atEnd;
        },
      );
    }

    private goTo(viewport: HTMLElement, index: number) {
      const target = viewport.children[index] as HTMLElement | undefined;
      if (target) viewport.scrollTo({ left: target.offsetLeft });
    }

    private step(viewport: HTMLElement, direction: number) {
      const last = viewport.children.length - 1;
      this.goTo(viewport, Math.min(Math.max(this.index + direction, 0), last));
    }
  }

  if (!customElements.get("markas-carousel"))
    customElements.define("markas-carousel", MarkasCarousel);
</script>
```

```astro
---
import Carousel from "@/components/markas/Carousel.astro";

const slides = ["Plan your week", "Share with your team", "Track progress"];
---

<Carousel label="Product tour" showDots items={slides}>
  {
    (title: string, index: number) => (
      <div class="h-40 rounded-xl bg-subtle p-5">{index + 1}. {title}</div>
    )
  }
</Carousel>
```

Setiap carousel adalah custom element kecil, jadi tetap jalan setelah view transition.

### Angular

Simpan di `src/app/markas/carousel.component.ts`. Tanpa dependensi tambahan.

```ts
import { NgTemplateOutlet } from "@angular/common";
import {
  afterNextRender,
  booleanAttribute,
  ChangeDetectionStrategy,
  Component,
  computed,
  contentChild,
  type ElementRef,
  input,
  signal,
  TemplateRef,
  viewChild,
} from "@angular/core";

const root = "w-full";
const viewport =
  "relative flex snap-x snap-mandatory gap-4 overflow-x-auto scroll-smooth rounded-xl [scrollbar-width:none] focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary motion-reduce:scroll-auto [&::-webkit-scrollbar]:hidden";
const slideClass = "min-w-0 shrink-0 snap-start";
const perViews = {
  1: "basis-full",
  2: "basis-[calc((100%-1rem)/2)]",
  3: "basis-[calc((100%-2rem)/3)]",
};
const controls = "mt-3 flex items-center gap-2";
const dots = "flex items-center";
const dot =
  "group inline-flex h-6 min-w-6 items-center justify-center rounded-full focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary";
const dotMark =
  "h-2 w-2 rounded-full bg-faint transition-all duration-150 ease-out group-data-[state=active]:w-4 group-data-[state=active]:bg-primary motion-reduce:transition-none";
const buttons = "ml-auto flex items-center gap-2";
const navButton =
  "inline-flex size-8 items-center justify-center rounded-md border border-line bg-surface text-ink transition-colors duration-150 ease-out hover:bg-subtle focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:pointer-events-none disabled:opacity-50 motion-reduce:transition-none";
const icon = "size-4";

/** Fill the {index} and {total} placeholders in a label. */
export const formatLabel = (template: string, index: number, total: number) =>
  template
    .replaceAll("{index}", String(index))
    .replaceAll("{total}", String(total));

export type CarouselSlideContext<T> = { $implicit: T; index: number };

let nextId = 0;

/**
 * One slide per item, rendered by the projected `<ng-template let-item let-index="index">`.
 * Host stays out of layout; id and class move to the region.
 */
@Component({
  selector: "markas-carousel",
  changeDetection: ChangeDetectionStrategy.OnPush,
  imports: [NgTemplateOutlet],
  host: { class: "contents", "[attr.id]": "null" },
  template: `
    <div
      [id]="carouselId()"
      role="region"
      aria-roledescription="carousel"
      [attr.aria-label]="label()"
      [class]="rootClass()"
      (keydown)="handleKeydown($event)"
    >
      <div
        #viewportEl
        [id]="viewportId()"
        tabindex="0"
        [class]="viewport"
        (scroll)="sync()"
      >
        @for (item of items(); track $index) {
          <div
            role="group"
            aria-roledescription="slide"
            [attr.aria-label]="format(slideLabel(), $index + 1)"
            [class]="slideClasses()"
          >
            @if (slide(); as template) {
              <ng-container
                [ngTemplateOutlet]="template"
                [ngTemplateOutletContext]="{ $implicit: item, index: $index }"
              />
            }
          </div>
        }
      </div>
      <div [class]="controls">
        @if (showDots()) {
          <div [class]="dots">
            @for (item of items(); track $index) {
              <button
                type="button"
                [attr.aria-label]="format(dotLabel(), $index + 1)"
                [attr.aria-controls]="viewportId()"
                [attr.aria-current]="$index === index() ? 'true' : null"
                [attr.data-state]="$index === index() ? 'active' : 'inactive'"
                [class]="dot"
                (click)="goTo($index)"
              >
                <span aria-hidden="true" [class]="dotMark"></span>
              </button>
            }
          </div>
        }
        <div [class]="buttons">
          <button
            type="button"
            [attr.aria-label]="previousLabel()"
            [attr.aria-controls]="viewportId()"
            [disabled]="atStart()"
            [class]="navButton"
            (click)="step(-1)"
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              [attr.class]="icon"
            >
              <path d="m15 18-6-6 6-6" />
            </svg>
          </button>
          <button
            type="button"
            [attr.aria-label]="nextLabel()"
            [attr.aria-controls]="viewportId()"
            [disabled]="atEnd()"
            [class]="navButton"
            (click)="step(1)"
          >
            <svg
              aria-hidden="true"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="1.5"
              stroke-linecap="round"
              stroke-linejoin="round"
              [attr.class]="icon"
            >
              <path d="m9 18 6-6-6-6" />
            </svg>
          </button>
        </div>
      </div>
    </div>
  `,
})
export class Carousel<T = unknown> {
  readonly items = input.required<T[]>();
  readonly label = input("Carousel");
  readonly perView = input<keyof typeof perViews>(1);
  readonly showDots = input(false, { transform: booleanAttribute });
  readonly previousLabel = input("Previous slide");
  readonly nextLabel = input("Next slide");
  readonly slideLabel = input("{index} of {total}");
  readonly dotLabel = input("Go to slide {index}");
  readonly id = input<string>();
  readonly userClass = input("", { alias: "class" });

  protected readonly slide =
    contentChild<TemplateRef<CarouselSlideContext<T>>>(TemplateRef);
  protected readonly viewport = viewport;
  protected readonly controls = controls;
  protected readonly dots = dots;
  protected readonly dot = dot;
  protected readonly dotMark = dotMark;
  protected readonly buttons = buttons;
  protected readonly navButton = navButton;
  protected readonly icon = icon;
  protected readonly index = signal(0);
  protected readonly atStart = signal(true);
  protected readonly atEnd = signal(false);
  private readonly generatedId = `markas-carousel-${nextId++}`;
  protected readonly carouselId = computed(() => this.id() ?? this.generatedId);
  protected readonly viewportId = computed(
    () => `${this.carouselId()}-viewport`,
  );
  protected readonly rootClass = computed(() =>
    [root, this.userClass()].filter(Boolean).join(" "),
  );
  protected readonly slideClasses = computed(
    () => `${slideClass} ${perViews[this.perView()]}`,
  );
  private readonly viewportRef =
    viewChild.required<ElementRef<HTMLDivElement>>("viewportEl");

  constructor() {
    afterNextRender(() => this.sync());
  }

  protected format(template: string, index: number) {
    return formatLabel(template, index, this.items().length);
  }

  /** Read the nearest slide and whether the viewport is at its left or right edge. */
  protected sync() {
    const el = this.viewportRef().nativeElement;
    const slides = Array.from(el.children) as HTMLElement[];
    const left = el.scrollLeft;
    this.index.set(
      slides.reduce(
        (best, item, i) =>
          Math.abs(item.offsetLeft - left) <
          Math.abs((slides[best]?.offsetLeft ?? 0) - left)
            ? i
            : best,
        0,
      ),
    );
    this.atStart.set(left <= 1);
    this.atEnd.set(left + el.clientWidth >= el.scrollWidth - 1);
  }

  /** Scrolls to a slide. Also callable from a template reference: carousel.goTo(2). */
  goTo(index: number) {
    const el = this.viewportRef().nativeElement;
    const target = el.children[index] as HTMLElement | undefined;
    if (target) el.scrollTo({ left: target.offsetLeft });
  }

  protected step(direction: 1 | -1) {
    this.goTo(
      Math.min(Math.max(this.index() + direction, 0), this.items().length - 1),
    );
  }

  protected handleKeydown(event: KeyboardEvent) {
    const directions: Record<string, 1 | -1 | undefined> = {
      ArrowRight: 1,
      ArrowLeft: -1,
    };
    const direction = directions[event.key];
    if (direction === undefined || event.defaultPrevented) return;
    event.preventDefault();
    this.step(direction);
  }
}
```

```ts
import { Component } from "@angular/core";
import { Carousel } from "./markas/carousel.component";

@Component({
  selector: "app-example",
  imports: [Carousel],
  template: `
    <markas-carousel label="Product tour" showDots [items]="slides">
      <ng-template let-title let-index="index">
        <div class="h-40 rounded-xl bg-subtle p-5">
          {{ index + 1 }}. {{ title }}
        </div>
      </ng-template>
    </markas-carousel>
  `,
})
export class Example {
  slides = ["Plan your week", "Share with your team", "Track progress"];
}
```

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `slides` | `Blade: named slots · React: children · Vue: default slot · Svelte, Astro, Angular: items` | - | Setiap named slot (Blade) atau setiap elemen anak (React dan Vue) menjadi satu slide, sesuai urutan. Svelte, Astro, dan Angular merender satu slide per entri items. |
| `items` | `T[]` | - | Khusus Svelte, Astro, dan Angular. Data slide, dirender oleh snippet slide (Svelte), function child (Astro), atau ng-template dengan let-item dan let-index (Angular). |
| `label` | `string` | Carousel | Nama aksesibel region carousel. Jelaskan isinya, misalnya Tur produk. |
| `perView` | `1 \| 2 \| 3` | 1 | Jumlah slide yang terlihat sekaligus. Tombol tetap bergeser satu slide. |
| `showDots` | `boolean` | false | Tampilkan satu titik per slide untuk melompat ke slide itu. Paling cocok dengan perView 1. |
| `previousLabel` | `string` | Previous slide | Label aksesibel tombol sebelumnya. Isi "Slide sebelumnya" untuk situs berbahasa Indonesia. |
| `nextLabel` | `string` | Next slide | Label aksesibel tombol berikutnya. Isi "Slide berikutnya" untuk situs berbahasa Indonesia. |
| `slideLabel` | `string` | {index} of {total} | Label aksesibel tiap slide. {index} dan {total} diganti angka, misalnya "{index} dari {total}". |
| `dotLabel` | `string` | Go to slide {index} | Label aksesibel tiap titik. {index} dan {total} diganti angka, misalnya "Ke slide {index}". |

## Aksesibilitas

- Root adalah region dengan aria-roledescription=carousel dan prop label sebagai namanya.
- Setiap slide adalah group dengan aria-roledescription=slide dan label seperti 2 of 4.
- Panah kiri dan kanan bergeser satu slide selama fokus ada di dalam carousel, dan viewport gulirnya sendiri bisa difokus.
- Tombol sebelumnya dan berikutnya adalah button native yang nonaktif di ujung, dan titik aktif punya aria-current=true.
- Tidak ada yang bergerak sendiri, jadi tidak perlu kontrol jeda. Gulir langsung tanpa animasi saat reduced motion aktif.

## Catatan

- Slide digulir dengan CSS scroll snap, jadi swipe sentuh dan trackpad langsung berfungsi.
- Pakai `perView` 2 atau 3 untuk menampilkan beberapa kartu sekaligus. Tombol tetap bergeser satu slide per tekan.
- `slideLabel` dan `dotLabel` menerima placeholder `{index}` dan `{total}`.
- Sengaja tanpa autoplay.
