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.

13.8 KB
Raw Blame
import { MakeLogicType, actions, afterMount, beforeUnmount, kea, path, reducers, selectors } from 'kea'

import { IconKeyboard } from '@posthog/icons'

import { SearchItem } from 'lib/components/Search/searchItems'
import posthog from 'lib/posthog-typed'
import { isMac } from 'lib/utils/dom'
import { Scene } from 'scenes/sceneTypes'

import { RenderKeybind } from './RenderKeybind'

const IS_MAC = isMac()
const COMMAND_OR_CTRL = IS_MAC ? 'command' : 'ctrl'

const DISABLED_SHORTCUTS_KEY = 'posthog-disabled-shortcuts'

/** These open search or the SQL editor, so listing them in search only repeats what the palette is for. */
const HIDDEN_FROM_SEARCH = new Set(['Search', 'SQLEditor'])

function loadDisabledShortcuts(): string[] {
    try {
        const stored = localStorage.getItem(DISABLED_SHORTCUTS_KEY)
        return stored ? JSON.parse(stored) : []
    } catch {
        return []
    }
}

function saveDisabledShortcuts(names: string[]): void {
    localStorage.setItem(DISABLED_SHORTCUTS_KEY, JSON.stringify(names))
}

interface ShortcutBase {
    name: string
    keybind: string[][]
    intent: string
    scope?: 'global' | keyof typeof Scene
    ignoreInEditable?: boolean
    /** Higher priority items appear first in their group. Default: 0 */
    priority?: number
}

interface ShortcutWithRef extends ShortcutBase {
    ref: React.RefObject<HTMLElement>
    interaction: 'click' | 'focus'
    callback?: never
}

interface ShortcutWithCallback extends ShortcutBase {
    callback: () => void
    interaction: 'function'
    ref?: never
}

export type ShortcutType = ShortcutWithRef | ShortcutWithCallback

function isSequenceKeybind(keybind: string[]): boolean {
    return keybind.includes('then')
}

function isSingleKeyKeybind(keybind: string[]): boolean {
    return keybind.length === 1 && !['command', 'option', 'shift', 'ctrl'].includes(keybind[0])
}

function getSequenceKeys(keybind: string[]): string[] {
    return keybind.filter((key) => key !== 'then')
}

function formatKeybind(keybind: string[]): string {
    return isSequenceKeybind(keybind) ? getSequenceKeys(keybind).join(' then ') : keybind.join('+')
}

function triggerShortcut(shortcut: ShortcutType, triggeredKeybind: string[]): void {
    posthog.capture('keybind triggered', {
        name: shortcut.name,
        intent: shortcut.intent,
        keybind: formatKeybind(triggeredKeybind),
        interaction: shortcut.interaction,
        scope: shortcut.scope ?? 'global',
        mechanism: 'shortcut',
    })

    if (shortcut.interaction === 'click') {
        shortcut.ref.current?.click()
    } else if (shortcut.interaction === 'focus') {
        shortcut.ref.current?.focus()
    } else if (shortcut.interaction === 'function') {
        shortcut.callback()
    }
}

function isEditableElement(event: KeyboardEvent): boolean {
    // Use composedPath to get the actual target element, even through shadow DOM boundaries
    // This is necessary because event.target gets retargeted to the shadow host when events
    // bubble up from inside a shadow DOM (e.g., surveys product inputs)
    const path = event.composedPath()
    const target = path[0] as HTMLElement | null

    if (!target || !(target instanceof HTMLElement)) {
        return false
    }
    const tagName = target.tagName.toLowerCase()
    return (
        tagName === 'input' ||
        tagName === 'textarea' ||
        tagName === 'select' ||
        target.isContentEditable ||
        target.closest('.monaco-editor') !== null
    )
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface shortcutLogicValues {
    disabledShortcutNames: string[]
    registeredShortcuts: ShortcutType[]
    shortcutItems: SearchItem[]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface shortcutLogicActions {
    registerShortcut: (shortcut: ShortcutType) => {
        shortcut: ShortcutType
    }
    toggleShortcutDisabled: (name: string) => {
        name: string
    }
    unregisterShortcut: (name: string) => {
        name: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface shortcutLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        shortcutItems: (registeredShortcuts: ShortcutType[], disabledShortcutNames: string[]) => SearchItem[]
    }
}

export type shortcutLogicType = MakeLogicType<
    shortcutLogicValues,
    shortcutLogicActions,
    Record<string, any>,
    shortcutLogicMeta
>

export const shortcutLogic = kea<shortcutLogicType>([
    path(['lib', 'components', 'Shortcuts', 'shortcutLogic']),
    actions({
        registerShortcut: (shortcut: ShortcutType) => ({ shortcut }),
        unregisterShortcut: (name: string) => ({ name }),
        toggleShortcutDisabled: (name: string) => ({ name }),
    }),
    reducers({
        registeredShortcuts: [
            [] as ShortcutType[],
            {
                registerShortcut: (state, { shortcut }) => {
                    // Remove any existing shortcut with the same name, then add the new one
                    const filtered = state.filter((existing) => existing.name !== shortcut.name)
                    return [...filtered, shortcut]
                },
                unregisterShortcut: (state, { name }) => state.filter((shortcut) => shortcut.name !== name),
            },
        ],
        disabledShortcutNames: [
            loadDisabledShortcuts() as string[],
            {
                toggleShortcutDisabled: (state, { name }) => {
                    const next = state.includes(name) ? state.filter((n) => n !== name) : [...state, name]
                    saveDisabledShortcuts(next)
                    return next
                },
            },
        ],
    }),
    selectors({
        shortcutItems: [
            (s) => [s.registeredShortcuts, s.disabledShortcutNames],
            (shortcuts: ShortcutType[], disabledNames: string[]): SearchItem[] =>
                shortcuts
                    .filter(
                        (shortcut) => !disabledNames.includes(shortcut.name) && !HIDDEN_FROM_SEARCH.has(shortcut.name)
                    )
                    .map((shortcut) => ({
                        id: `shortcut-${shortcut.name}`,
                        name: shortcut.intent,
                        category: 'shortcuts',
                        icon: <IconKeyboard />,
                        keybinding: <RenderKeybind keybind={shortcut.keybind} />,
                        onSelect: () => {
                            if (shortcut.interaction === 'click') {
                                shortcut.ref.current?.click()
                            } else if (shortcut.interaction === 'focus') {
                                shortcut.ref.current?.focus()
                            } else {
                                shortcut.callback?.()
                            }
                        },
                        record: { type: 'shortcut', ref: shortcut.name },
                    })),
        ],
    }),
    afterMount(({ values, cache }) => {
        // Sequence shortcut state
        cache.sequenceKeys = [] as string[]
        cache.sequenceShortcut = null as ShortcutType | null
        cache.sequenceLastKeyTime = 0

        cache.onKeyDown = (event: KeyboardEvent) => {
            const target = event.composedPath()[0]
            if (target instanceof HTMLElement && target.closest('[data-shortcuts-ignore="all"]')) {
                cache.sequenceKeys = []
                cache.sequenceShortcut = null
                return
            }
            const controlKeyCapture =
                target instanceof HTMLElement ? target.closest<HTMLElement>('[data-shortcuts-ignore="ctrl"]') : null
            if (
                event.ctrlKey &&
                !event.metaKey &&
                controlKeyCapture &&
                !controlKeyCapture.dataset.shortcutsAllowKeys?.split(' ').includes(event.key)
            ) {
                // Terminal editors need control keys before application shortcuts capture them.
                return
            }
            const commandKey = event.metaKey || event.ctrlKey

            // Handle modifier-based shortcuts (Cmd+K, etc.)
            if (commandKey) {
                // Reset any in-progress sequence
                cache.sequenceKeys = []
                cache.sequenceShortcut = null

                // modifier vocabulary and order must stay in lockstep with formatTriggeredKeybind in
                // lib/hooks/useKeyboardHotkeys.tsx, so the same chord reports the same `keybind` string
                const pressedKeys: string[] = [COMMAND_OR_CTRL]
                if (event.shiftKey) {
                    pressedKeys.push('shift')
                }
                if (event.altKey) {
                    pressedKeys.push('option')
                }

                // Handle Alt key combinations - event.key can change with Alt held
                let keyToAdd = event.key.toLowerCase()
                if (event.altKey) {
                    const codeMatch = event.code.match(/^Key([A-Z])$/)
                    if (codeMatch) {
                        keyToAdd = codeMatch[1].toLowerCase()
                    } else if (event.code === 'Tab') {
                        keyToAdd = 'tab'
                    }
                }

                pressedKeys.push(keyToAdd)
                const pressedKeyString = pressedKeys.join('+')

                const matchingShortcut = values.registeredShortcuts.find((shortcut) =>
                    shortcut.keybind.some(
                        (keybind) =>
                            !isSequenceKeybind(keybind) &&
                            keybind.map((k) => k.toLowerCase()).join('+') === pressedKeyString
                    )
                )

                if (
                    matchingShortcut &&
                    !values.disabledShortcutNames.includes(matchingShortcut.name) &&
                    !(matchingShortcut.ignoreInEditable && isEditableElement(event))
                ) {
                    event.preventDefault()
                    event.stopPropagation()
                    triggerShortcut(matchingShortcut, pressedKeys)
                }
                return
            }

            // Handle sequence shortcuts (no modifier keys, not in editable elements, not mid-IME-composition)
            if (isEditableElement(event) || event.altKey || event.isComposing) {
                return
            }

            const now = Date.now()
            const key = event.key.toLowerCase()

            // Check for single-key shortcuts first (immediate trigger, no sequence)
            // Since single key shortcuts trigger eagerly, sequence shortcuts need to
            // check for collisions before being implemented. We could also make this
            // "lazy" but that would result in a noticeable lag in app for single key
            // shortcuts. My preference is the eager way
            const singleKeyMatch = values.registeredShortcuts.find((shortcut) =>
                shortcut.keybind.some((keybind) => isSingleKeyKeybind(keybind) && keybind[0] === key)
            )

            if (singleKeyMatch && !values.disabledShortcutNames.includes(singleKeyMatch.name)) {
                event.preventDefault()
                event.stopPropagation()
                cache.sequenceKeys = []
                cache.sequenceShortcut = null
                triggerShortcut(singleKeyMatch, [key])
                return
            }

            // Reset if too much time has passed (1.5s)
            if (now - cache.sequenceLastKeyTime > 1500) {
                cache.sequenceKeys = []
                cache.sequenceShortcut = null
            }
            cache.sequenceLastKeyTime = now

            // Build up the sequence
            cache.sequenceKeys.push(key)

            // Look for a matching sequence shortcut
            const matchingShortcut = values.registeredShortcuts.find((shortcut) =>
                shortcut.keybind.some((keybind) => {
                    if (!isSequenceKeybind(keybind)) {
                        return false
                    }
                    const sequenceKeys = getSequenceKeys(keybind)
                    // Check if our current keys match the end of a sequence
                    if (cache.sequenceKeys.length > sequenceKeys.length) {
                        return false
                    }
                    return sequenceKeys
                        .slice(0, cache.sequenceKeys.length)
                        .every((k: string, i: number) => k === cache.sequenceKeys[i])
                })
            )

            if (matchingShortcut) {
                const keybind = matchingShortcut.keybind.find((kb) => isSequenceKeybind(kb))!
                const sequenceKeys = getSequenceKeys(keybind)

                if (cache.sequenceKeys.length === sequenceKeys.length) {
                    // Sequence complete
                    cache.sequenceKeys = []
                    cache.sequenceShortcut = null
                    if (!values.disabledShortcutNames.includes(matchingShortcut.name)) {
                        event.preventDefault()
                        triggerShortcut(matchingShortcut, keybind)
                    }
                } else {
                    // Partial match - keep tracking
                    cache.sequenceShortcut = matchingShortcut
                }
            } else {
                // No match - reset
                cache.sequenceKeys = []
                cache.sequenceShortcut = null
            }
        }

        window.addEventListener('keydown', cache.onKeyDown, { capture: true })
        window.addEventListener('keyup', cache.onKeyUp)
        window.addEventListener('blur', cache.onBlur)
    }),
    beforeUnmount(({ cache }) => {
        // unregister app shortcuts
        window.removeEventListener('keydown', cache.onKeyDown, { capture: true })
        window.removeEventListener('keyup', cache.onKeyUp)
        window.removeEventListener('blur', cache.onBlur)
    }),
])