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.

3.5 KB
Raw Blame
import { useMergeRefs } from '@floating-ui/react'
import { ReactElement, cloneElement, forwardRef, isValidElement } from 'react'

import { cn } from 'lib/utils/css-classes'

import { RenderKeybind } from './RenderKeybind'
import { ShortcutType } from './shortcutLogic'
import { convertPlatformKeybind, useShortcut } from './useShortcut'

export function keybindToKeyboardShortcutProps(keybind: string[]): Record<string, boolean> {
    const platformAgnosticKeybind = convertPlatformKeybind(keybind)
    return Object.fromEntries(platformAgnosticKeybind.map((key) => [key, true]))
}

interface ShortcutProps extends Omit<ShortcutType, 'ref' | 'keybind' | 'interaction' | 'callback'> {
    /** The keybind(s) to use for the shortcut - can be a single keybind or multiple alternative keybinds */
    keybind: string[][]
    /** Single React element child - must forward ref to clickable/focusable element */
    children: ReactElement
    /** 'click' triggers element.click(), 'focus' triggers element.focus(), doesn't support `function` which should use `useShortcut` directly instead */
    interaction: 'click' | 'focus'
    /** If true, the keyboard shortcut will not be registered and tooltip keyboard shortcut will not be added to the childs tooltip */
    disabled?: boolean
    /** Reason the child is disabled, e.g. injected by AccessControlAction. Forwarded to the child. */
    disabledReason?: string | null
}

export const Shortcut = forwardRef<HTMLElement, ShortcutProps>(function Shortcut(
    {
        children,
        name,
        keybind,
        intent,
        interaction,
        scope = 'global',
        disabled = false,
        disabledReason,
        ignoreInEditable,
        priority = 0,
    },
    forwardedRef
): ReactElement {
    const childProps = (isValidElement(children) ? children.props : {}) as Record<string, unknown>

    // A disabled control must not keep a live keybind, so this also gates registration below.
    const isDisabled =
        disabled || Boolean(disabledReason) || Boolean(childProps.disabled) || Boolean(childProps.disabledReason)

    const { callbackRef } = useShortcut({
        name,
        keybind,
        intent,
        interaction,
        scope,
        disabled: isDisabled,
        priority,
        ignoreInEditable,
    })

    const mergedRef = useMergeRefs([callbackRef, forwardedRef])

    if (!isValidElement(children)) {
        throw new Error('Shortcut requires a single React element child')
    }

    const keybindStrings = keybind.map((kb) => kb.join('+')).join(',')

    // Append keyboard shortcut to tooltip if child has one
    let finalTooltip = childProps.tooltip
    if (childProps.tooltip && !isDisabled) {
        finalTooltip = (
            <>
                {childProps.tooltip}{' '}
                {keybind.map((kb, index) => (
                    <span key={index}>
                        {index > 0 && <span className="text-xs opacity-75"> or </span>}
                        <RenderKeybind keybind={[kb]} className="relative text-xs -top-px" />
                    </span>
                ))}
            </>
        )
    }

    return cloneElement(children, {
        ref: mergedRef,
        disabled: isDisabled,
        disabledReason: disabledReason ?? (childProps.disabledReason as string | null | undefined),
        'data-shortcut-name': name,
        'data-shortcut-keybind': keybindStrings,
        'data-shortcut-intent': intent,
        'aria-keyshortcuts': keybindStrings,
        tooltip: finalTooltip,
        className: cn(childProps.className as string | undefined),
    } as Record<string, unknown>)
})