Command palette
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.
실제로 돌아가는 부품입니다. 눌러 보고 입력해 보세요.
내 앱에 넣기
아직 npm 패키지가 없어서 Taster 리포를 받아 그 안의 명령을 씁니다. 내 앱 폴더가 들어 있는 폴더에서 한 번만 받습니다.
git clone https://github.com/makim-414/taster.git && npm ci --prefix taster/packages/engine내 앱 폴더에서 이 부품을 넣습니다. 부품 파일과 토큰 파일이
src/components/taster에 들어갑니다.node ../taster/packages/engine/cli.mjs add blocks/command-palette --from https://taster-six.vercel.app --dir src/components/taster부품은 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.
정보
코드 보기
'use client'
import * as React from 'react'
import { cn } from './_cn'
import { useFocusTrap } from './use-hotkeys'
// CommandPalette. A command menu opened with mod+k. Tokens only, no external UI dependency.
// Items are defined by the caller, each item carries its own run() callback.
// Korean labels also match by initials, see matchCommands.
export interface CommandItem {
id: string
kind: string
label: string
hint?: string
run: () => void
}
export interface CommandPaletteProps {
items: CommandItem[]
onClose: () => void
placeholder?: string
}
// Hangul initials: a Korean query typed as consonants only ("ㄹㅇㅂㄹ") matches the syllables they start
// ("라이브러리"). Each syllable from U+AC00 maps to one of 19 initials in blocks of 588.
const INITIALS = 'ㄱㄲㄴㄷㄸㄹㅁㅂㅃㅅㅆㅇㅈㅉㅊㅋㅌㅍㅎ'
const ONLY_INITIALS = /^[\u3131-\u314e]+$/
function initialsOf(text: string) {
return Array.from(text, (ch) => {
const k = ch.charCodeAt(0) - 0xac00
return k >= 0 && k < 11172 ? INITIALS[Math.floor(k / 588)] : ch
}).join('')
}
// Rank: label starts with the query, then label contains it, then kind or hint does. Same rank keeps input order.
export function matchCommands(items: CommandItem[], query: string): CommandItem[] {
const q = query.trim().toLowerCase().replace(/\s+/g, '')
if (!q) return items
const squash = (t: string) => t.toLowerCase().replace(/\s+/g, '')
const fold = ONLY_INITIALS.test(q) ? (t: string) => initialsOf(squash(t)) : squash
const rank = (it: CommandItem) => {
const label = fold(it.label)
if (label.startsWith(q)) return 0
if (label.includes(q)) return 1
if (fold(`${it.kind} ${it.hint ?? ''}`).includes(q)) return 2
return -1
}
return items
.map((it, i) => ({ it, i, r: rank(it) }))
.filter((x) => x.r >= 0)
.sort((a, b) => a.r - b.r || a.i - b.i)
.map((x) => x.it)
}
export function CommandPalette({ items, onClose, placeholder = 'Search commands' }: CommandPaletteProps) {
const [query, setQuery] = React.useState('')
const [hi, setHi] = React.useState(0)
const dialogRef = React.useRef<HTMLDivElement>(null)
// The trap puts focus on the input and gives it back to the opener on close.
useFocusTrap(dialogRef)
const listId = React.useId()
const optionId = (i: number) => `${listId}-${i}`
const filtered = React.useMemo(() => matchCommands(items, query), [items, query])
const clampedHi = Math.min(hi, Math.max(0, filtered.length - 1))
const activeId = filtered.length ? optionId(clampedHi) : undefined
React.useEffect(() => {
if (activeId) document.getElementById(activeId)?.scrollIntoView({ block: 'nearest' })
}, [activeId])
// Focus stays on the input (combobox with aria-activedescendant): the arrows move the highlight and Enter runs
// the highlighted command, so what Enter runs is always the row that is shown as chosen.
const onKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'ArrowDown') {
e.preventDefault()
setHi((i) => Math.min(filtered.length - 1, i + 1))
} else if (e.key === 'ArrowUp') {
e.preventDefault()
setHi((i) => Math.max(0, i - 1))
} else if (e.key === 'Home' || e.key === 'End') {
e.preventDefault()
setHi(e.key === 'Home' ? 0 : Math.max(0, filtered.length - 1))
} else if (e.key === 'Enter') {
e.preventDefault()
filtered[clampedHi]?.run()
} else if (e.key === 'Escape') {
e.stopPropagation()
onClose()
}
}
return (
<>
<div
className="fixed inset-0 z-40"
style={{ background: 'var(--scrim)' }}
onClick={onClose}
aria-hidden="true"
/>
<div
ref={dialogRef}
role="dialog"
aria-modal="true"
aria-label="Command palette"
className="fixed left-1/2 top-[12vh] z-50 w-[min(620px,94vw)] -translate-x-1/2 overflow-hidden rounded-lg border border-border bg-bg-popover shadow-[var(--sh-pop)]"
onKeyDown={onKeyDown}
>
<input
role="combobox"
aria-expanded="true"
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeId}
aria-label={placeholder}
value={query}
onChange={(e) => {
setQuery(e.target.value)
setHi(0)
}}
placeholder={placeholder}
className="h-12 w-full border-b border-border bg-transparent px-4 text-base text-text outline-none placeholder:text-text-subtle focus-visible:border-ring"
/>
<div id={listId} role="listbox" aria-label="Commands" className="max-h-[52vh] overflow-y-auto py-1">
{filtered.length === 0 && (
<div role="presentation" className="px-4 py-6 text-center text-sm text-text-muted">No results</div>
)}
{filtered.map((it, i) => (
<div
key={it.id}
id={optionId(i)}
role="option"
aria-selected={i === clampedHi}
onMouseMove={() => setHi(i)}
// Keep focus on the input when a row is clicked.
onMouseDown={(e) => e.preventDefault()}
onClick={() => it.run()}
className={cn(
'flex w-full cursor-pointer items-center gap-3 px-4 py-2 text-left text-sm',
i === clampedHi ? 'bg-bg ring-2 ring-inset ring-ring' : 'hover:bg-bg',
)}
>
<span className="shrink-0 rounded border border-border px-1.5 py-0.5 text-xs text-text-subtle">
{it.kind}
</span>
<span className="min-w-0 flex-1 truncate text-text">{it.label}</span>
{it.hint && <span className="shrink-0 text-xs text-text-subtle">{it.hint}</span>}
</div>
))}
</div>
</div>
</>
)
}