Taster

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

Search field

Form and input

Search with autocomplete or a static index, sort and one primary action in a single row above a list, filters as selects or chips.

내 사이트에서 가져오기

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

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

내 앱에 넣기

  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/search-field --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 처럼 그런 변수가 있으면 지우거나 이름을 바꾸세요.

언제 쓰나요

  • Search and filter barSearch with autocomplete or a static index, sort and one primary action in a single row above a list, filters as selects or chips.

정보

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

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

// SearchField. A search box that filters a list on the page: leading search icon, a clear button once there is
// text, an optional one-key shortcut (default "/") that focuses it from anywhere outside another field, and a
// polite live count of results. For commands and places across the app use the command palette instead.

export interface SearchFieldProps
  extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'type' | 'value' | 'onChange' | 'size'> {
  value: string
  onValueChange: (value: string) => void
  /** Accessible name. Shown as the placeholder too unless one is given. */
  label: string
  /** A single key that focuses the field, shown as a hint while it is empty. Pass null to turn it off. */
  shortcut?: string | null
  /** Number of matches, announced politely. Leave undefined to say nothing. */
  resultCount?: number
  resultLabel?: (count: number) => string
  clearLabel?: string
}

function isTypingTarget(el: EventTarget | null): boolean {
  if (!(el instanceof HTMLElement)) return false
  return el.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(el.tagName)
}

export const SearchField = React.forwardRef<HTMLInputElement, SearchFieldProps>(
  (
    {
      value,
      onValueChange,
      label,
      shortcut = '/',
      resultCount,
      resultLabel = (n) => (n === 1 ? '1 result' : `${n} results`),
      clearLabel = 'Clear search',
      placeholder,
      className,
      onKeyDown,
      ...props
    },
    forwarded,
  ) => {
    const inner = React.useRef<HTMLInputElement | null>(null)
    const setRef = (el: HTMLInputElement | null) => {
      inner.current = el
      if (typeof forwarded === 'function') forwarded(el)
      else if (forwarded) forwarded.current = el
    }

    React.useEffect(() => {
      if (!shortcut) return
      const onKey = (e: KeyboardEvent) => {
        if (e.key !== shortcut || e.metaKey || e.ctrlKey || e.altKey || isTypingTarget(e.target)) return
        e.preventDefault()
        inner.current?.focus()
      }
      window.addEventListener('keydown', onKey)
      return () => window.removeEventListener('keydown', onKey)
    }, [shortcut])

    return (
      <div className={cn('relative w-full', className)}>
        <svg
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          strokeWidth={1.75}
          strokeLinecap="round"
          strokeLinejoin="round"
          aria-hidden="true"
          className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-text-subtle"
        >
          <circle cx="11" cy="11" r="7" />
          <path d="M20 20l-3.5-3.5" />
        </svg>
        <input
          ref={setRef}
          type="search"
          aria-label={label}
          placeholder={placeholder ?? label}
          value={value}
          onChange={(e) => onValueChange(e.target.value)}
          onKeyDown={(e) => {
            if (e.key === 'Escape' && value) {
              e.preventDefault()
              onValueChange('')
            }
            onKeyDown?.(e)
          }}
          className={cn(
            'h-11 w-full rounded-md border border-border-input bg-transparent pl-9 pr-12 text-sm text-text desk:h-9',
            'placeholder:text-text-subtle outline-none focus-visible:ring-2 focus-visible:ring-ring',
            '[&::-webkit-search-cancel-button]:appearance-none',
          )}
          {...props}
        />
        <div className="absolute inset-y-0 right-0 flex items-center">
          {value ? (
            <button
              type="button"
              onClick={() => {
                onValueChange('')
                inner.current?.focus()
              }}
              aria-label={clearLabel}
              className={cn(
                'inline-flex size-11 items-center justify-center rounded-md text-text-subtle outline-none desk:size-9',
                'transition-colors duration-press hover:text-text focus-visible:ring-2 focus-visible:ring-ring',
              )}
            >
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={1.75} strokeLinecap="round" aria-hidden="true">
                <path d="M6 6l12 12M18 6L6 18" />
              </svg>
            </button>
          ) : shortcut ? (
            <span className="pr-3" aria-hidden="true">
              <Kbd>{shortcut}</Kbd>
            </span>
          ) : null}
        </div>
        {resultCount !== undefined && (
          <span className="sr-only" role="status" aria-live="polite">
            {value ? resultLabel(resultCount) : ''}
          </span>
        )}
      </div>
    )
  },
)
SearchField.displayName = 'SearchField'