Skip to content

: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.

5.1 KB
Raw Blame
import { DependencyList } from 'react'

import { useEventListener } from 'lib/hooks/useEventListener'
import posthog from 'lib/posthog-typed'

import { HotKey } from '~/types'

export interface HotkeyInterface {
    action: (e: KeyboardEvent) => void
    disabled?: boolean
    // Indicates the "action" will handle the event and preventDefault should not be called
    willHandleEvent?: boolean
    // Run the action again on each OS key-repeat event while the key is held. Off by default so a
    // held key fires the action once; opt in for seek-style shortcuts that should repeat (arrow keys).
    allowRepeat?: boolean
}

export type HotkeysInterface = Partial<Record<HotKey, HotkeyInterface>>
/**
 * input boxes in the hovering toolbar do not have event target of input.
 * they are detected as for e.g.div#__POSTHOG_TOOLBAR__.ph-no-capture
 * see https://developer.mozilla.org/en-US/docs/Web/API/Event/composedPath
 * @param event
 * @param ignorableElements
 */
const isToolbarInput = (event: Event, ignorableElements: string[]): boolean => {
    const path = event.composedPath() || (event as any).path
    if (!path) {
        return false
    }

    const sourceElement = path[0] as HTMLElement
    const tagName = sourceElement.tagName || 'not an html element'
    return ignorableElements.includes(tagName.toLowerCase())
}

const exceptions = ['.hotkey-block', '.hotkey-block *']

// modifier vocabulary and order must stay in lockstep with shortcutLogic.tsx's pressedKeys,
// so the same chord reports the same `keybind` string from either mechanism
function formatTriggeredKeybind(event: KeyboardEvent, key: string): string {
    const parts: string[] = []
    if (event.metaKey) {
        parts.push('command')
    }
    if (event.ctrlKey) {
        parts.push('ctrl')
    }
    if (event.shiftKey) {
        parts.push('shift')
    }
    if (event.altKey) {
        parts.push('option')
    }
    parts.push(key)
    return parts.join('+')
}

/**
 *
 * @param hotkeys Hotkeys to listen to and actions to execute
 * @param deps List of dependencies for the hook
 */
export function useKeyboardHotkeys(hotkeys: HotkeysInterface, deps?: DependencyList): void {
    const IGNORE_INPUTS = ['input', 'textarea'] // Inputs in which hotkey events will be ignored

    useEventListener(
        'keydown',
        (event) => {
            const key = event.key

            // Ignore explicit hotkey exceptions
            if (exceptions.some((exception) => (event.target as Element)?.matches(exception))) {
                return
            }

            // Ignore typing on inputs (default behavior); except Esc key
            const isDOMInput =
                IGNORE_INPUTS.includes((event.target as HTMLElement).tagName.toLowerCase()) ||
                (event.target as HTMLElement).isContentEditable ||
                (event.target as HTMLElement).closest('.monaco-editor') !== null
            if (key !== 'Escape' && (isDOMInput || isToolbarInput(event, IGNORE_INPUTS))) {
                return
            }

            for (const relevantKey of Object.keys(hotkeys)) {
                const hotkey = hotkeys[relevantKey as HotKey]

                if (!hotkey || hotkey.disabled) {
                    continue
                }

                // Ignore if the key is pressed with a meta or control key (these are general browser commands; e.g. Cmd + R) if the action doesn't support it
                if (!hotkey.willHandleEvent && (event.metaKey || event.ctrlKey || event.altKey)) {
                    continue
                }
                const normalizedKey = (key === ' ' ? 'space' : key.toLowerCase()) as HotKey
                if (normalizedKey === relevantKey) {
                    if (!hotkey.willHandleEvent) {
                        event.preventDefault()
                    }
                    // Skip the action on held-key repeats unless the hotkey opts in. This stops a
                    // resting key from firing an action per OS repeat event (e.g. one server-side
                    // screenshot export per repeat for the replay player's "s" shortcut).
                    if (event.repeat && !hotkey.allowRepeat) {
                        break
                    }
                    // don't capture: when posthog is uninitialized (the toolbar bundle on customer sites — capturing
                    // there only warns in the customer's console), on held-key repeats (seeking by holding an arrow
                    // counts once), or on ctrl/meta chords reaching willHandleEvent actions (they treat those as
                    // browser shortcuts and no-op)
                    if (
                        posthog.__loaded &&
                        !event.repeat &&
                        !(hotkey.willHandleEvent && (event.metaKey || event.ctrlKey))
                    ) {
                        posthog.capture('keybind triggered', {
                            keybind: formatTriggeredKeybind(event, normalizedKey),
                            mechanism: 'hotkey',
                        })
                    }
                    hotkey.action(event)
                    break
                }
            }
        },
        undefined,
        [hotkeys, ...(deps || [])]
    )
}