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.

9.3 KB
Raw Blame
import { useActions, useValues } from 'kea'
import { useLayoutEffect, useRef } from 'react'

import { IconSearch, IconSparkles, IconX } from '@posthog/icons'
import { Button, InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, cn } from '@posthog/quill'

import { todayShellLogic } from '~/layout/today/todayShellLogic'

import { keyIntent } from './commandKKeys'
import { queryAsText } from './commandKQuery'
import { commandKSearchLogic } from './commandKSearchLogic'
import { rowDomId } from './CommandKSearchRow'

export const COMMAND_K_LISTBOX_ID = 'command-k-listbox'

export function CommandKSearchInput(): JSX.Element {
    const { text, cursor, chips, chipSelection, highlightedRow, highlightIsFilterRow, tabAsksAi, isPaletteEmpty } =
        useValues(commandKSearchLogic)
    const { todayRailEnabled } = useValues(todayShellLogic)
    const { inputChanged, setCursor, applyKeyIntent, selectChip, clearQuery, askAi, closeCommand } =
        useActions(commandKSearchLogic)
    const inputRef = useRef<HTMLInputElement>(null)
    const pastingRef = useRef(false)

    // The logic moves the cursor when it commits or edits a chip, so mirror it onto the field.
    useLayoutEffect(() => {
        const input = inputRef.current
        if (input && document.activeElement === input && input.selectionStart !== cursor) {
            input.setSelectionRange(cursor, cursor)
        }
    }, [text, cursor])

    useLayoutEffect(() => {
        inputRef.current?.focus()
    }, [])

    const onKeyDown = (event: React.KeyboardEvent<HTMLInputElement>): void => {
        // Keys confirm or move inside an IME composition, so leave them to the input. Safari reports 229.
        if (event.nativeEvent.isComposing || event.keyCode === 229) {
            return
        }
        const input = event.currentTarget
        const intent = keyIntent(event.key, event, {
            atStart: input.selectionStart === 0 && input.selectionEnd === 0,
            chipCount: chips.length,
            chipSelection,
            tabHasAction: tabAsksAi || highlightIsFilterRow,
        })
        if (!intent) {
            return
        }
        if (!('keepDefault' in intent)) {
            event.preventDefault()
        }
        if (intent.type === 'close') {
            event.stopPropagation()
        }
        applyKeyIntent(intent)
    }

    // With everything selected, the clipboard gets the chips as text, so pasting it back rebuilds them.
    const copyWholeQuery = (event: React.ClipboardEvent<HTMLInputElement>): void => {
        event.preventDefault()
        event.clipboardData.setData('text/plain', queryAsText(text, chips))
    }

    return (
        <div className="flex items-center gap-1 p-2">
            {/* A fixed height, so committing a chip never resizes the field. Chips that overflow scroll sideways. */}
            <InputGroup className="flex-1">
                {/* The scroll container clips, so it gets room on the right for the selected chip's outline and gives it back with a negative margin.
                    ms-0 cancels quill's pull-in for button addons, and gap-1.5 matches the input's start padding, so committing a chip doesn't shift the text. */}
                <InputGroupAddon
                    align="inline-start"
                    className="-mr-1 ms-0 min-w-0 shrink gap-1.5 overflow-x-auto pr-1 [scrollbar-width:none]"
                >
                    <IconSearch className="size-4 shrink-0" />
                    {chips.map((chip, index) => (
                        // Committed filters read as typed text: plain key, brand-tinted value.
                        <button
                            key={chip.key}
                            type="button"
                            tabIndex={-1}
                            data-attr="command-k-chip"
                            aria-label={`${chip.negated ? 'Not ' : ''}${chip.key}: ${chip.label}. Backspace removes it.`}
                            className={cn(
                                'flex max-w-60 shrink-0 items-center rounded-xs leading-none text-foreground',
                                chipSelection === index && 'ring-2 ring-ring',
                                // The system color the input paints its own selected text with.
                                chipSelection === 'all' && 'bg-[Highlight]'
                            )}
                            onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}
                            onClick={() => selectChip(index)}
                        >
                            <span className="shrink-0 font-normal">
                                {chip.negated ? '-' : ''}
                                {chip.key}:
                            </span>
                            <span className="truncate rounded-xs bg-[var(--primary)]/10 px-0.5 text-[var(--primary)]">
                                {chip.label}
                            </span>
                        </button>
                    ))}
                </InputGroupAddon>
                <InputGroupInput
                    ref={inputRef}
                    id="command-k-input"
                    data-attr="command-k-input"
                    role="combobox"
                    aria-expanded
                    aria-controls={COMMAND_K_LISTBOX_ID}
                    aria-autocomplete="list"
                    aria-activedescendant={highlightedRow ? rowDomId(highlightedRow.key) : undefined}
                    aria-label="Search"
                    autoComplete="off"
                    spellCheck={false}
                    placeholder={chips.length === 0 ? 'Search or ask PostHog AI… try is:dashboard' : undefined}
                    className="min-w-24 flex-1"
                    value={text}
                    onPaste={() => {
                        pastingRef.current = true
                    }}
                    onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                        const pasted = pastingRef.current
                        pastingRef.current = false
                        inputChanged(
                            event.target.value,
                            event.target.selectionStart ?? event.target.value.length,
                            pasted
                        )
                    }}
                    onCopy={(event: React.ClipboardEvent<HTMLInputElement>) => {
                        if (chipSelection === 'all') {
                            copyWholeQuery(event)
                        }
                    }}
                    onCut={(event: React.ClipboardEvent<HTMLInputElement>) => {
                        if (chipSelection === 'all') {
                            copyWholeQuery(event)
                            clearQuery()
                        }
                    }}
                    // An empty input fires no select event on click, so this is the only place that click deselects.
                    onMouseDown={() => chipSelection === 'all' && selectChip(null)}
                    onSelect={(event: React.SyntheticEvent<HTMLInputElement>) => {
                        const input = event.currentTarget
                        const wholeTextSelected =
                            input.selectionStart === 0 && input.selectionEnd === input.value.length
                        if (chipSelection === 'all' && !wholeTextSelected) {
                            selectChip(null)
                        }
                        const nextCursor = event.currentTarget.selectionStart ?? 0
                        if (nextCursor !== cursor) {
                            setCursor(nextCursor)
                        }
                    }}
                    onKeyDown={onKeyDown}
                />
                <InputGroupAddon align="inline-end">
                    {tabAsksAi && (
                        <InputGroupButton
                            size="sm"
                            variant="secondary"
                            tabIndex={-1}
                            data-attr="command-k-ask-ai"
                            onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}
                            onClick={() => askAi()}
                        >
                            <IconSparkles />
                            Press Tab to ask AI
                        </InputGroupButton>
                    )}
                    {!isPaletteEmpty && (
                        <InputGroupButton
                            size="icon-xs"
                            tabIndex={-1}
                            aria-label="Clear search"
                            data-attr="command-k-clear"
                            className="mr-1"
                            onMouseDown={(event: React.MouseEvent<HTMLButtonElement>) => event.preventDefault()}
                            onClick={() => clearQuery()}
                        >
                            <IconX />
                        </InputGroupButton>
                    )}
                </InputGroupAddon>
            </InputGroup>
            {todayRailEnabled && (
                <Button
                    size="sm"
                    className="hidden shrink-0 max-md:flex"
                    data-attr="command-phone-cancel"
                    onClick={() => closeCommand()}
                >
                    Cancel
                </Button>
            )}
        </div>
    )
}