:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import { useActions } from 'kea'
import { useCallback, useEffect, useRef, useState } from 'react'
import { isMac } from 'lib/utils/dom'
import { ShortcutType, shortcutLogic } from './shortcutLogic'
const IS_MAC = isMac()
export function convertPlatformKeybind(keybind: string[]): string[] {
return keybind.map((key) => (!IS_MAC && key === 'command' ? 'ctrl' : key))
}
export function convertPlatformKeybinds(keybinds: string[][]): string[][] {
return keybinds.map(convertPlatformKeybind)
}
interface UseShortcutOptionsBase {
/** Unique identifier for the shortcut */
name: string
/** Keybind(s) - use 'command' for Cmd/Ctrl. Multiple arrays = alternative keybinds */
keybind: string[][]
/** Description of what the shortcut does */
intent: string
/** Scope: 'global' or a specific Scene key */
scope?: ShortcutType['scope']
/** When true, shortcut is not registered */
disabled?: boolean
ignoreInEditable?: boolean
/** Higher priority items appear first in their group. Default: 0 */
priority?: number
}
interface UseShortcutOptionsWithRef extends UseShortcutOptionsBase {
/** 'click' triggers element.click(), 'focus' triggers element.focus() */
interaction: 'click' | 'focus'
/** Optional: use your own ref instead of the one returned by the hook */
externalRef?: React.RefObject<HTMLElement>
callback?: never
}
interface UseShortcutOptionsWithCallback extends UseShortcutOptionsBase {
/** 'function' calls your callback directly - no ref needed */
interaction: 'function'
/** The function to call when the shortcut is triggered */
callback: () => void
externalRef?: never
}
export type UseShortcutOptions = UseShortcutOptionsWithRef | UseShortcutOptionsWithCallback
export interface UseShortcutReturn<T extends HTMLElement> {
/** Object ref - use this if you just need a simple ref */
ref: React.RefObject<T>
/** Callback ref - use this if you need to know when the element mounts (e.g., for conditional rendering) */
callbackRef: (node: T | null) => void
}
/**
* Hook to register a keyboard shortcut that triggers an action.
*
* There are two modes:
*
* **1. Element interaction (click/focus)** - triggers click() or focus() on an element
* ```tsx
* // Simple: use the returned ref
* const { ref } = useShortcut({
* name: 'open-search',
* keybind: [['command', 'k']],
* intent: 'Open search',
* interaction: 'click',
* })
* return <button ref={ref}>Search</button>
*
* // Or bring your own ref
* const myRef = useRef<HTMLButtonElement>(null)
* useShortcut({
* name: 'open-search',
* keybind: [['command', 'k']],
* intent: 'Open search',
* interaction: 'click',
* externalRef: myRef,
* })
* return <button ref={myRef}>Search</button>
* ```
*
* **2. Function callback** - calls a function directly, no element needed
* ```tsx
* useShortcut({
* name: 'toggle-theme',
* keybind: [['command', 'd']],
* intent: 'Toggle dark mode',
* interaction: 'function',
* callback: () => toggleTheme(),
* })
* // No ref needed - returned ref/callbackRef can be ignored
* ```
*
* **When to use `ref` vs `callbackRef`:**
* - `ref` (object ref): Use for most cases. Simple to attach.
* - `callbackRef`: Use when the element renders conditionally or you need
* to know exactly when it mounts. The shortcut won't register until
* the element exists in the DOM.
*
* **Multiple keybinds:**
* ```tsx
* keybind: [['command', 'k'], ['command', 'shift', 'k']] // Either triggers it
* ```
*/
export function useShortcut<T extends HTMLElement = HTMLElement>(options: UseShortcutOptions): UseShortcutReturn<T> {
const {
name,
keybind,
intent,
interaction,
scope = 'global',
disabled = false,
ignoreInEditable = false,
priority,
} = options
const internalRef = useRef<T>(null)
const [isRefReady, setIsRefReady] = useState(false)
const { registerShortcut, unregisterShortcut } = useActions(shortcutLogic)
const externalRef = options.interaction !== 'function' ? options.externalRef : undefined
const callback = options.interaction === 'function' ? options.callback : undefined
// Keep a ref to the callback to avoid re-registering on every render
// This way, the latest callback is always called and callers
// don't need to remember to memoize it
const callbackFnRef = useRef(callback)
callbackFnRef.current = callback
const ref = (externalRef as React.RefObject<T>) ?? internalRef
const callbackRef = useCallback((node: T | null) => {
;(internalRef as React.MutableRefObject<T | null>).current = node
setIsRefReady(!!node)
}, [])
useEffect(() => {
if (disabled) {
return
}
if (interaction === 'function' && callbackFnRef.current) {
const platformAgnosticKeybinds = convertPlatformKeybinds(keybind)
registerShortcut({
name,
keybind: platformAgnosticKeybinds,
callback: () => callbackFnRef.current?.(),
intent,
interaction: 'function',
scope,
priority,
ignoreInEditable,
})
} else if (isRefReady && ref.current && interaction !== 'function') {
const platformAgnosticKeybinds = convertPlatformKeybinds(keybind)
registerShortcut({
name,
keybind: platformAgnosticKeybinds,
ref: ref as React.RefObject<HTMLElement>,
intent,
interaction,
scope,
priority,
ignoreInEditable,
})
}
return () => {
unregisterShortcut(name)
}
// oxlint-disable-next-line react-hooks/exhaustive-deps
}, [
isRefReady,
name,
intent,
interaction,
scope,
disabled,
ignoreInEditable,
ref,
priority,
registerShortcut,
unregisterShortcut,
])
return { ref, callbackRef }
}