# Pagination

Navigasi antar halaman berbasis link dengan tombol Sebelumnya, Berikutnya, dan elipsis untuk halaman yang dilewati.

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

## Kapan dipakai

Daftar panjang yang dibagi ke beberapa halaman dan dimuat ulang lewat URL, misalnya tabel atau hasil pencarian.

- Pola href wajib memuat {page}
- Jumlah tombol tetap siblings * 2 + 5 agar posisi tidak bergeser saat berpindah halaman

## Kode

### Blade

Simpan di `resources/views/components/markas/pagination.blade.php`. Tanpa dependensi tambahan.

```blade
@props([
    'page' => 1,
    'total' => 1,
    'href' => '?page={page}',
    'siblings' => 1,
    'navLabel' => 'Pagination',
    'previousLabel' => 'Previous',
    'nextLabel' => 'Next',
])

@php
    $root = '@container';
    $list = 'flex flex-wrap items-center gap-1';
    $link = 'inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none';
    $ellipsis = 'inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted';
    $icon = 'size-4 shrink-0';
    $label = 'sr-only @lg:not-sr-only';

    // Logika sama persis dengan pageRange() di Pagination.tsx dan Pagination.vue.
    $pageRange = function (int $page, int $total, int $siblings): array {
        if ($total < 1) {
            return [];
        }
        $slots = $siblings * 2 + 5;
        if ($total <= $slots) {
            return range(1, $total);
        }
        $current = min(max($page, 1), $total);
        $start = min(max($current - $siblings, 3), $total - 2 - $siblings * 2);
        $end = $start + $siblings * 2;

        return [1, $start > 3 ? 'ellipsis' : 2, ...range($start, $end), $end < $total - 2 ? 'ellipsis' : $total - 1, $total];
    };

    // Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#".
    $safeHref = function (string $href): string {
        $value = ltrim(str_replace(["\t", "\n", "\r"], '', $href), "\x00..\x20");
        $hasScheme = preg_match('/^[a-z][a-z0-9+.\-]*:/i', $value) === 1;

        return $hasScheme && preg_match('/^(https?|mailto|tel):/i', $value) !== 1 ? '#' : $href;
    };

    $total = (int) $total;
    $current = min(max((int) $page, 1), max($total, 1));
    $pages = $pageRange($current, $total, (int) $siblings);
    $hrefFor = fn (int $target): string => $safeHref(str_replace('{page}', (string) $target, (string) $href));
@endphp

<nav {{ $attributes->merge(['aria-label' => $navLabel])->class([$root]) }}>
    <ul class="{{ $list }}">
        <li>
            @if ($current > 1)
                <a href="{{ $hrefFor($current - 1) }}" rel="prev" class="{{ $link }}">
                    <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
                    <span class="{{ $label }}">{{ $previousLabel }}</span>
                </a>
            @else
                <span aria-disabled="true" class="{{ $link }}">
                    <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m15 18-6-6 6-6" /></svg>
                    <span class="{{ $label }}">{{ $previousLabel }}</span>
                </span>
            @endif
        </li>
        @foreach ($pages as $index => $item)
            <li>
                @if ($item === 'ellipsis')
                    <span class="{{ $ellipsis }}" aria-hidden="true">…</span>
                @else
                    <a
                        href="{{ $hrefFor($item) }}"
                        @if ($item === $current) aria-current="page" @endif
                        data-state="{{ $item === $current ? 'active' : 'inactive' }}"
                        class="{{ $link }}"
                    >{{ $item }}</a>
                @endif
            </li>
        @endforeach
        <li>
            @if ($current < $total)
                <a href="{{ $hrefFor($current + 1) }}" rel="next" class="{{ $link }}">
                    <span class="{{ $label }}">{{ $nextLabel }}</span>
                    <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
                </a>
            @else
                <span aria-disabled="true" class="{{ $link }}">
                    <span class="{{ $label }}">{{ $nextLabel }}</span>
                    <svg class="{{ $icon }}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m9 18 6-6-6-6" /></svg>
                </span>
            @endif
        </li>
    </ul>
</nav>
```

```blade
<x-markas.pagination
    :page="$users->currentPage()"
    :total="$users->lastPage()"
    href="?page={page}"
    nav-label="Navigasi halaman"
    previous-label="Sebelumnya"
    next-label="Berikutnya"
/>
```

Tidak butuh Alpine.js.

### React

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

```tsx
import type { ComponentProps } from "react";

const root = "@container";
const list = "flex flex-wrap items-center gap-1";
const link =
  "inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none";
const ellipsis =
  "inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted";
const icon = "size-4 shrink-0";
const label = "sr-only @lg:not-sr-only";
const cx = (...c: (string | false | null | undefined)[]) =>
  c.filter(Boolean).join(" ");

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

export type PageItem = number | "ellipsis";

const range = (from: number, to: number) =>
  Array.from({ length: to - from + 1 }, (_, index) => from + index);

/** Logika sama persis dengan $pageRange di pagination.blade.php dan Pagination.vue. */
export function pageRange(
  page: number,
  total: number,
  siblings: number,
): PageItem[] {
  if (total < 1) return [];
  const slots = siblings * 2 + 5;
  if (total <= slots) return range(1, total);
  const current = Math.min(Math.max(page, 1), total);
  const start = Math.min(
    Math.max(current - siblings, 3),
    total - 2 - siblings * 2,
  );
  const end = start + siblings * 2;

  return [
    1,
    start > 3 ? "ellipsis" : 2,
    ...range(start, end),
    end < total - 2 ? "ellipsis" : total - 1,
    total,
  ];
}

export type PaginationProps = ComponentProps<"nav"> & {
  page: number;
  total: number;
  href?: string;
  siblings?: number;
  /** Accessible label of the nav element. */
  navLabel?: string;
  /** Text of the previous page link. */
  previousLabel?: string;
  /** Text of the next page link. */
  nextLabel?: string;
};

const PrevIcon = () => (
  <svg
    className={icon}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d="m15 18-6-6 6-6" />
  </svg>
);

const NextIcon = () => (
  <svg
    className={icon}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    strokeWidth="1.5"
    strokeLinecap="round"
    strokeLinejoin="round"
    aria-hidden="true"
  >
    <path d="m9 18 6-6-6-6" />
  </svg>
);

export function Pagination({
  page,
  total,
  href = "?page={page}",
  siblings = 1,
  navLabel = "Pagination",
  previousLabel = "Previous",
  nextLabel = "Next",
  className,
  ...props
}: PaginationProps) {
  const current = Math.min(Math.max(page, 1), Math.max(total, 1));
  const pages = pageRange(current, total, siblings);
  const hrefFor = (target: number) =>
    safeHref(href.replaceAll("{page}", String(target)));

  return (
    <nav aria-label={navLabel} className={cx(root, className)} {...props}>
      <ul className={list}>
        <li>
          {current > 1 ? (
            <a href={hrefFor(current - 1)} rel="prev" className={link}>
              <PrevIcon />
              <span className={label}>{previousLabel}</span>
            </a>
          ) : (
            <span aria-disabled="true" className={link}>
              <PrevIcon />
              <span className={label}>{previousLabel}</span>
            </span>
          )}
        </li>
        {pages.map((item, index) => (
          <li key={index}>
            {item === "ellipsis" ? (
              <span className={ellipsis} aria-hidden="true">
                …
              </span>
            ) : (
              <a
                href={hrefFor(item)}
                aria-current={item === current ? "page" : undefined}
                data-state={item === current ? "active" : "inactive"}
                className={link}
              >
                {item}
              </a>
            )}
          </li>
        ))}
        <li>
          {current < total ? (
            <a href={hrefFor(current + 1)} rel="next" className={link}>
              <span className={label}>{nextLabel}</span>
              <NextIcon />
            </a>
          ) : (
            <span aria-disabled="true" className={link}>
              <span className={label}>{nextLabel}</span>
              <NextIcon />
            </span>
          )}
        </li>
      </ul>
    </nav>
  );
}
```

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

<Pagination
  page={5}
  total={10}
  href="?page={page}"
  navLabel="Navigasi halaman"
  previousLabel="Sebelumnya"
  nextLabel="Berikutnya"
/>;
```

### Vue

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

```vue
<script lang="ts">
export type PageItem = number | "ellipsis";

const range = (from: number, to: number) =>
  Array.from({ length: to - from + 1 }, (_, index) => from + index);

/** Logika sama persis dengan $pageRange di pagination.blade.php dan Pagination.tsx. */
export function pageRange(
  page: number,
  total: number,
  siblings: number,
): PageItem[] {
  if (total < 1) return [];
  const slots = siblings * 2 + 5;
  if (total <= slots) return range(1, total);
  const current = Math.min(Math.max(page, 1), total);
  const start = Math.min(
    Math.max(current - siblings, 3),
    total - 2 - siblings * 2,
  );
  const end = start + siblings * 2;

  return [
    1,
    start > 3 ? "ellipsis" : 2,
    ...range(start, end),
    end < total - 2 ? "ellipsis" : total - 1,
    total,
  ];
}
</script>

<script setup lang="ts">
import { computed } from "vue";

const props = withDefaults(
  defineProps<{
    page: number;
    total: number;
    href?: string;
    siblings?: number;
    navLabel?: string;
    previousLabel?: string;
    nextLabel?: string;
  }>(),
  {
    href: "?page={page}",
    siblings: 1,
    navLabel: "Pagination",
    previousLabel: "Previous",
    nextLabel: "Next",
  },
);

const root = "@container";
const list = "flex flex-wrap items-center gap-1";
const link =
  "inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none";
const ellipsis =
  "inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted";
const icon = "size-4 shrink-0";
const label = "sr-only @lg:not-sr-only";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

const current = computed(() =>
  Math.min(Math.max(props.page, 1), Math.max(props.total, 1)),
);
const pages = computed(() =>
  pageRange(current.value, props.total, props.siblings),
);
const hrefFor = (target: number) =>
  safeHref(props.href.replaceAll("{page}", String(target)));
</script>

<template>
  <nav :aria-label="props.navLabel" :class="root">
    <ul :class="list">
      <li>
        <a
          v-if="current > 1"
          :href="hrefFor(current - 1)"
          rel="prev"
          :class="link"
        >
          <svg
            :class="icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
          <span :class="label">{{ props.previousLabel }}</span>
        </a>
        <span v-else aria-disabled="true" :class="link">
          <svg
            :class="icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m15 18-6-6 6-6" />
          </svg>
          <span :class="label">{{ props.previousLabel }}</span>
        </span>
      </li>
      <li v-for="(item, index) in pages" :key="index">
        <span v-if="item === 'ellipsis'" :class="ellipsis" aria-hidden="true"
          >…</span
        >
        <a
          v-else
          :href="hrefFor(item)"
          :aria-current="item === current ? 'page' : undefined"
          :data-state="item === current ? 'active' : 'inactive'"
          :class="link"
          >{{ item }}</a
        >
      </li>
      <li>
        <a
          v-if="current < props.total"
          :href="hrefFor(current + 1)"
          rel="next"
          :class="link"
        >
          <span :class="label">{{ props.nextLabel }}</span>
          <svg
            :class="icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </a>
        <span v-else aria-disabled="true" :class="link">
          <span :class="label">{{ props.nextLabel }}</span>
          <svg
            :class="icon"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            stroke-width="1.5"
            stroke-linecap="round"
            stroke-linejoin="round"
            aria-hidden="true"
          >
            <path d="m9 18 6-6-6-6" />
          </svg>
        </span>
      </li>
    </ul>
  </nav>
</template>
```

```vue
<template>
  <Pagination
    :page="5"
    :total="10"
    href="?page={page}"
    nav-label="Navigasi halaman"
    previous-label="Sebelumnya"
    next-label="Berikutnya"
  />
</template>
```

### Svelte

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

```svelte
<script lang="ts" module>
  export type PageItem = number | "ellipsis";

  const range = (from: number, to: number) =>
    Array.from({ length: to - from + 1 }, (_, index) => from + index);

  /** Logika sama persis dengan pageRange di Pagination.tsx dan $pageRange di pagination.blade.php. */
  export function pageRange(
    page: number,
    total: number,
    siblings: number,
  ): PageItem[] {
    if (total < 1) return [];
    const slots = siblings * 2 + 5;
    if (total <= slots) return range(1, total);
    const current = Math.min(Math.max(page, 1), total);
    const start = Math.min(
      Math.max(current - siblings, 3),
      total - 2 - siblings * 2,
    );
    const end = start + siblings * 2;

    return [
      1,
      start > 3 ? "ellipsis" : 2,
      ...range(start, end),
      end < total - 2 ? "ellipsis" : total - 1,
      total,
    ];
  }
</script>

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

  const root = "@container";
  const list = "flex flex-wrap items-center gap-1";
  const link =
    "inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none";
  const ellipsis =
    "inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted";
  const icon = "size-4 shrink-0";
  const label = "sr-only @lg:not-sr-only";

  const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
  const SAFE_SCHEME = /^(https?|mailto|tel):/i;

  /** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
  const safeHref = (href: string) => {
    const cleaned = href.replace(/[\t\n\r]/g, "");
    const start = [...cleaned].findIndex((char) => char > " ");
    const value = cleaned.slice(Math.max(start, 0));
    return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
  };

  type Props = HTMLAttributes<HTMLElement> & {
    page: number;
    total: number;
    href?: string;
    siblings?: number;
    /** Accessible label of the nav element. */
    navLabel?: string;
    /** Text of the previous page link. */
    previousLabel?: string;
    /** Text of the next page link. */
    nextLabel?: string;
  };

  let {
    page,
    total,
    href = "?page={page}",
    siblings = 1,
    navLabel = "Pagination",
    previousLabel = "Previous",
    nextLabel = "Next",
    class: className,
    ...rest
  }: Props = $props();

  const current = $derived(Math.min(Math.max(page, 1), Math.max(total, 1)));
  const pages = $derived(pageRange(current, total, siblings));
  const hrefFor = (target: number) =>
    safeHref(href.replaceAll("{page}", String(target)));
</script>

{#snippet prevIcon()}
  <svg
    class={icon}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d="m15 18-6-6 6-6" />
  </svg>
{/snippet}

{#snippet nextIcon()}
  <svg
    class={icon}
    viewBox="0 0 24 24"
    fill="none"
    stroke="currentColor"
    stroke-width="1.5"
    stroke-linecap="round"
    stroke-linejoin="round"
    aria-hidden="true"
  >
    <path d="m9 18 6-6-6-6" />
  </svg>
{/snippet}

<nav aria-label={navLabel} class={[root, className]} {...rest}>
  <ul class={list}>
    <li>
      {#if current > 1}
        <a href={hrefFor(current - 1)} rel="prev" class={link}>
          {@render prevIcon()}
          <span class={label}>{previousLabel}</span>
        </a>
      {:else}
        <span aria-disabled="true" class={link}>
          {@render prevIcon()}
          <span class={label}>{previousLabel}</span>
        </span>
      {/if}
    </li>
    {#each pages as item, index (index)}
      <li>
        {#if item === "ellipsis"}
          <span class={ellipsis} aria-hidden="true">…</span>
        {:else}
          <a
            href={hrefFor(item)}
            aria-current={item === current ? "page" : undefined}
            data-state={item === current ? "active" : "inactive"}
            class={link}>{item}</a
          >
        {/if}
      </li>
    {/each}
    <li>
      {#if current < total}
        <a href={hrefFor(current + 1)} rel="next" class={link}>
          <span class={label}>{nextLabel}</span>
          {@render nextIcon()}
        </a>
      {:else}
        <span aria-disabled="true" class={link}>
          <span class={label}>{nextLabel}</span>
          {@render nextIcon()}
        </span>
      {/if}
    </li>
  </ul>
</nav>
```

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

<Pagination
  page={5}
  total={10}
  href={"?page={page}"}
  navLabel="Navigasi halaman"
  previousLabel="Sebelumnya"
  nextLabel="Berikutnya"
/>
```

Tulis pola di dalam `{"..."}`, karena `{page}` di atribut Svelte yang dikutip dianggap ekspresi.

### Astro

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

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

const root = "@container";
const list = "flex flex-wrap items-center gap-1";
const link =
  "inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none";
const ellipsis =
  "inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted";
const icon = "size-4 shrink-0";
const label = "sr-only @lg:not-sr-only";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

type PageItem = number | "ellipsis";

const range = (from: number, to: number) =>
  Array.from({ length: to - from + 1 }, (_, index) => from + index);

/** Logika sama persis dengan pageRange di Pagination.tsx dan $pageRange di pagination.blade.php. */
function pageRange(page: number, total: number, siblings: number): PageItem[] {
  if (total < 1) return [];
  const slots = siblings * 2 + 5;
  if (total <= slots) return range(1, total);
  const current = Math.min(Math.max(page, 1), total);
  const start = Math.min(
    Math.max(current - siblings, 3),
    total - 2 - siblings * 2,
  );
  const end = start + siblings * 2;

  return [
    1,
    start > 3 ? "ellipsis" : 2,
    ...range(start, end),
    end < total - 2 ? "ellipsis" : total - 1,
    total,
  ];
}

type Props = HTMLAttributes<"nav"> & {
  page: number;
  total: number;
  href?: string;
  siblings?: number;
  /** Accessible label of the nav element. */
  navLabel?: string;
  /** Text of the previous page link. */
  previousLabel?: string;
  /** Text of the next page link. */
  nextLabel?: string;
};

const {
  page,
  total,
  href = "?page={page}",
  siblings = 1,
  navLabel = "Pagination",
  previousLabel = "Previous",
  nextLabel = "Next",
  class: className,
  ...rest
} = Astro.props;

const current = Math.min(Math.max(page, 1), Math.max(total, 1));
const pages = pageRange(current, total, siblings);
const hrefFor = (target: number) =>
  safeHref(href.replaceAll("{page}", String(target)));
const prevPath = "m15 18-6-6 6-6";
const nextPath = "m9 18 6-6-6-6";
---

<nav aria-label={navLabel} class:list={[root, className]} {...rest}>
  <ul class={list}>
    <li>
      {
        current > 1 ? (
          <a href={hrefFor(current - 1)} rel="prev" class={link}>
            <svg class={icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={prevPath} /></svg>
            <span class={label}>{previousLabel}</span>
          </a>
        ) : (
          <span aria-disabled="true" class={link}>
            <svg class={icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={prevPath} /></svg>
            <span class={label}>{previousLabel}</span>
          </span>
        )
      }
    </li>
    {
      pages.map((item) => (
        <li>
          {item === "ellipsis" ? (
            <span class={ellipsis} aria-hidden="true">…</span>
          ) : (
            <a
              href={hrefFor(item)}
              aria-current={item === current ? "page" : undefined}
              data-state={item === current ? "active" : "inactive"}
              class={link}
            >{item}</a>
          )}
        </li>
      ))
    }
    <li>
      {
        current < total ? (
          <a href={hrefFor(current + 1)} rel="next" class={link}>
            <span class={label}>{nextLabel}</span>
            <svg class={icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={nextPath} /></svg>
          </a>
        ) : (
          <span aria-disabled="true" class={link}>
            <span class={label}>{nextLabel}</span>
            <svg class={icon} viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d={nextPath} /></svg>
          </span>
        )
      }
    </li>
  </ul>
</nav>
```

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

<Pagination
  page={5}
  total={10}
  href="?page={page}"
  navLabel="Navigasi halaman"
  previousLabel="Sebelumnya"
  nextLabel="Berikutnya"
/>
```

Tanpa script klien: semua link berupa anchor biasa.

### Angular

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

```ts
import {
  ChangeDetectionStrategy,
  Component,
  computed,
  input,
  numberAttribute,
} from "@angular/core";
import { NgTemplateOutlet } from "@angular/common";

const root = "@container";
const list = "flex flex-wrap items-center gap-1";
const link =
  "inline-flex h-8 min-w-8 items-center justify-center gap-1 rounded-md border border-transparent px-2 text-sm font-medium text-muted transition-colors duration-150 ease-out hover:bg-subtle hover:text-ink focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[state=active]:border-line data-[state=active]:bg-surface data-[state=active]:text-ink motion-reduce:transition-none";
const ellipsis =
  "inline-flex h-8 min-w-8 items-center justify-center text-sm text-muted";
const icon = "size-4 shrink-0";
const label = "sr-only @lg:not-sr-only";

const HAS_SCHEME = /^[a-z][a-z0-9+.-]*:/i;
const SAFE_SCHEME = /^(https?|mailto|tel):/i;

/** Href berskema selain http, https, mailto, dan tel (misalnya javascript:) diganti "#". */
const safeHref = (href: string) => {
  const cleaned = href.replace(/[\t\n\r]/g, "");
  const start = [...cleaned].findIndex((char) => char > " ");
  const value = cleaned.slice(Math.max(start, 0));
  return HAS_SCHEME.test(value) && !SAFE_SCHEME.test(value) ? "#" : href;
};

export type PageItem = number | "ellipsis";

const range = (from: number, to: number) =>
  Array.from({ length: to - from + 1 }, (_, index) => from + index);

/** Logika sama persis dengan pageRange di Pagination.tsx dan $pageRange di pagination.blade.php. */
export function pageRange(
  page: number,
  total: number,
  siblings: number,
): PageItem[] {
  if (total < 1) return [];
  const slots = siblings * 2 + 5;
  if (total <= slots) return range(1, total);
  const current = Math.min(Math.max(page, 1), total);
  const start = Math.min(
    Math.max(current - siblings, 3),
    total - 2 - siblings * 2,
  );
  const end = start + siblings * 2;

  return [
    1,
    start > 3 ? "ellipsis" : 2,
    ...range(start, end),
    end < total - 2 ? "ellipsis" : total - 1,
    total,
  ];
}

/**
 * Attribute selector on the native nav, so id, class, and other attributes stay on the nav.
 * Usage: `<nav markas-pagination page="5" total="10"></nav>`.
 */
@Component({
  selector: "nav[markas-pagination]",
  changeDetection: ChangeDetectionStrategy.OnPush,
  host: { "[attr.aria-label]": "navLabel()", "[class]": "root" },
  template: `
    <ng-template #prevIcon>
      <svg
        [attr.class]="icon"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m15 18-6-6 6-6" />
      </svg>
    </ng-template>
    <ng-template #nextIcon>
      <svg
        [attr.class]="icon"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1.5"
        stroke-linecap="round"
        stroke-linejoin="round"
        aria-hidden="true"
      >
        <path d="m9 18 6-6-6-6" />
      </svg>
    </ng-template>
    <ul [class]="list">
      <li>
        @if (current() > 1) {
          <a [attr.href]="hrefFor(current() - 1)" rel="prev" [class]="link">
            <ng-container [ngTemplateOutlet]="prevIcon" />
            <span [class]="label">{{ previousLabel() }}</span>
          </a>
        } @else {
          <span aria-disabled="true" [class]="link">
            <ng-container [ngTemplateOutlet]="prevIcon" />
            <span [class]="label">{{ previousLabel() }}</span>
          </span>
        }
      </li>
      @for (item of pages(); track $index) {
        <li>
          @if (item === "ellipsis") {
            <span [class]="ellipsis" aria-hidden="true">…</span>
          } @else {
            <a
              [attr.href]="hrefFor(item)"
              [attr.aria-current]="item === current() ? 'page' : null"
              [attr.data-state]="item === current() ? 'active' : 'inactive'"
              [class]="link"
              >{{ item }}</a
            >
          }
        </li>
      }
      <li>
        @if (current() < total()) {
          <a [attr.href]="hrefFor(current() + 1)" rel="next" [class]="link">
            <span [class]="label">{{ nextLabel() }}</span>
            <ng-container [ngTemplateOutlet]="nextIcon" />
          </a>
        } @else {
          <span aria-disabled="true" [class]="link">
            <span [class]="label">{{ nextLabel() }}</span>
            <ng-container [ngTemplateOutlet]="nextIcon" />
          </span>
        }
      </li>
    </ul>
  `,
  imports: [NgTemplateOutlet],
})
export class Pagination {
  readonly page = input.required({ transform: numberAttribute });
  readonly total = input.required({ transform: numberAttribute });
  readonly href = input("?page={page}");
  readonly siblings = input(1, { transform: numberAttribute });
  /** Accessible label of the nav element. */
  readonly navLabel = input("Pagination");
  /** Text of the previous page link. */
  readonly previousLabel = input("Previous");
  /** Text of the next page link. */
  readonly nextLabel = input("Next");

  protected readonly root = root;
  protected readonly list = list;
  protected readonly link = link;
  protected readonly ellipsis = ellipsis;
  protected readonly icon = icon;
  protected readonly label = label;
  protected readonly current = computed(() =>
    Math.min(Math.max(this.page(), 1), Math.max(this.total(), 1)),
  );
  protected readonly pages = computed(() =>
    pageRange(this.current(), this.total(), this.siblings()),
  );

  protected hrefFor(target: number) {
    return safeHref(this.href().replaceAll("{page}", String(target)));
  }
}
```

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

@Component({
  selector: "app-hasil",
  imports: [Pagination],
  template: `
    <nav
      markas-pagination
      [page]="page"
      total="10"
      [href]="href"
      navLabel="Navigasi halaman"
      previousLabel="Sebelumnya"
      nextLabel="Berikutnya"
    ></nav>
  `,
})
export class Hasil {
  readonly page = 5;
  readonly href = "?page={page}";
}
```

Angular memakai attribute selector pada nav native, jadi `id`, `class`, dan atribut lain tetap di nav. Isi `href` lewat properti karena `{page}` bentrok dengan sintaks template.

## Props

| Nama | Tipe | Default | Keterangan |
| --- | --- | --- | --- |
| `page` | `number` | 1 | Halaman saat ini. Dibatasi ke rentang 1 sampai total. |
| `total` | `number` | 1 | Jumlah halaman. |
| `href` | `string` | '?page={page}' | Pola URL. {page} diganti nomor halaman. |
| `siblings` | `number` | 1 | Jumlah halaman yang tampil di kiri dan kanan halaman saat ini. |
| `navLabel` | `string` | Pagination | Label aksesibel elemen nav. Isi "Navigasi halaman" untuk situs berbahasa Indonesia. |
| `previousLabel` | `string` | Previous | Teks link halaman sebelumnya. Isi "Sebelumnya" untuk situs berbahasa Indonesia. |
| `nextLabel` | `string` | Next | Teks link halaman berikutnya. Isi "Berikutnya" untuk situs berbahasa Indonesia. |

## Aksesibilitas

- Dibungkus nav dengan label dari navLabel (default Pagination).
- Halaman aktif memakai aria-current=page.
- Link sebelumnya dan berikutnya memakai rel prev dan next, dan menjadi span aria-disabled di halaman pertama atau terakhir.
- Elipsis diberi aria-hidden.
- Di container sempit teks previousLabel dan nextLabel hanya disembunyikan secara visual (sr-only), nama aksesibelnya tetap ada.

## Catatan

- Jumlah tombol angka tetap `siblings * 2 + 5` (7 untuk default), contoh halaman 5 dari 10: 1 … 4 5 6 … 10.
- Fungsi `pageRange(page, total, siblings)` diekspor dari versi React, Vue, Svelte (module script), dan Angular bila ingin membuat tampilan sendiri.
- Teks bawaan dalam bahasa Inggris ("Pagination", "Previous", "Next"). Isi `navLabel`, `previousLabel`, dan `nextLabel` (Blade: `nav-label`, `previous-label`, `next-label`) untuk situs berbahasa Indonesia.
