Taster

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

Use hotkeys

Command palette and shortcuts

Open with a shortcut, type to filter grouped commands and pages, move with arrows, trap focus inside. A companion sheet lists keyboard shortcuts by area.

내 사이트에서 가져오기

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

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

내 앱에 넣기

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

언제 쓰나요

  • Command paletteOpen with a shortcut, type to filter grouped commands and pages, move with arrows, trap focus inside. A companion sheet lists keyboard shortcuts by area.

정보

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

import * as React from 'react'

// Keyboard hooks, React only, no dependency.
// useHotkeys: mod+k (works while typing), two-key chords like 'g q', single keys (ignored while typing).
// useFocusTrap: moves focus into a modal, cycles Tab inside it and returns focus on close.
// useListNavigation: j/k and arrow keys over a list.

export type HotkeyHandler = (e: KeyboardEvent) => void

const isTyping = (el: EventTarget | null): boolean => {
  const t = el as HTMLElement | null
  if (!t) return false
  const tag = t.tagName
  return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || t.isContentEditable
}

export function useHotkeys(bindings: Record<string, HotkeyHandler>, enabled = true): void {
  const ref = React.useRef(bindings)
  ref.current = bindings

  React.useEffect(() => {
    if (!enabled) return
    let chordPrefix: string | null = null
    let chordTimer: ReturnType<typeof setTimeout> | null = null

    const clearChord = () => {
      chordPrefix = null
      if (chordTimer) clearTimeout(chordTimer)
      chordTimer = null
    }

    const onKey = (e: KeyboardEvent) => {
      const map = ref.current
      const key = e.key.toLowerCase()

      if ((e.metaKey || e.ctrlKey) && !e.altKey) {
        const binding = map[`mod+${key}`]
        if (binding) {
          e.preventDefault()
          binding(e)
          return
        }
      }
      if (e.metaKey || e.ctrlKey || e.altKey) return
      if (isTyping(e.target)) return

      if (chordPrefix) {
        const combo = `${chordPrefix} ${key}`
        clearChord()
        const binding = map[combo]
        if (binding) {
          e.preventDefault()
          binding(e)
          return
        }
      }

      if (map[key]) {
        e.preventDefault()
        map[key](e)
        return
      }
      const startsChord = Object.keys(map).some((k) => k.startsWith(`${key} `))
      if (startsChord) {
        chordPrefix = key
        chordTimer = setTimeout(clearChord, 800)
      }
    }

    window.addEventListener('keydown', onKey)
    return () => {
      window.removeEventListener('keydown', onKey)
      clearChord()
    }
  }, [enabled])
}

export function useFocusTrap(ref: React.RefObject<HTMLElement | null>, active = true): void {
  React.useEffect(() => {
    if (!active) return
    const node = ref.current
    if (!node) return

    const selector =
      'a[href],button:not([disabled]),textarea,input,select,[tabindex]:not([tabindex="-1"])'
    const focusables = () =>
      Array.from(node.querySelectorAll<HTMLElement>(selector)).filter((el) => el.offsetParent !== null)

    // Move focus in on open and hand it back on close. Leave autoFocus off the fields inside: it runs before this
    // effect, so the element to return to would already be lost.
    const opener = document.activeElement instanceof HTMLElement ? document.activeElement : null
    if (!node.contains(document.activeElement)) (focusables()[0] ?? node).focus()

    const onKey = (e: KeyboardEvent) => {
      if (e.key !== 'Tab') return
      const items = focusables()
      if (items.length === 0) {
        e.preventDefault()
        return
      }
      const first = items[0]
      const last = items[items.length - 1]
      const activeEl = document.activeElement
      if (e.shiftKey && (activeEl === first || activeEl === node)) {
        e.preventDefault()
        last.focus()
      } else if (!e.shiftKey && activeEl === last) {
        e.preventDefault()
        first.focus()
      }
    }

    node.addEventListener('keydown', onKey, true)
    return () => {
      node.removeEventListener('keydown', onKey, true)
      if (opener && opener !== node && !node.contains(opener) && opener.isConnected) opener.focus()
    }
  }, [ref, active])
}

export function useListNavigation({
  length,
  onOpen,
  enabled = true,
}: {
  length: number
  onOpen?: (index: number) => void
  enabled?: boolean
}): [number, React.Dispatch<React.SetStateAction<number>>] {
  const [index, setIndex] = React.useState(0)

  React.useEffect(() => {
    if (index > length - 1) setIndex(Math.max(0, length - 1))
  }, [length, index])

  React.useEffect(() => {
    if (!enabled) return
    const onKey = (e: KeyboardEvent) => {
      if (isTyping(e.target)) return
      switch (e.key) {
        case 'j':
        case 'ArrowDown':
          e.preventDefault()
          setIndex((i) => Math.min(length - 1, i + 1))
          break
        case 'k':
        case 'ArrowUp':
          e.preventDefault()
          setIndex((i) => Math.max(0, i - 1))
          break
        case 'Home':
          e.preventDefault()
          setIndex(0)
          break
        case 'End':
          e.preventDefault()
          setIndex(length - 1)
          break
        case 'Enter':
          if (onOpen) {
            e.preventDefault()
            onOpen(index)
          }
          break
        default:
          break
      }
    }
    window.addEventListener('keydown', onKey)
    return () => window.removeEventListener('keydown', onKey)
  }, [enabled, length, index, onOpen])

  return [index, setIndex]
}