diff --git a/.changeset/violet-onions-tickle.md b/.changeset/violet-onions-tickle.md new file mode 100644 index 0000000000..10ea5afa3d --- /dev/null +++ b/.changeset/violet-onions-tickle.md @@ -0,0 +1,5 @@ +--- +"@hyperdx/app": patch +--- + +ui: Extract FilterPill, add filter editor components diff --git a/packages/app/src/components/ActiveFilterPills.tsx b/packages/app/src/components/ActiveFilterPills.tsx index 0d91fcb11a..86d8234951 100644 --- a/packages/app/src/components/ActiveFilterPills.tsx +++ b/packages/app/src/components/ActiveFilterPills.tsx @@ -1,30 +1,11 @@ import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { BuilderChartConfigWithDateRange } from '@hyperdx/common-utils/dist/types'; -import { - ActionIcon, - Autocomplete, - Flex, - FlexProps, - Popover, - Text, - Tooltip, -} from '@mantine/core'; -import { notifications } from '@mantine/notifications'; -import { - IconCheck, - IconCopy, - IconFilter, - IconFilterX, - IconX, -} from '@tabler/icons-react'; +import { Flex, FlexProps, Text } from '@mantine/core'; +import { FilterPill, FilterValueEditor } from '@/components/FilterPill'; import { useGetKeyValues } from '@/hooks/useMetadata'; import type { FilterStateHook } from '@/searchFilters'; import { useFormatTime } from '@/useFormatTime'; -import { - CLIPBOARD_ERROR_MESSAGE, - copyTextToClipboard, -} from '@/utils/clipboard'; const MAX_VISIBLE_PILLS = 8; // Cap the value list fetched for the in-pill value picker. @@ -91,21 +72,7 @@ function flattenFilters( return pills; } -const pillStyle = { - display: 'inline-flex', - alignItems: 'center', - gap: 4, - padding: '1px 6px', - borderRadius: 3, - fontSize: 11, - lineHeight: '18px', - cursor: 'default', - whiteSpace: 'nowrap' as const, - maxWidth: 260, - overflow: 'hidden', -}; - -function FilterPill({ +function SearchFilterPill({ pill, isInvalid, invalidReason, @@ -123,33 +90,10 @@ function FilterPill({ onReplaceValue: (value: string) => void; }) { const isExcluded = pill.type === 'excluded'; - const operator = isExcluded ? ' != ' : pill.type === 'range' ? ': ' : ' = '; - // A range pill has no single value to copy or flip, and an unapplied filter - // (column missing on the active source) can only be removed. Both keep the - // plain remove-only pill; only included/excluded pills open the action menu. + // (column missing on the active source) can only be removed. const isEditable = pill.type !== 'range' && !isInvalid; - const polarityLabel = isExcluded ? 'Include' : 'Exclude'; - const [opened, setOpened] = useState(false); - const [copied, setCopied] = useState(false); - // Draft of the value being typed in the picker. Free text is allowed (the - // field may not have this value in the sampled data yet), so we track what - // the user types and only commit it on submit/blur. It starts empty (the - // current value shows as a placeholder) so the full suggestion list is - // visible on open instead of being filtered down to just the current value. - const [draftValue, setDraftValue] = useState(''); - const copyTimerRef = useRef>(undefined); - - useEffect(() => { - return () => clearTimeout(copyTimerRef.current); - }, []); - - // Reset the draft each time the menu opens so reopening on a different - // pill (or after a replace) starts from a clean, unfiltered list. - useEffect(() => { - setDraftValue(''); - }, [pill.value, opened]); // The picker lists values to switch this pill to, so it must not be scoped // by the active query or by the pill's own filter. Reusing chartConfig @@ -162,8 +106,6 @@ function FilterPill({ [chartConfig], ); - // Fetch the field's values for the in-pill value picker, only while the - // menu is open (and never for range / not-applied pills). const { data: keyValues, isFetching: isFetchingValues } = useGetKeyValues( { chartConfig: valueChartConfig, @@ -172,209 +114,36 @@ function FilterPill({ }, { enabled: opened && isEditable }, ); - const valueOptions = useMemo( - () => Array.from(new Set([pill.value, ...(keyValues?.[0]?.value ?? [])])), - [keyValues, pill.value], - ); - - const label = pill.displayValue ?? pill.value; - const tooltipLabel = isInvalid - ? (invalidReason ?? - `Filter not applied: "${pill.field}" isn't a column on the current source. It will reapply if you switch back.`) - : `${pill.field}${operator}${label}`; - - const showDangerAccent = isExcluded && !isInvalid; - - // Commit the typed/picked value, but only when it actually differs from the - // current one (avoids a redundant query on blur with no change). - const commitValue = (value: string) => { - const trimmed = value.trim(); - if (trimmed && trimmed !== pill.value) { - onReplaceValue(trimmed); - } - setOpened(false); - }; - - const handleCopy = async () => { - const ok = await copyTextToClipboard(pill.value); - if (!ok) { - notifications.show({ color: 'red', message: CLIPBOARD_ERROR_MESSAGE }); - return; - } - setCopied(true); - clearTimeout(copyTimerRef.current); - copyTimerRef.current = setTimeout(() => setCopied(false), 1500); - }; - - const pillWithTooltip = ( - - setOpened(o => !o) : undefined} - style={{ - ...pillStyle, - cursor: isEditable ? 'pointer' : 'default', - backgroundColor: isInvalid - ? 'transparent' - : isExcluded - ? 'var(--mantine-color-red-light)' - : 'var(--color-bg-hover)', - border: isInvalid - ? '1px dashed var(--color-border-emphasis)' - : '1px solid transparent', - opacity: isInvalid ? 0.75 : 1, - }} - > - - {pill.field} - - - {operator} - - - {label} - - { - // Keep the one-click remove without also toggling the action menu. - e.stopPropagation(); - onRemove(); - }} - style={{ - flexShrink: 0, - marginLeft: 2, - color: showDangerAccent - ? 'var(--mantine-color-red-light-color)' - : undefined, - }} - aria-label="Remove filter" - > - - - - - ); - - if (!isEditable) { - return pillWithTooltip; - } + const valueOptions = useMemo(() => keyValues?.[0]?.value ?? [], [keyValues]); return ( - - {pillWithTooltip} - - { - if (e.key !== 'Enter') { - return; - } - // If the user is keyboard-navigating the dropdown, an option is - // highlighted (Mantine marks it with [data-combobox-selected]). - // Let the combobox handle Enter natively so it submits that option - // via onOptionSubmit. Only commit free text when no option is - // highlighted, so a typed value not in the list still applies. - // Scope the lookup to this input's own listbox (via aria-controls) - // rather than the whole document, so another open combobox on the - // page can't make us swallow Enter here. - const listId = e.currentTarget.getAttribute('aria-controls'); - const list = listId ? document.getElementById(listId) : null; - const hasHighlightedOption = !!list?.querySelector( - '[data-combobox-selected]', - ); - if (!hasHighlightedOption) { - e.preventDefault(); - commitValue(draftValue); - } - }} - comboboxProps={{ withinPortal: false }} - placeholder={isFetchingValues ? 'Loading values...' : pill.value} - aria-label="Change filter value" - /> - - - - {copied ? : } - - - - { - onTogglePolarity(); - setOpened(false); - }} - aria-label={polarityLabel} - > - {isExcluded ? ( - - ) : ( - - )} - - - - - + { + const listId = input.getAttribute('aria-controls'); + const list = listId ? document.getElementById(listId) : null; + return !!list?.querySelector('[data-combobox-selected]'); +}; + +export type FilterAutocompleteProps = { + value: string; + onChange: (value: string) => void; + /** Enter with no suggestion highlighted, so free text is accepted. */ + onSubmit: (value: string) => void; + /** A suggestion was picked. Its value is also reported through `onChange`. */ + onOptionSubmit?: (value: string) => void; + options: string[]; + isLoading?: boolean; + label?: string; + placeholder?: string; + 'aria-label'?: string; + 'data-testid'?: string; + ref?: Ref; +} & Pick; + +/** Suggestion input for filter keys and values that also accepts free text. */ +export function FilterAutocomplete({ + value, + onChange, + onSubmit, + onOptionSubmit, + options, + isLoading, + size = 'xs', + ...props +}: FilterAutocompleteProps) { + const testId = props['data-testid']; + return ( + { + if (e.key === 'Enter' && !isSuggestionHighlighted(e.currentTarget)) { + e.preventDefault(); + onSubmit(value); + } + }} + limit={200} + rightSection={ + isLoading ? ( + + ) : null + } + // Keep the dropdown inside the parent popover so picking an option + // doesn't count as an outside click. + comboboxProps={{ withinPortal: false }} + /> + ); +} diff --git a/packages/app/src/components/FilterPill/FilterConditionEditor.stories.tsx b/packages/app/src/components/FilterPill/FilterConditionEditor.stories.tsx new file mode 100644 index 0000000000..7db25cea43 --- /dev/null +++ b/packages/app/src/components/FilterPill/FilterConditionEditor.stories.tsx @@ -0,0 +1,114 @@ +import { useState } from 'react'; +import { Code, Stack } from '@mantine/core'; +import type { Meta } from '@storybook/nextjs'; + +import { + MOCK_PROMQL_VALUES, + MOCK_SQL_VALUES, + useMockValues, +} from '@/mocks/filterValues'; + +import { + FilterCondition, + FilterConditionEditor, + FilterConditionEditorProps, +} from './FilterConditionEditor'; +import { + FilterOperator, + PROMQL_FILTER_OPERATORS, + SQL_FILTER_OPERATORS, +} from './filterOperators'; + +const meta = { + title: 'Components/FilterConditionEditor', + component: FilterConditionEditor, + parameters: { + docs: { + description: { + component: + 'Pick a key, operator, and value for an ad hoc filter condition. Data loading is up to the caller; these stories serve mock keys and values.', + }, + }, + }, +} satisfies Meta; + +export default meta; + +function Demo({ + values, + isLoadingKeys, + forceLoadingValues, + ...props +}: Omit< + FilterConditionEditorProps, + 'keyOptions' | 'valueOptions' | 'onSubmit' +> & { + values: Record; + forceLoadingValues?: boolean; +}) { + const [key, setKey] = useState(''); + const [submitted, setSubmitted] = useState([]); + const valueQuery = useMockValues(values, key); + return ( + + setSubmitted(s => [...s, condition])} + /> + {submitted.length > 0 && ( + {JSON.stringify(submitted, null, 2)} + )} + + ); +} + +export const Sql = () => ( + +); + +export const Promql = () => ( + +); + +export const EditingExisting = () => ( + +); + +export const LoadingKeys = () => ( + +); + +export const LoadingValues = () => ( + +); + +export const NoSuggestions = () => ( + +); diff --git a/packages/app/src/components/FilterPill/FilterConditionEditor.tsx b/packages/app/src/components/FilterPill/FilterConditionEditor.tsx new file mode 100644 index 0000000000..e5486e544a --- /dev/null +++ b/packages/app/src/components/FilterPill/FilterConditionEditor.tsx @@ -0,0 +1,127 @@ +import { useEffect, useRef, useState } from 'react'; +import { Button, Group, Select, Stack } from '@mantine/core'; +import { useDebouncedValue } from '@mantine/hooks'; + +import { FilterAutocomplete } from './FilterAutocomplete'; + +export type FilterOperatorOption = { + value: TOperator; + /** Shown in the operator select and on the pill, e.g. `regex` for `=~`. */ + label: string; + /** Conditions using this operator get the pill's excluded accent. */ + negated?: boolean; + valueLabel?: string; + valuePlaceholder?: string; +}; + +export type FilterCondition = { + key: string; + operator: TOperator; + value: string; +}; + +export type FilterConditionEditorProps = { + operators: FilterOperatorOption[]; + /** The condition being edited; unset when adding one. */ + initial?: FilterCondition; + keyOptions: string[]; + isLoadingKeys?: boolean; + /** Suggestions for the key last reported by `onKeyChange`. */ + valueOptions: string[]; + isLoadingValues?: boolean; + /** The trimmed key, once typing pauses, so the caller can fetch its values. */ + onKeyChange?: (key: string) => void; + keyLabel?: string; + keyPlaceholder?: string; + onSubmit: (condition: FilterCondition) => void; + 'data-testid'?: string; +}; + +const KEY_DEBOUNCE_MS = 300; + +/** Pick a key, an operator, and a value. Free text is accepted for both inputs. */ +export function FilterConditionEditor({ + operators, + initial, + keyOptions, + isLoadingKeys, + valueOptions, + isLoadingValues, + onKeyChange, + keyLabel = 'Key', + keyPlaceholder = 'Select a key', + onSubmit, + 'data-testid': testId = 'filter-condition-editor', +}: FilterConditionEditorProps) { + const [key, setKey] = useState(initial?.key ?? ''); + const [operator, setOperator] = useState( + initial?.operator ?? operators[0]?.value, + ); + const [value, setValue] = useState(initial?.value ?? ''); + const valueInputRef = useRef(null); + + const trimmedKey = key.trim(); + const [debouncedKey] = useDebouncedValue(trimmedKey, KEY_DEBOUNCE_MS); + useEffect(() => { + onKeyChange?.(debouncedKey); + }, [debouncedKey, onKeyChange]); + + // Values shown while the key is still settling belong to the previous key. + const isValueLoading = + !!trimmedKey && (!!isLoadingValues || debouncedKey !== trimmedKey); + const selectedOperator = operators.find(op => op.value === operator); + const canSubmit = !!trimmedKey && operator != null; + + const submit = () => { + if (!canSubmit) return; + onSubmit({ key: trimmedKey, operator, value }); + }; + + return ( + + valueInputRef.current?.focus()} + data-testid={`${testId}-key`} + /> + + size="xs" + label="Operator" + data={operators.map(op => ({ value: op.value, label: op.label }))} + value={operator ?? null} + onChange={next => next != null && setOperator(next)} + allowDeselect={false} + comboboxProps={{ withinPortal: false }} + data-testid={`${testId}-operator`} + /> + + + + + + ); +} diff --git a/packages/app/src/components/FilterPill/FilterPill.stories.tsx b/packages/app/src/components/FilterPill/FilterPill.stories.tsx new file mode 100644 index 0000000000..0f16ab08ab --- /dev/null +++ b/packages/app/src/components/FilterPill/FilterPill.stories.tsx @@ -0,0 +1,200 @@ +import { useState } from 'react'; +import { Group, SegmentedControl, Stack } from '@mantine/core'; +import type { Meta, StoryObj } from '@storybook/nextjs'; + +import { + MOCK_PROMQL_VALUES, + MOCK_SQL_VALUES, + useMockValues, +} from '@/mocks/filterValues'; + +import { + FilterCondition, + FilterConditionEditor, +} from './FilterConditionEditor'; +import { + FilterLanguage, + FilterOperator, + getFilterOperators, +} from './filterOperators'; +import { FilterPill } from './FilterPill'; +import { FilterValueEditor } from './FilterValueEditor'; + +const meta = { + title: 'Components/FilterPill', + component: FilterPill, + args: { + field: 'ServiceName', + operator: '=', + value: 'checkout', + onRemove: () => {}, + }, +} satisfies Meta; + +export default meta; +type Story = StoryObj; + +export const Included: Story = {}; + +export const Excluded: Story = { + args: { + operator: '!=', + value: 'debug', + field: 'SeverityText', + isExcluded: true, + }, +}; + +export const DisplayValue: Story = { + args: { + field: 'Timestamp', + value: '2026-06-16T15:35:16.731000000Z', + displayValue: 'Jun 16 11:35:16.731 AM', + }, +}; + +export const Invalid: Story = { + args: { + isInvalid: true, + invalidReason: + 'Filter not applied: "ServiceName" isn\'t a column on the current source.', + }, +}; + +export const RangeRemoveOnly: Story = { + args: { field: 'Duration', operator: ':', value: '100 – 500' }, +}; + +export const LongValues: Story = { + args: { + field: "ResourceAttributes['k8s.deployment.name']", + value: 'a-very-long-deployment-name-that-should-be-truncated-in-the-pill', + }, +}; + +export const Row: Story = { + render: () => ( + + {}} + /> + {}} + /> + {}} + /> + {}} + /> + + ), +}; + +function ValueEditorDemo() { + const [value, setValue] = useState('checkout'); + const [isExcluded, setIsExcluded] = useState(false); + const [opened, setOpened] = useState(false); + const values = useMockValues(MOCK_SQL_VALUES, opened ? 'ServiceName' : ''); + return ( + {}} + onOpenedChange={setOpened} + renderPopover={close => ( + setIsExcluded(e => !e)} + onDone={close} + /> + )} + /> + ); +} + +export const WithValueEditor: Story = { + render: () => , +}; + +function ConditionEditorDemo() { + const [language, setLanguage] = useState('sql'); + const [condition, setCondition] = useState>({ + key: 'ServiceName', + operator: '=', + value: 'checkout', + }); + const [key, setKey] = useState(''); + const mockValues = + language === 'promql' ? MOCK_PROMQL_VALUES : MOCK_SQL_VALUES; + const values = useMockValues(mockValues, key); + const operators = getFilterOperators(language); + const operator = operators.find(op => op.value === condition.operator); + + return ( + + + size="xs" + value={language} + onChange={next => { + setLanguage(next); + setCondition( + next === 'promql' + ? { key: 'job', operator: '=', value: 'api' } + : { key: 'ServiceName', operator: '=', value: 'checkout' }, + ); + }} + data={[ + { value: 'sql', label: 'SQL' }, + { value: 'promql', label: 'PromQL' }, + ]} + /> + {}} + renderPopover={close => ( + { + setCondition(next); + close(); + }} + /> + )} + /> + + ); +} + +export const WithConditionEditor: Story = { + render: () => , +}; diff --git a/packages/app/src/components/FilterPill/FilterPill.tsx b/packages/app/src/components/FilterPill/FilterPill.tsx new file mode 100644 index 0000000000..2f95877837 --- /dev/null +++ b/packages/app/src/components/FilterPill/FilterPill.tsx @@ -0,0 +1,177 @@ +import { CSSProperties, useState } from 'react'; +import { ActionIcon, Popover, Text, Tooltip } from '@mantine/core'; +import { IconX } from '@tabler/icons-react'; + +const pillStyle: CSSProperties = { + display: 'inline-flex', + alignItems: 'center', + gap: 4, + padding: '1px 6px', + borderRadius: 3, + fontSize: 11, + lineHeight: '18px', + whiteSpace: 'nowrap', + maxWidth: 260, + overflow: 'hidden', +}; + +export type FilterPillProps = { + field: string; + /** Display label for the operator, e.g. `=`, `regex`, `:`. */ + operator: string; + value: string; + /** Display-only label for the value (e.g. a locale-formatted DateTime). */ + displayValue?: string; + /** A negated condition, shown with the danger accent. */ + isExcluded?: boolean; + /** + * A filter that's in state but not applied to the query. Rendered muted with + * a dashed border, and can only be removed. + */ + isInvalid?: boolean; + invalidReason?: string; + onRemove: () => void; + /** + * Content of the popover opened by clicking the pill. Omit for a remove-only + * pill. `close` dismisses the popover. + */ + renderPopover?: (close: () => void) => React.ReactNode; + /** Lets callers fetch popover data lazily. */ + onOpenedChange?: (opened: boolean) => void; + 'data-testid'?: string; +}; + +/** A removable `field operator value` chip that can open an edit popover. */ +export function FilterPill({ + field, + operator, + value, + displayValue, + isExcluded = false, + isInvalid = false, + invalidReason, + onRemove, + renderPopover, + onOpenedChange, + 'data-testid': testId, +}: FilterPillProps) { + const [opened, setOpened] = useState(false); + const changeOpened = (next: boolean) => { + setOpened(next); + onOpenedChange?.(next); + }; + + const isEditable = renderPopover != null && !isInvalid; + const showDangerAccent = isExcluded && !isInvalid; + const label = displayValue ?? value; + const strikethrough = isInvalid ? 'line-through' : undefined; + // `:` reads as a label separator (`duration: 100 – 500`), not an infix operator. + const operatorText = operator === ':' ? ': ' : ` ${operator} `; + const tooltipLabel = isInvalid + ? (invalidReason ?? + `Filter not applied: "${field}" isn't a column on the current source. It will reapply if you switch back.`) + : `${field}${operatorText}${label}`; + + const pill = ( + + changeOpened(!opened) : undefined} + style={{ + ...pillStyle, + cursor: isEditable ? 'pointer' : 'default', + backgroundColor: isInvalid + ? 'transparent' + : isExcluded + ? 'var(--mantine-color-red-light)' + : 'var(--color-bg-hover)', + border: isInvalid + ? '1px dashed var(--color-border-emphasis)' + : '1px solid transparent', + opacity: isInvalid ? 0.75 : 1, + }} + > + + {field} + + + {operatorText} + + + {label} + + { + // Remove in one click without also toggling the popover. + e.stopPropagation(); + onRemove(); + }} + style={{ + flexShrink: 0, + marginLeft: 2, + color: showDangerAccent + ? 'var(--mantine-color-red-light-color)' + : undefined, + }} + aria-label="Remove filter" + > + + + + + ); + + if (!isEditable) { + return pill; + } + + return ( + + {pill} + + {renderPopover(() => changeOpened(false))} + + + ); +} diff --git a/packages/app/src/components/FilterPill/FilterValueEditor.tsx b/packages/app/src/components/FilterPill/FilterValueEditor.tsx new file mode 100644 index 0000000000..0294c9a898 --- /dev/null +++ b/packages/app/src/components/FilterPill/FilterValueEditor.tsx @@ -0,0 +1,120 @@ +import { useEffect, useMemo, useRef, useState } from 'react'; +import { ActionIcon, Flex, Tooltip } from '@mantine/core'; +import { notifications } from '@mantine/notifications'; +import { + IconCheck, + IconCopy, + IconFilter, + IconFilterX, +} from '@tabler/icons-react'; + +import { + CLIPBOARD_ERROR_MESSAGE, + copyTextToClipboard, +} from '@/utils/clipboard'; + +import { FilterAutocomplete } from './FilterAutocomplete'; + +export type FilterValueEditorProps = { + value: string; + /** Suggestions to switch to; the current value is always listed. */ + valueOptions: string[]; + isLoadingValues?: boolean; + isExcluded: boolean; + /** Called only when the new value differs from `value`. */ + onReplaceValue: (value: string) => void; + onTogglePolarity: () => void; + /** Called after a commit or polarity toggle, e.g. to close the popover. */ + onDone: () => void; +}; + +/** Change a filter's value, copy it, or flip it between include and exclude. */ +export function FilterValueEditor({ + value, + valueOptions, + isLoadingValues, + isExcluded, + onReplaceValue, + onTogglePolarity, + onDone, +}: FilterValueEditorProps) { + // Starts empty, with the current value as the placeholder, so the full + // suggestion list shows instead of being filtered down to the current value. + const [draftValue, setDraftValue] = useState(''); + const [copied, setCopied] = useState(false); + const copyTimerRef = useRef>(undefined); + + useEffect(() => { + return () => clearTimeout(copyTimerRef.current); + }, []); + + const options = useMemo( + () => Array.from(new Set([value, ...valueOptions])), + [value, valueOptions], + ); + + // Skip a no-op replace so Enter without a change doesn't rerun the query. + const commitValue = (next: string) => { + const trimmed = next.trim(); + if (trimmed && trimmed !== value) { + onReplaceValue(trimmed); + } + onDone(); + }; + + const handleCopy = async () => { + const ok = await copyTextToClipboard(value); + if (!ok) { + notifications.show({ color: 'red', message: CLIPBOARD_ERROR_MESSAGE }); + return; + } + setCopied(true); + clearTimeout(copyTimerRef.current); + copyTimerRef.current = setTimeout(() => setCopied(false), 1500); + }; + + const polarityLabel = isExcluded ? 'Include' : 'Exclude'; + + return ( + <> + + + + + {copied ? : } + + + + { + onTogglePolarity(); + onDone(); + }} + aria-label={polarityLabel} + > + {isExcluded ? : } + + + + + ); +} diff --git a/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx b/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx new file mode 100644 index 0000000000..7f5661d90e --- /dev/null +++ b/packages/app/src/components/FilterPill/__tests__/FilterConditionEditor.test.tsx @@ -0,0 +1,152 @@ +import { act, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { + FilterConditionEditor, + FilterConditionEditorProps, +} from '@/components/FilterPill/FilterConditionEditor'; +import { + FilterOperator, + PROMQL_FILTER_OPERATORS, + SQL_FILTER_OPERATORS, +} from '@/components/FilterPill/filterOperators'; + +// Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks +// it. jsdom also has no layout, so options must be queried with { hidden: true }. +window.HTMLElement.prototype.scrollIntoView = jest.fn(); + +const renderEditor = ( + props: Partial> = {}, +) => { + const onSubmit = jest.fn(); + renderWithMantine( + , + ); + return onSubmit; +}; + +const keyInput = () => screen.getByRole('combobox', { name: 'Key' }); +const valueInput = (name = 'Value') => screen.getByRole('combobox', { name }); +const applyButton = () => screen.getByRole('button', { name: 'Apply' }); + +describe('FilterConditionEditor', () => { + it('shows a loading indicator on the key input while keys load', () => { + renderEditor({ isLoadingKeys: true }); + expect( + screen.getByTestId('filter-condition-editor-key-loading'), + ).toBeInTheDocument(); + }); + + it('shows a loading indicator on the value input once a key is entered', async () => { + renderEditor({ isLoadingValues: true }); + expect( + screen.queryByTestId('filter-condition-editor-value-loading'), + ).toBeNull(); + await userEvent.type(keyInput(), 'ServiceName'); + expect( + screen.getByTestId('filter-condition-editor-value-loading'), + ).toBeInTheDocument(); + }); + + it('submits free-form text on Enter in the value input', async () => { + const onSubmit = renderEditor({ isLoadingValues: true }); + // `[[` types a literal `[`. + await userEvent.type(keyInput(), "LogAttributes[['custom']"); + await userEvent.type(valueInput(), 'anything{enter}'); + expect(onSubmit).toHaveBeenCalledWith({ + key: "LogAttributes['custom']", + operator: '=', + value: 'anything', + }); + }); + + it('moves focus to the value input on Enter in the key input', async () => { + const onSubmit = renderEditor(); + await userEvent.type(keyInput(), 'ServiceName{enter}'); + expect(onSubmit).not.toHaveBeenCalled(); + expect(valueInput()).toHaveFocus(); + }); + + it('fills the value from a picked suggestion without submitting', async () => { + const onSubmit = renderEditor({ + initial: { key: 'ServiceName', operator: '=', value: '' }, + valueOptions: ['checkout', 'frontend'], + }); + await userEvent.click(valueInput()); + await userEvent.click( + await screen.findByRole('option', { name: 'frontend', hidden: true }), + ); + expect(valueInput()).toHaveValue('frontend'); + expect(onSubmit).not.toHaveBeenCalled(); + + await userEvent.click(applyButton()); + expect(onSubmit).toHaveBeenCalledWith({ + key: 'ServiceName', + operator: '=', + value: 'frontend', + }); + }); + + it('submits the chosen operator and relabels the value for regex', async () => { + const onSubmit = renderEditor({ + initial: { key: 'ServiceName', operator: '=', value: '' }, + }); + await userEvent.click(screen.getByRole('combobox', { name: 'Operator' })); + await userEvent.click( + await screen.findByRole('option', { name: 'regex', hidden: true }), + ); + await userEvent.type(valueInput('Pattern'), '^check{enter}'); + expect(onSubmit).toHaveBeenCalledWith({ + key: 'ServiceName', + operator: '=~', + value: '^check', + }); + }); + + it('offers only the given operators', async () => { + renderEditor({ operators: PROMQL_FILTER_OPERATORS }); + await userEvent.click(screen.getByRole('combobox', { name: 'Operator' })); + const options = await screen.findAllByRole('option', { hidden: true }); + expect(options.map(o => o.textContent)).toEqual(['=', '!=', '=~', '!~']); + }); + + it('disables Apply until a key is entered', async () => { + const onSubmit = renderEditor({ + initial: { key: 'job', operator: '!=', value: 'api' }, + operators: PROMQL_FILTER_OPERATORS, + }); + expect(applyButton()).toBeEnabled(); + await userEvent.click(applyButton()); + expect(onSubmit).toHaveBeenCalledWith({ + key: 'job', + operator: '!=', + value: 'api', + }); + + await userEvent.clear(keyInput()); + expect(applyButton()).toBeDisabled(); + }); + + it('reports the key only once it stops changing', async () => { + jest.useFakeTimers(); + try { + const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime }); + const onKeyChange = jest.fn(); + renderEditor({ onKeyChange }); + await user.type(keyInput(), 'Svc'); + expect(onKeyChange).not.toHaveBeenCalledWith('Sv'); + act(() => { + jest.advanceTimersByTime(300); + }); + expect(onKeyChange).toHaveBeenLastCalledWith('Svc'); + } finally { + jest.useRealTimers(); + } + }); +}); diff --git a/packages/app/src/components/FilterPill/__tests__/FilterPill.test.tsx b/packages/app/src/components/FilterPill/__tests__/FilterPill.test.tsx new file mode 100644 index 0000000000..9c65b947d5 --- /dev/null +++ b/packages/app/src/components/FilterPill/__tests__/FilterPill.test.tsx @@ -0,0 +1,97 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { FilterPill } from '@/components/FilterPill/FilterPill'; + +describe('FilterPill', () => { + it('renders field, operator, and display value', () => { + renderWithMantine( + , + ); + expect(screen.getByText('Timestamp')).toBeInTheDocument(); + expect(screen.getByText('formatted')).toBeInTheDocument(); + expect(screen.queryByText('raw')).not.toBeInTheDocument(); + }); + + it('renders a range operator without a leading space', () => { + renderWithMantine( + , + ); + expect(screen.getByTestId('pill')).toHaveTextContent( + /^duration: 100 – 500$/, + ); + }); + + it('removes without opening the popover', async () => { + const onRemove = jest.fn(); + renderWithMantine( +
popover content
} + />, + ); + await userEvent.click( + screen.getByRole('button', { name: 'Remove filter' }), + ); + expect(onRemove).toHaveBeenCalledTimes(1); + expect(screen.queryByText('popover content')).not.toBeInTheDocument(); + }); + + it('opens the popover on click and closes it via close()', async () => { + const onOpenedChange = jest.fn(); + renderWithMantine( + } + data-testid="pill" + />, + ); + await userEvent.click(screen.getByTestId('pill')); + expect(onOpenedChange).toHaveBeenLastCalledWith(true); + await userEvent.click( + await screen.findByRole('button', { name: 'Done', hidden: true }), + ); + expect(onOpenedChange).toHaveBeenLastCalledWith(false); + await waitFor(() => + expect( + screen.queryByRole('button', { name: 'Done', hidden: true }), + ).not.toBeInTheDocument(), + ); + }); + + it('does not open the popover for an invalid pill', async () => { + renderWithMantine( +
popover content
} + data-testid="pill" + />, + ); + expect(screen.getByTestId('pill')).toHaveAttribute('data-invalid', 'true'); + await userEvent.click(screen.getByTestId('pill')); + expect(screen.queryByText('popover content')).not.toBeInTheDocument(); + }); +}); diff --git a/packages/app/src/components/FilterPill/__tests__/FilterValueEditor.test.tsx b/packages/app/src/components/FilterPill/__tests__/FilterValueEditor.test.tsx new file mode 100644 index 0000000000..2e0a07eee1 --- /dev/null +++ b/packages/app/src/components/FilterPill/__tests__/FilterValueEditor.test.tsx @@ -0,0 +1,71 @@ +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { + FilterValueEditor, + FilterValueEditorProps, +} from '@/components/FilterPill/FilterValueEditor'; + +// Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks +// it. jsdom also has no layout, so options must be queried with { hidden: true }. +window.HTMLElement.prototype.scrollIntoView = jest.fn(); + +const renderEditor = (props: Partial = {}) => { + const handlers = { + onReplaceValue: jest.fn(), + onTogglePolarity: jest.fn(), + onDone: jest.fn(), + }; + renderWithMantine( + , + ); + return handlers; +}; + +const valueInput = () => + screen.getByRole('combobox', { name: 'Change filter value' }); + +describe('FilterValueEditor', () => { + it('lists the current value alongside the suggestions', async () => { + renderEditor({ valueOptions: ['404', '200'] }); + await userEvent.click(valueInput()); + const options = await screen.findAllByRole('option', { hidden: true }); + expect(options.map(o => o.textContent)).toEqual(['200', '404']); + }); + + it('replaces with the trimmed typed value', async () => { + const { onReplaceValue, onDone } = renderEditor(); + await userEvent.type(valueInput(), ' 418 {enter}'); + expect(onReplaceValue).toHaveBeenCalledWith('418'); + expect(onDone).toHaveBeenCalled(); + }); + + it('does not replace when the value is unchanged or empty', async () => { + const { onReplaceValue, onDone } = renderEditor(); + await userEvent.type(valueInput(), '{enter}'); + await userEvent.type(valueInput(), '200{enter}'); + expect(onReplaceValue).not.toHaveBeenCalled(); + expect(onDone).toHaveBeenCalledTimes(2); + }); + + it('shows a loading placeholder while values load', () => { + renderEditor({ isLoadingValues: true }); + expect(valueInput()).toHaveAttribute('placeholder', 'Loading values...'); + }); + + it.each([ + [false, 'Exclude'], + [true, 'Include'], + ])('offers to flip polarity (excluded: %s)', async (isExcluded, label) => { + const { onTogglePolarity, onDone } = renderEditor({ isExcluded }); + await userEvent.click(screen.getByRole('button', { name: label })); + expect(onTogglePolarity).toHaveBeenCalled(); + expect(onDone).toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/FilterPill/filterOperators.ts b/packages/app/src/components/FilterPill/filterOperators.ts new file mode 100644 index 0000000000..e766e247bd --- /dev/null +++ b/packages/app/src/components/FilterPill/filterOperators.ts @@ -0,0 +1,34 @@ +import type { FilterOperatorOption } from './FilterConditionEditor'; + +export type FilterLanguage = 'sql' | 'promql'; + +/** One spelling for both languages; each preset's labels show its own wording. */ +export type FilterOperator = '=' | '!=' | '=~' | '!~' | 'LIKE' | 'NOT LIKE'; + +const REGEX_VALUE = { + valueLabel: 'Pattern', + valuePlaceholder: 'Regular expression', +}; +const LIKE_VALUE = { valuePlaceholder: 'Text the value contains' }; + +export const SQL_FILTER_OPERATORS: FilterOperatorOption[] = [ + { value: '=', label: '=' }, + { value: '!=', label: '!=', negated: true }, + { value: '=~', label: 'regex', ...REGEX_VALUE }, + { value: '!~', label: 'not regex', negated: true, ...REGEX_VALUE }, + { value: 'LIKE', label: 'like', ...LIKE_VALUE }, + { value: 'NOT LIKE', label: 'not like', negated: true, ...LIKE_VALUE }, +]; + +export const PROMQL_FILTER_OPERATORS: FilterOperatorOption[] = [ + { value: '=', label: '=' }, + { value: '!=', label: '!=', negated: true }, + { value: '=~', label: '=~', ...REGEX_VALUE }, + { value: '!~', label: '!~', negated: true, ...REGEX_VALUE }, +]; + +export function getFilterOperators( + language: FilterLanguage, +): FilterOperatorOption[] { + return language === 'promql' ? PROMQL_FILTER_OPERATORS : SQL_FILTER_OPERATORS; +} diff --git a/packages/app/src/components/FilterPill/index.ts b/packages/app/src/components/FilterPill/index.ts new file mode 100644 index 0000000000..ee08a1a354 --- /dev/null +++ b/packages/app/src/components/FilterPill/index.ts @@ -0,0 +1,5 @@ +export * from './FilterAutocomplete'; +export * from './FilterConditionEditor'; +export * from './filterOperators'; +export * from './FilterPill'; +export * from './FilterValueEditor'; diff --git a/packages/app/src/mocks/filterValues.ts b/packages/app/src/mocks/filterValues.ts new file mode 100644 index 0000000000..ebfa8eabe2 --- /dev/null +++ b/packages/app/src/mocks/filterValues.ts @@ -0,0 +1,38 @@ +import { useEffect, useState } from 'react'; + +export const MOCK_SQL_VALUES: Record = { + ServiceName: ['checkout', 'frontend', 'payment', 'cart', 'shipping'], + SeverityText: ['debug', 'info', 'warn', 'error', 'fatal'], + StatusCode: ['200', '201', '301', '400', '404', '500', '503'], + "LogAttributes['http.method']": ['GET', 'POST', 'PUT', 'DELETE'], + "ResourceAttributes['k8s.namespace.name']": ['default', 'otel', 'prod'], +}; + +export const MOCK_PROMQL_VALUES: Record = { + job: ['api', 'node-exporter', 'otel-collector'], + instance: ['10.0.0.1:9100', '10.0.0.2:9100', '10.0.0.3:9100'], + namespace: ['default', 'otel', 'prod'], + status_code: ['200', '404', '500'], +}; + +/** Serves mock values for a key after a delay, like a metadata query. */ +export function useMockValues( + values: Record, + key: string, + delayMs = 400, +) { + const [state, setState] = useState<{ key: string; data: string[] }>({ + key: '', + data: [], + }); + useEffect(() => { + if (!key) return; + const timer = setTimeout( + () => setState({ key, data: values[key] ?? [] }), + delayMs, + ); + return () => clearTimeout(timer); + }, [values, key, delayMs]); + const isLoading = !!key && state.key !== key; + return { data: isLoading ? [] : state.data, isLoading }; +}