Taster

진단부품톤 고르기
부품 갤러리 / Pagination

Pagination

Tabs, segmented control and disclosure

Previous and Next in words, page numbers with gaps and aria-current on the page in view, folding to "Page 4 of 12" on phones instead of wrapping.

내 사이트에서 가져오기

색을 고르면 아래 부품이 그 색으로 바뀝니다.

실제로 돌아가는 부품입니다. 눌러 보고 입력해 보세요.

내 앱에 넣기

  1. 아직 npm 패키지가 없어서 Taster 리포를 받아 그 안의 명령을 씁니다. 내 앱 폴더가 들어 있는 폴더에서 한 번만 받습니다.

    git clone https://github.com/makim-414/taster.git && npm ci --prefix taster/packages/engine
  2. 내 앱 폴더에서 이 부품을 넣습니다. 부품 파일과 토큰 파일이 src/components/taster 에 들어갑니다.

    node ../taster/packages/engine/cli.mjs add blocks/pagination --from https://taster-six.vercel.app --dir src/components/taster
  3. 부품은 Tailwind 클래스로 그리고, Taster 프리셋이 그 클래스를 토큰에 연결합니다. Tailwind CSS 를 설치하고, tokens.css 를 앱 루트에서 한 번 불러온 뒤, 앱 루트에 이 설정을 둡니다. 프리셋이 없으면 빌드는 되어도 부품이 스타일 없이 나옵니다.

    // tailwind.config.cjs
    module.exports = {
      presets: [require('./src/components/taster/tailwind-preset.cjs')],
      content: ['./index.html', './src/**/*.{ts,tsx}'],
    };

    Tailwind v3 는 이 파일을 그대로 읽습니다. v4 는 Tailwind 를 불러오는 src/ 의 스타일시트 맨 위에 이 두 줄을 넣습니다.

    @import "tailwindcss";
    @config "../tailwind.config.cjs";

    tokens.css 는 :root 에 --bg, --text, --border, --accent 를 정의합니다. 내 앱의 스타일시트가 같은 이름을 뒤에서 다시 정의하면 그쪽 색이 이깁니다. 새 Vite 앱의 스타터 CSS 처럼 그런 변수가 있으면 지우거나 이름을 바꾸세요.

언제 쓰나요

  • PaginationPrevious and Next in words, page numbers with gaps and aria-current on the page in view, folding to "Page 4 of 12" on phones instead of wrapping.

대신 없애 주는 AI 티

  • Tinted pill badge (AC-04)
  • Page wider than the screen (RSP-01)

정보

설치할 패키지
tailwindcss
라이선스
MIT
코드 보기
'use client'

import * as React from 'react'
import { cn } from './_cn'

// Pagination. Previous and Next with words, page numbers with gaps for long ranges, aria-current on the page in
// view. Below the sm breakpoint the numbers give way to "Page 3 of 12", so the row never wraps or scrolls.
// `paginationRange` is exported for custom layouts (for example a table footer).

export type PageToken = number | 'gap-start' | 'gap-end'

/** Pages to show: first, last, the current page and `siblings` on each side, with gaps between. */
export function paginationRange(page: number, pageCount: number, siblings = 1): PageToken[] {
  const total = siblings * 2 + 5
  if (pageCount <= total) return Array.from({ length: pageCount }, (_, i) => i + 1)
  const left = Math.max(page - siblings, 1)
  const right = Math.min(page + siblings, pageCount)
  const showLeftGap = left > 3
  const showRightGap = right < pageCount - 2
  if (!showLeftGap) {
    const count = siblings * 2 + 3
    return [...Array.from({ length: count }, (_, i) => i + 1), 'gap-end', pageCount]
  }
  if (!showRightGap) {
    const count = siblings * 2 + 3
    return [1, 'gap-start', ...Array.from({ length: count }, (_, i) => pageCount - count + i + 1)]
  }
  return [1, 'gap-start', ...Array.from({ length: right - left + 1 }, (_, i) => left + i), 'gap-end', pageCount]
}

export interface PaginationProps extends Omit<React.HTMLAttributes<HTMLElement>, 'onChange'> {
  page: number
  pageCount: number
  onPageChange: (page: number) => void
  siblings?: number
  label?: string
  previousLabel?: string
  nextLabel?: string
  pageLabel?: (page: number, pageCount: number) => string
}

const BTN = cn(
  'inline-flex h-11 min-w-11 items-center justify-center gap-1 rounded-md px-2 text-sm tabular-nums outline-none desk:h-9 desk:min-w-9',
  'transition-colors duration-press focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40',
)

export function Pagination({
  page,
  pageCount,
  onPageChange,
  siblings = 1,
  label = 'Pagination',
  previousLabel = 'Previous',
  nextLabel = 'Next',
  pageLabel = (p, n) => `Page ${p} of ${n}`,
  className,
  ...props
}: PaginationProps) {
  if (pageCount <= 1) return null
  const go = (p: number) => onPageChange(Math.min(pageCount, Math.max(1, p)))
  return (
    <nav aria-label={label} className={cn('flex items-center justify-between gap-2 sm:justify-start', className)} {...props}>
      <button type="button" onClick={() => go(page - 1)} disabled={page <= 1} className={cn(BTN, 'text-text-muted hover:text-text')}>
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M15 6l-6 6 6 6" />
        </svg>
        {previousLabel}
      </button>
      <span className="text-sm tabular-nums text-text-muted sm:hidden" aria-live="polite">
        {pageLabel(page, pageCount)}
      </span>
      <ul className="hidden items-center gap-1 sm:flex">
        {paginationRange(page, pageCount, siblings).map((t) =>
          typeof t === 'number' ? (
            <li key={t}>
              <button
                type="button"
                onClick={() => go(t)}
                aria-current={t === page ? 'page' : undefined}
                aria-label={pageLabel(t, pageCount)}
                className={cn(BTN, t === page ? 'border border-border bg-bg-elev font-medium text-text' : 'text-text-muted hover:text-text')}
              >
                {t}
              </button>
            </li>
          ) : (
            <li key={t} aria-hidden="true" className="px-1 text-sm text-text-subtle">
              ...
            </li>
          ),
        )}
      </ul>
      <button type="button" onClick={() => go(page + 1)} disabled={page >= pageCount} className={cn(BTN, 'text-text-muted hover:text-text')}>
        {nextLabel}
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <path d="M9 6l6 6-6 6" />
        </svg>
      </button>
    </nav>
  )
}