본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

단축키 (Hotkeys)

원문 보기 위키 갱신

키보드 단축키, 시퀀스와 스코프를 등록하고 다시 읽어서 커맨드 팔레트를 만드는 데 사용하는 유틸리티예요.

출처: 문서

본문

설정 (Setup)

useHotkey로 단축키를 등록하세요. document에서 리스닝하며 언마운트 시 정리합니다.

import { useFormatHotkey, useHotkey } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import styles from 'styles/hotkeys.module.css'

export const Basic = () => {
  const [count, setCount] = useState(0)
  const formatHotkey = useFormatHotkey()

  useHotkey({ hotkey: 'mod+K', action: () => setCount((value) => value + 1) })

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>
        Press <kbd className={styles.Kbd}>{formatHotkey('mod+K')}</kbd> anywhere on this page
      </p>
      <div className={styles.Metric}>
        <span className={styles.MetricValue}>{count}</span>
        <span className={styles.MetricLabel}>{count === 1 ? 'time' : 'times'}</span>
      </div>
    </div>
  )
}

mod는 macOS에서 Command로, 그 외에는 Control로 해석되므로 바인딩을 한 번만 작성하면 됩니다.

예제 (Examples)

여러 단축키 (Multiple shortcuts)

useHotkeys는 배열을 받는데, 목록이 데이터에서 오는 경우에 유용합니다. 각 커맨드는 hotkey와 action이 필요해요.

import { useFormatHotkey, useHotkeys, usePlatform } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import styles from 'styles/hotkeys.module.css'

const commands = [
  { id: 'save', hotkey: 'mod+S', label: 'Save', category: 'File' },
  { id: 'undo', hotkey: 'mod+Z', label: 'Undo', category: 'Edit' },
  { id: 'redo', hotkey: 'mod+shift+Z', label: 'Redo', category: 'Edit' },
]

export const Multiple = () => {
  const [lastFired, setLastFired] = useState<string | null>(null)
  const platform = usePlatform()
  const formatHotkey = useFormatHotkey()

  useHotkeys({ commands: commands.map((command) => ({ ...command, action: () => setLastFired(command.id) })) })

  return (
    <div className={styles.Panel}>
      <div className={styles.Toolbar}>
        <span className={styles.SectionLabel}>Detected platform</span>
        <span className={styles.Badge}>{platform}</span>
      </div>
      <ul className={styles.List}>
        {commands.map((command) => (
          <li className={styles.Row} key={command.id} data-fired={command.id === lastFired ? '' : undefined}>
            <span>{command.label}</span>
            <kbd className={styles.Kbd} data-active={command.id === lastFired ? '' : undefined}>
              {formatHotkey(command.hotkey)}
            </kbd>
          </li>
        ))}
      </ul>
    </div>
  )
}

시퀀스 (Sequences)

키를 하나 누른 뒤 다른 키를 누르는 방식이에요. G > H는 두 키 모두 시퀀스 창 안에 들어올 때만 발동됩니다.

import { useHotkeys } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import styles from 'styles/hotkeys.module.css'

const routes = [
  { id: 'home', hotkey: 'G > H', keys: ['G', 'H'], label: 'Home' },
  { id: 'settings', hotkey: 'G > S', keys: ['G', 'S'], label: 'Settings' },
]

export const Sequence = () => {
  const [page, setPage] = useState('home')

  useHotkeys({
    commands: routes.map((route) => ({ id: route.id, hotkey: route.hotkey, action: () => setPage(route.id) })),
  })

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>Press the keys in order, one after the other</p>
      <ul className={styles.List}>
        {routes.map((route) => (
          <li className={styles.Row} key={route.id} data-fired={route.id === page ? '' : undefined}>
            <span>{route.label}</span>
            <span className={styles.KeyStrip}>
              {route.keys.map((key, index) => (
                <kbd className={styles.Kbd} key={key} data-active={route.id === page ? '' : undefined}>
                  {index > 0 ? `then ${key}` : key}
                </kbd>
              ))}
            </span>
          </li>
        ))}
      </ul>
      <div className={styles.Metric}>
        <span className={styles.MetricLabel}>Current page</span>
        <span className={styles.Badge} data-state="active">
          {page}
        </span>
      </div>
    </div>
  )
}

시퀀스 타임아웃 (Sequence timeout)

sequenceTimeoutMs가 그 창을 설정하며, 기본값은 1초입니다. 더 오래 기다리면 시퀀스는 발동 없이 리셋됩니다.

import { createHotkeyStore, useHotkey } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import styles from 'styles/hotkeys.module.css'

const TIMEOUT_MS = 600

const store = createHotkeyStore({ sequenceTimeoutMs: TIMEOUT_MS })

export const SequenceTimeout = () => {
  const [completed, setCompleted] = useState(0)

  useHotkey({ hotkey: 'G > H', action: () => setCompleted((value) => value + 1), store })
  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>
        Press <kbd className={styles.Kbd}>G</kbd> then <kbd className={styles.Kbd}>H</kbd>. The second key must land
        within {TIMEOUT_MS}ms, otherwise the sequence resets and nothing fires.
      </p>

      <div className={styles.Metric}>
        <span className={styles.MetricValue}>{completed}</span>
        <span className={styles.MetricLabel}>{completed === 1 ? 'completion' : 'completions'}</span>
      </div>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>sequenceTimeoutMs</span>
        <span className={styles.Badge}>{TIMEOUT_MS}ms</span>
      </div>
    </div>
  )
}

스코프 (Scopes)

scopes: ['editor']를 가진 커맨드는 해당 스코프가 활성 상태일 때만 발동합니다. store.setScope는 한 번에 단축키의 전체 세트를 바꿉니다.

import { createHotkeyStore, useFormatHotkey, useHotkeys } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/hotkeys.module.css'

const commands = [
  { id: 'bold', hotkey: 'mod+B', label: 'Bold', scope: 'editor' },
  { id: 'print', hotkey: 'mod+P', label: 'Print', scope: 'reader' },
]

const store = createHotkeyStore({ activeScopes: ['editor'] })

export const Scopes = () => {
  const formatHotkey = useFormatHotkey()
  const [scope, setScope] = useState('editor')
  const [fired, setFired] = useState<string | null>(null)

  useHotkeys({
    commands: commands.map((command) => ({
      id: command.id,
      hotkey: command.hotkey,
      scopes: [command.scope],
      action: () => setFired(command.id),
    })),
    store,
  })

  const toggle = () => {
    const next = scope === 'editor' ? 'reader' : 'editor'
    setScope(next)
    setFired(null)
    store.setScope(next)
  }

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>Only commands in the active scope respond</p>

      <div className={styles.Toolbar}>
        <button type="button" className={button.Root} onClick={toggle}>
          Switch scope
        </button>
        <span className={styles.Badge} data-state="active">
          {scope}
        </span>
      </div>

      <ul className={styles.List}>
        {commands.map((command) => {
          const active = command.scope === scope
          return (
            <li className={styles.Row} key={command.id} data-fired={command.id === fired ? '' : undefined}>
              <span style={{ opacity: active ? 1 : 0.45 }}>
                {command.label} <span className={styles.MetricLabel}>· {command.scope}</span>
              </span>
              <kbd className={styles.Kbd} data-active={command.id === fired ? '' : undefined}>
                {formatHotkey(command.hotkey)}
              </kbd>
            </li>
          )
        })}
      </ul>
    </div>
  )
}

폼 필드 (Form fields)

input, textarea 또는 select에서 타이핑하는 동안 단일 키는 무시됩니다. 수정자(modifier)가 있는 단축키는 여전히 발동하는데, 텍스트 필드에서 Cmd+S가 여전히 저장을 의미하기 때문이에요. 단일 키는 options: { enableOnFormTags: true }로 다시 활성화할 수 있습니다.

import { useFormatHotkey, useHotkeys } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import styles from 'styles/hotkeys.module.css'

export const FormFields = () => {
  const [log, setLog] = useState<string | null>(null)
  const formatHotkey = useFormatHotkey()

  useHotkeys({
    commands: [
      { hotkey: 'S', action: () => setLog('Search (single key)') },
      { hotkey: 'mod+S', action: () => setLog('Save (modifier)') },
      {
        hotkey: 'P',
        action: () => setLog('Preview (opted in)'),
        options: { enableOnFormTags: true },
      },
    ],
  })

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>Try each shortcut outside the field, then again with the field focused</p>

      <input className={styles.Input} placeholder="Type here…" aria-label="Note" />

      <ul className={styles.List}>
        <li className={styles.Row}>
          <span>
            Search <span className={styles.MetricLabel}>· ignored while typing</span>
          </span>
          <kbd className={styles.Kbd}>{formatHotkey('S')}</kbd>
        </li>
        <li className={styles.Row}>
          <span>
            Save <span className={styles.MetricLabel}>· modifiers always fire</span>
          </span>
          <kbd className={styles.Kbd}>{formatHotkey('mod+S')}</kbd>
        </li>
        <li className={styles.Row}>
          <span>
            Preview <span className={styles.MetricLabel}>· enableOnFormTags</span>
          </span>
          <kbd className={styles.Kbd}>{formatHotkey('P')}</kbd>
        </li>
      </ul>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Last fired</span>
        <span className={styles.Badge} data-state={log ? 'active' : undefined}>
          {log ?? 'nothing yet'}
        </span>
      </div>
    </div>
  )
}

충돌 (Conflicts)

두 커맨드가 같은 단축키를 차지하면 conflictBehavior가 결정합니다. warn이 기본이며 둘 다 유지하고, replace는 먼저 등록된 것을 버리며, allow는 조용히 둘 다 유지하고, error는 두 번째 것을 거부합니다.

import {
  type ConflictBehavior,
  type HotkeyStore,
  createHotkeyStore,
  useHotkeyRegistrations,
  useHotkeys,
} from '@ark-ui/react/hotkeys'
import { useMemo, useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/hotkeys.module.css'

const BEHAVIORS: ConflictBehavior[] = ['warn', 'replace', 'allow']

const Demo = ({ store }: { store: HotkeyStore }) => {
  const [fired, setFired] = useState<string[]>([])

  useHotkeys({
    commands: [
      { id: 'first', hotkey: 'mod+K', action: () => setFired((log) => [...log, 'First']), label: 'First' },
      { id: 'second', hotkey: 'mod+K', action: () => setFired((log) => [...log, 'Second']), label: 'Second' },
    ],
    store,
  })

  const commands = useHotkeyRegistrations({ store })

  return (
    <>
      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Registered on mod+K</span>
        <div className={styles.KeyStrip}>
          {commands.length === 0 ? (
            <span className={styles.Placeholder}>none</span>
          ) : (
            commands.map((command) => (
              <span className={styles.Badge} key={command.id}>
                {command.label}
              </span>
            ))
          )}
        </div>
      </div>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Fired on last press</span>
        <span className={styles.Badge} data-state={fired.length > 0 ? 'active' : undefined}>
          {fired.slice(-2).join(' + ') || 'nothing yet'}
        </span>
      </div>
    </>
  )
}

export const Conflicts = () => {
  const [behavior, setBehavior] = useState<ConflictBehavior>('warn')

  // Conflict behavior is fixed when the store is created, so switching it makes a new store.
  const store = useMemo(() => createHotkeyStore({ conflictBehavior: behavior }), [behavior])

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>
        Two commands claim the same shortcut. Pick how the store resolves it, then press it.
      </p>

      <div className={styles.Toolbar}>
        {BEHAVIORS.map((value) => (
          <button
            type="button"
            className={button.Root}
            key={value}
            onClick={() => setBehavior(value)}
            data-selected={value === behavior ? '' : undefined}
          >
            {value}
          </button>
        ))}
      </div>

      <Demo key={behavior} store={store} />
    </div>
  )
}

키 상태 (Key state)

usePressedKeys는 현재 눌려 있는 키들을 반환하고, useIsKeyPressed는 하나의 키에 대해 답합니다. Shift로 선택 영역을 확장하는 것처럼 누른 키가 인터랙션의 의미를 바꿀 때 이것을 사용하세요.

import { useHotkey, useIsKeyPressed, usePressedKeys } from '@ark-ui/react/hotkeys'
import styles from 'styles/hotkeys.module.css'

export const KeyState = () => {
  useHotkey({ hotkey: 'mod+K', action: () => {} })

  const pressedKeys = usePressedKeys()
  const isShiftPressed = useIsKeyPressed({ hotkey: 'shift' })

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>Hold any key to see it tracked live</p>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Currently pressed</span>
        <div className={styles.KeyStrip}>
          {pressedKeys.length === 0 ? (
            <span className={styles.Placeholder}>nothing</span>
          ) : (
            pressedKeys.map((key) => (
              <kbd className={styles.Kbd} key={key} data-active="">
                {key}
              </kbd>
            ))
          )}
        </div>
      </div>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Shift</span>
        <span className={styles.Badge} data-state={isShiftPressed ? 'active' : undefined}>
          <span className={styles.Dot} data-pulse={isShiftPressed ? '' : undefined} />
          {isShiftPressed ? 'Precision mode' : 'Hold Shift for precision'}
        </span>
      </div>
    </div>
  )
}

단축키 녹음 (Recording a shortcut)

useHotkeyRecorder는 사용자가 누르는 것을 캡처하여 "클릭하여 다시 바인딩" 설정에 사용합니다. Escape는 취소, Backspace는 지우며, 코드와 시퀀스 모두 동작합니다.

import { useHotkeyRecorder } from '@ark-ui/react/hotkeys'
import { useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/hotkeys.module.css'

export const Recorder = () => {
  const [binding, setBinding] = useState<string | null>(null)
  const [lastEvent, setLastEvent] = useState<string | null>(null)

  const recorder = useHotkeyRecorder({
    onRecord: (hotkey) => {
      setBinding(hotkey.display)
      setLastEvent('recorded')
    },
    onCancel: () => setLastEvent('cancelled'),
    onClear: () => {
      setBinding(null)
      setLastEvent('cleared')
    },
  })

  return (
    <div className={styles.Panel}>
      <p className={styles.Hint}>
        Click record, then press a shortcut. <kbd className={styles.Kbd}>Esc</kbd> cancels,{' '}
        <kbd className={styles.Kbd}>Backspace</kbd> clears.
      </p>

      <div className={styles.Toolbar}>
        <button type="button" className={button.Root} onClick={() => recorder.start()} disabled={recorder.recording}>
          {recorder.recording ? 'Listening…' : 'Record shortcut'}
        </button>
        {recorder.recording && (
          <span className={styles.Badge} data-state="active">
            <span className={styles.Dot} data-pulse="" />
            {recorder.value?.display ?? 'Press a key'}
          </span>
        )}
      </div>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Bound to</span>
        <div className={styles.KeyStrip}>
          {binding ? (
            <kbd className={styles.Kbd} data-active="">
              {binding}
            </kbd>
          ) : (
            <span className={styles.Placeholder}>nothing yet</span>
          )}
        </div>
      </div>

      <div className={styles.Section}>
        <span className={styles.SectionLabel}>Last event</span>
        <span className={styles.Badge}>{lastEvent ?? 'none'}</span>
      </div>
    </div>
  )
}

커맨드 팔레트 (Command palette)

useHotkeyRegistrations는 메타데이터와 함께 등록된 모든 커맨드를 반환하므로, 팔레트는 동기화할 두 번째 목록이 아니라 레지스트리의 뷰가 됩니다.

import { Combobox, useListCollection } from '@ark-ui/react/combobox'
import { Dialog } from '@ark-ui/react/dialog'
import {
  createHotkeyStore,
  useFormatHotkey,
  useHotkey,
  useHotkeyRegistrations,
  useHotkeys,
} from '@ark-ui/react/hotkeys'
import { useFilter } from '@ark-ui/react/locale'
import { Portal } from '@ark-ui/react/portal'
import { CornerDownLeftIcon, SearchIcon } from 'lucide-react'
import { useEffect, useState } from 'react'
import button from 'styles/button.module.css'
import styles from 'styles/command-palette.module.css'

// Its own store, so the palette lists only the commands registered here.
const store = createHotkeyStore()

export const CommandPalette = () => {
  const [open, setOpen] = useState(false)
  const [lastRun, setLastRun] = useState<string | null>(null)

  useHotkeys({
    commands: [
      {
        id: 'save',
        hotkey: 'mod+S',
        action: () => setLastRun('Save file'),
        label: 'Save file',
        category: 'File',
        keywords: ['write', 'persist'],
      },
      {
        id: 'theme',
        hotkey: 'mod+shift+D',
        action: () => setLastRun('Toggle theme'),
        label: 'Toggle theme',
        category: 'View',
        keywords: ['dark', 'light', 'appearance'],
      },
      {
        id: 'undo',
        hotkey: 'mod+Z',
        action: () => setLastRun('Undo'),
        label: 'Undo',
        category: 'Edit',
        keywords: ['revert', 'back'],
      },
    ],
    store,
  })

  const formatHotkey = useFormatHotkey()
  const commands = useHotkeyRegistrations({ store })
  const { contains } = useFilter({ sensitivity: 'base' })

  const { collection, filter, set } = useListCollection({
    initialItems: commands,
    itemToString: (item) => item.label ?? item.id,
    itemToValue: (item) => item.id,
    groupBy: (item) => item.category ?? 'Other',
    filter: (itemText, filterText, item) =>
      contains(itemText, filterText) || item.keywords.some((keyword) => contains(keyword, filterText)),
  })

  useEffect(() => {
    set([...commands])
  }, [commands, set])

  const openPalette = () => setOpen(true)

  useHotkey({
    hotkey: 'mod+shift+P',
    action: openPalette,
    label: 'Open command palette',
    category: 'General',
    store,
  })

  const handleValueChange = (details: Combobox.ValueChangeDetails) => {
    const selected = details.items.at(0)
    if (!selected) return
    setOpen(false)
    selected.action(new KeyboardEvent('keydown'))
  }

  return (
    <div>
      <button type="button" className={button.Root} onClick={openPalette}>
        Open palette ({formatHotkey('mod+shift+P')})
      </button>
      <p>Last run: {lastRun ?? 'nothing yet'}</p>

      <Dialog.Root
        lazyMount
        unmountOnExit
        open={open}
        onOpenChange={(details) => setOpen(details.open)}
        onExitComplete={() => filter('')}
      >
        <Portal>
          <Dialog.Backdrop className={styles.Backdrop} />
          <Dialog.Positioner className={styles.Positioner}>
            <Dialog.Content className={styles.Content} aria-label="Command palette">
              <Combobox.Root
                className={styles.Root}
                collection={collection}
                open
                disableLayer
                inputBehavior="autohighlight"
                selectionBehavior="preserve"
                loopFocus={false}
                placeholder="Search commands…"
                onInputValueChange={(details) => filter(details.inputValue)}
                onValueChange={handleValueChange}
              >
                <Combobox.Control className={styles.Control}>
                  <SearchIcon />
                  <Combobox.Input className={styles.Input} />
                </Combobox.Control>
                <Combobox.Content className={styles.Content_list}>
                  {collection.size === 0 ? (
                    <div className={styles.Empty}>No commands found</div>
                  ) : (
                    collection.group().map(([category, group]) => (
                      <Combobox.ItemGroup className={styles.ItemGroup} key={category}>
                        <Combobox.ItemGroupLabel className={styles.ItemGroupLabel}>{category}</Combobox.ItemGroupLabel>
                        {group.map((item) => (
                          <Combobox.Item className={styles.Item} key={item.id} item={item} persistFocus>
                            <Combobox.ItemText className={styles.ItemText}>{item.label ?? item.id}</Combobox.ItemText>
                            <kbd className={styles.Shortcut}>{formatHotkey(item.hotkey)}</kbd>
                          </Combobox.Item>
                        ))}
                      </Combobox.ItemGroup>
                    ))
                  )}
                </Combobox.Content>
              </Combobox.Root>
              <div className={styles.Footer}>
                <span className={styles.FooterHint}>
                  <CornerDownLeftIcon size={12} /> to run
                </span>
                <span className={styles.FooterHint}>esc to close</span>
              </div>
            </Dialog.Content>
          </Dialog.Positioner>
        </Portal>
      </Dialog.Root>
    </div>
  )
}

label, category, keywords로 한 번 등록한 뒤 category로 그룹핑하고, keywords로 검색하며, 선택 시 item.action을 호출합니다. 여기서 "dark"를 입력하면 라벨에 "dark"가 없음에도 "Toggle theme"을 찾는 것을 볼 수 있어요.

가이드 (Guides)

단축키 표시 (Displaying a shortcut)

useFormatHotkey는 현재 플랫폼에 바인딩된 포매터를 반환하므로 mod+K가 macOS에서는 ⌘ K로, 그 외에는 Ctrl K로 렌더링됩니다.

const formatHotkey = useFormatHotkey()

return <kbd>{formatHotkey('mod+K')}</kbd>

@zag-js/hotkeys의 formatHotkey는 컴포넌트 밖에서만 사용하세요. 컴포넌트 안에서는 렌더링 중에 플랫폼을 읽기 때문에, 서버가 Ctrl K라 하고 브라우저가 ⌘ K라 할 때 하이드레이션에서 불일치가 생깁니다. 플랫폼 자체에 대해서는 usePlatform이 mac, windows, linux를 반환합니다.

직접 만든 스토어 사용 (Using your own store)

한 개가 없으면 모든 훅이 공유되는 기본 스토어에 등록됩니다. createHotkeyStore로 직접 만든 스토어를 만들어 어떤 훅에도 전달하면 커맨드 세트를 격리하거나, 모두에 기본값을 설정하거나, 활성 스코프를 제어할 수 있어요.

const store = createHotkeyStore({
  activeScopes: ['editor'],
  conflictBehavior: 'replace',
  sequenceTimeoutMs: 800,
})

useHotkeys({ commands, store })
useHotkey({ hotkey: 'mod+S', action: save, store })

스토어는 컴포넌트 밖에서 만들거나 메모이즈하세요. 렌더링 중에 만들어진 것은 매 렌더링마다 다시 만들어져 등록이 사라집니다.

커맨드 팔레트가 이를 사용하는 일반적인 이유예요. 팔레트에 자체 스토어를 주고 useHotkeyRegistrations({ store })를 사용하면 페이지의 모든 것이 아니라 해당 스토어에 등록된 커맨드만 반환합니다.

활성화와 비활성화 (Enabling and disabling)

enabled를 boolean 또는 함수로 전달하세요. 함수는 키가 발동할 때마다 다시 평가되므로, 재등록 없이 현재 상태를 읽습니다.

useHotkey({ hotkey: 'mod+S', action: save, enabled: () => !isReadOnly })

키 릴리스에 반응하기 (Reacting to a key release)

options: { eventType: 'keyup' }는 눌렀을 때가 아니라 놓았을 때 발동합니다. 같은 키의 keydown 커맨드와 짝지어 push-to-talk를 구현할 수 있어요.

API 레퍼런스 (API Reference)

createHotkeyStore

Props

activeScopes Type: string | string[] Required: false Default Value: ['*'] Description: 활성 상태로 시작하는 스코프. 활성 스코프에 있는 커맨드만 발동합니다.

conflictBehavior Type: 'warn' | 'error' | 'replace' | 'allow' Required: false Default Value: 'warn' Description: 두 커맨드가 같은 hotkey를 등록할 때 할 일. warn은 둘 다 유지하고 로그를 남기며, replace는 먼저 등록된 것을 버리고, allow는 조용히 둘 다 유지하며, error는 두 번째 것을 거부합니다.

defaultOptions Type: HotkeyOptions Required: false Default Value: undefined Description: 이 스토어에 등록되는 모든 커맨드에 적용되는 옵션. 커맨드별 옵션이 이를 덮어씁니다.

sequenceTimeoutMs Type: number Required: false Default Value: 1000 Description: G > H 같은 시퀀스가 다음 키를 기다린 후 리셋될 때까지의 시간.

returns Type: HotkeyStore Required: false Default Value: undefined Description: 스토어. 어떤 훅에도 store로 전달하며 안정적으로 유지하세요. 렌더링 중에 만들어진 것은 매 렌더링마다 다시 만들어져 등록이 사라지므로 컴포넌트 밖에서 만들거나 메모이즈하세요.

useHotkey

Props

props Type: UseHotkeyProps Required: true Default Value: undefined Description: 하나의 커맨드와 선택적인 store. UseHotkeysCommand의 모든 필드를 받습니다.

useHotkeys

Props

commands Type: UseHotkeysCommand[] Required: true Default Value: undefined Description: 등록할 커맨드들. 단일 객체 안에 전달되므로 전체 인자는 { commands, store, id }입니다.

store Type: HotkeyStore Required: false Default Value: undefined Description: 등록할 스토어. 이름을 지정하지 않은 모든 훅이 공유하는 스토어가 기본값입니다.

id Type: string Required: false Default Value: undefined Description: 고유 id를 설정하지 않은 커맨드에 생성되는 id의 접두사. 생략하면 하나가 생성됩니다.

UseHotkeysCommand

Props

id Type: string Required: false Default Value: undefined Description: 렌더링 사이에 커맨드를 식별합니다. 생략하면 훅 인스턴스 내 위치를 기준으로 하나가 생성되는데, 다른 곳에서 커맨드를 이름으로 지정할 필요가 없다면 충분합니다.

hotkey Type: string Required: true Default Value: undefined Description: 커맨드를 트리거하는 키 조합 또는 시퀀스.

action Type: (event: KeyboardEvent) => void Required: true Default Value: undefined Description: hotkey가 발동할 때 호출됩니다.

label Type: string Required: false Default Value: undefined Description: 사람이 읽을 수 있는 이름. useHotkeyRegistrations가 읽으므로 커맨드 팔레트가 렌더링할 수 있습니다.

description Type: string Required: false Default Value: undefined Description: 커맨드가 무엇을 하는지에 대한 더 긴 설명.

category Type: string Required: false Default Value: undefined Description: 커맨드 팔레트를 섹션으로 나누기 위한 그룹 이름.

keywords Type: string[] Required: false Default Value: undefined Description: 대체 검색어. 팔레트가 "Toggle theme"이라는 커맨드를 "dark"로 매칭하게 해줍니다.

scopes Type: string | string[] Required: false Default Value: '*' Description: 이 커맨드가 속한 스코프. 그중 하나가 활성일 때만 발동합니다.

enabled Type: boolean | (() => boolean) Required: false Default Value: true Description: 커맨드가 발동할 수 있는지 여부. 함수는 매 키 입력마다 다시 평가되므로 재등록 없이 현재 상태를 읽습니다.

options Type: HotkeyOptions Required: false Default Value: undefined Description: 커맨드별 동작. 프로바이더 defaultOptions를 덮어씁니다.

HotkeyOptions

Props

preventDefault Type: boolean Required: false Default Value: undefined Description: 액션을 실행하기 전에 이벤트에서 preventDefault()를 호출합니다.

stopPropagation Type: boolean Required: false Default Value: undefined Description: 액션을 실행하기 전에 이벤트에서 stopPropagation()을 호출합니다.

enableOnFormTags Type: boolean | ('input' | 'textarea' | 'select')[] Required: false Default Value: false Description: input, textarea 또는 select가 포커스를 가졌을 때 단일 키 단축키가 발동할지 여부. 수정자가 있는 단축키는 항상 발동합니다. 특정 태그를 선택하려면 배열을 전달하세요.

enableOnContentEditable Type: boolean Required: false Default Value: false Description: contenteditable 요소 안에서 단축키가 발동할지 여부.

capture Type: boolean Required: false Default Value: true Description: 캡처 단계에서 리스닝합니다.

requireReset Type: boolean Required: false Default Value: false Description: 누름당 한 번씩 발동합니다. 다시 발동하려면 키가 먼저 놓여져야 하므로 키 반복을 억제합니다.

eventType Type: 'keydown' | 'keyup' Required: false Default Value: 'keydown' Description: 눌렀을 때 발동할지 놓았을 때 발동할지. push-to-talk를 위해 같은 키의 keydown 커맨드와 keyup 커맨드를 짝지으세요.

target Type: Element | (() => Element | null) Required: false Default Value: undefined Description: 커맨드를 DOM 하위 트리로 제한합니다. 이벤트가 이 요소 안에서 발생할 때만 발동하며, 요소는 포커스를 포함해야 합니다. 매 이벤트마다 해석되며 null로 해석되면 건너뜁니다.

useHotkeyRegistrations

Props

store Type: HotkeyStore Required: false Default Value: undefined Description: 읽어올 스토어. 이름을 지정하지 않은 모든 훅이 공유하는 스토어가 기본값입니다.

returns Type: HotkeyCommand[] Required: false Default Value: undefined Description: label, category, keywords와 해석된 hotkey와 함께 현재 스토어에 등록된 모든 커맨드. 커맨드가 추가되거나 제거될 때 다시 읽으므로 커맨드 팔레트가 동기화할 두 번째 목록이 아니라 레지스트리의 뷰가 될 수 있게 합니다.

useHotkeyStore

Props

returns Type: HotkeyStore Required: false Default Value: undefined Description: 전달한 스토어 또는 공유되는 기본 스토어. 어떤 커맨드가 활성인지 바꾸려면 setScope, addScope, removeScope, toggleScope를 사용하고, 조합을 직접 테스트하려면 isPressed를 사용하세요.

usePressedKeys

Props

store Type: HotkeyStore Required: false Default Value: undefined Description: 읽어올 스토어. 이름을 지정하지 않은 모든 훅이 공유하는 스토어가 기본값입니다.

returns Type: string[] Required: false Default Value: undefined Description: 현재 눌려 있는 키들. Shift로 선택 영역을 확장하는 것처럼 누른 키가 인터랙션의 의미를 바꿀 때 사용하세요.

useIsKeyPressed

Props

hotkey Type: string Required: true Default Value: undefined Description: 감시할 키 또는 조합. 단일 객체 안에 전달되므로 전체 인자는 { hotkey, store }입니다.

store Type: HotkeyStore Required: false Default Value: undefined Description: 읽어올 스토어. 이름을 지정하지 않은 모든 훅이 공유하는 스토어가 기본값입니다.

returns Type: boolean Required: false Default Value: undefined Description: 해당 키 또는 조합이 현재 눌려 있는지 여부.

usePlatform

Props

returns Type: Platform Required: false Default Value: undefined Description: 현재 플랫폼, 'mac', 'windows' 또는 'linux' 중 하나. 마운트 후에 해석되므로 서버와 클라이언트가 같은 마크업을 렌더링합니다.

useFormatHotkey

Props

returns Type: (hotkey: string, options?: HotkeyFormatOptions) => string Required: false Default Value: undefined Description: 현재 플랫폼에 바인딩된 포매터로, mod+K가 macOS에서는 ⌘ K로, 그 외에는 Ctrl K로 렌더링됩니다. 컴포넌트 안에서 formatHotkey를 직접 import하는 것보다 이것을 선호하세요. 직접 import하면 렌더링 중에 플랫폼을 읽어 하이드레이션에서 불일치가 생깁니다.

useHotkeyRecorder

Props

props Type: UseHotkeyRecorderProps Required: false Default Value: undefined Description: onRecord, onCancel, onClear, formatOptions와 sequenceTimeoutMs를 받습니다.

returns Type: UseHotkeyRecorderReturn Required: false Default Value: undefined Description: 아래에서 설명하는 리코더 핸들.

UseHotkeyRecorderReturn

Props

recording Type: boolean Required: false Default Value: undefined Description: 리코더가 현재 키 이벤트를 리스닝하고 있는지 여부.

value Type: RecordedHotkey | null Required: false Default Value: undefined Description: 지금까지 기록된 hotkey. value는 원시 문자열이고, display는 플랫폼 포맷된 문자열입니다.

start Type: () => void Required: false Default Value: undefined Description: 키 이벤트 리스닝을 시작합니다.

stop Type: () => void Required: false Default Value: undefined Description: 리스닝을 멈추고 기록된 hotkey를 유지합니다.

cancel Type: () => void Required: false Default Value: undefined Description: 리스닝을 멈추고 기록된 hotkey를 버립니다. Escape로도 트리거됩니다.

clear Type: () => void Required: false Default Value: undefined Description: 기록된 hotkey를 지웁니다. Backspace 또는 Delete로도 트리거됩니다.

더 알아보기 (Learn more)