From 65876701c27680d139c00c3c2ea7a8393b4dddad Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 11:56:36 +0100 Subject: [PATCH 01/14] feat(app): put select and order by on the results table Those clauses and the table actions belong with the results table. They stay hidden on Event Deltas and Event Patterns. Co-authored-by: Cursor --- packages/app/src/DBSearchPage.tsx | 96 +++++---- packages/app/src/components/DBRowTable.tsx | 189 ++++++++++-------- .../components/DBSqlRowTableWithSidebar.tsx | 8 +- .../app/tests/e2e/page-objects/SearchPage.ts | 6 +- 4 files changed, 181 insertions(+), 118 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index e7a257d397..8cbb32d7ba 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2209,6 +2209,48 @@ function DBSearchPageContent() { [setValue, setNewSourceModalClosed], ); + // SELECT and ORDER BY shape the results table, so they sit on that table + // and stay hidden on Event Deltas and Event Patterns. + const resultsClauseEditors = + analysisMode === 'results' ? ( + + + + + + + + + ) : null; + return ( setIsSourceSchemaPreviewOpen(false)} /> - - - - - - <> {!savedSearchId ? ( + + + + setMode(value === 'sql' ? 'sql' : 'pick')} + data={MODE_OPTIONS} + data-testid={`${testId}-mode`} + /> + {mode === 'pick' ? renderPick(apply) : renderSql(apply)} + + + + + + + + ); +} diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx new file mode 100644 index 0000000000..bcd1fd422d --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -0,0 +1,149 @@ +import { useMemo, useState } from 'react'; +import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { + ActionIcon, + Autocomplete, + Group, + ScrollArea, + Stack, + Text, +} from '@mantine/core'; +import { IconColumns, IconX } from '@tabler/icons-react'; + +import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; +import { withMapKeyAlias } from '@/utils'; + +import { ClausePopover } from './ClausePopover'; + +export function ColumnsPopover({ + value, + defaultValue, + fieldOptions, + knownColumns, + onApply, + tableConnection, + sourceId, + dateRange, +}: { + /** The SELECT expression in the search form. */ + value: string; + /** The source's SELECT, used while `value` is empty. */ + defaultValue: string; + fieldOptions: string[]; + knownColumns: Set; + /** Called with the new SELECT and the items it no longer contains. */ + onApply: (select: string, removedItems: string[]) => void; + tableConnection: TableConnection | undefined; + sourceId?: string; + dateRange?: [Date, Date]; +}) { + const [draft, setDraft] = useState(value); + const [search, setSearch] = useState(''); + + const effective = (select: string) => + splitAndTrimWithBracket(select || defaultValue); + + const count = effective(value).length; + const items = effective(draft); + + const options = useMemo( + () => fieldOptions.filter(option => !items.includes(option)), + [fieldOptions, items], + ); + + const addColumn = (column: string) => { + const trimmed = column.trim(); + if (!trimmed) return; + setDraft( + [...items, withMapKeyAlias(trimmed, items, knownColumns)].join(', '), + ); + setSearch(''); + }; + + const removeColumn = (item: string) => { + setDraft(items.filter(i => i !== item).join(', ')); + }; + + return ( + 0 ? `Columns (${count})` : 'Columns'} + title={value || defaultValue} + icon={} + initialMode="pick" + onOpen={() => { + setDraft(value); + setSearch(''); + }} + onApply={() => { + const next = effective(draft); + onApply( + draft, + effective(value).filter(item => !next.includes(item)), + ); + }} + data-testid="search-columns-button" + renderPick={() => ( + + + {items.length === 0 ? ( + + No columns selected. + + ) : ( + + {items.map(item => ( + + + {item} + + removeColumn(item)} + aria-label={`Remove ${item}`} + > + + + + ))} + + )} + + + + )} + renderSql={apply => ( +
+ +
+ )} + /> + ); +} diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx new file mode 100644 index 0000000000..d7fe3e119d --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -0,0 +1,131 @@ +import { useState } from 'react'; +import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { + Autocomplete, + Group, + SegmentedControl, + Stack, + Text, +} from '@mantine/core'; +import { IconArrowsSort } from '@tabler/icons-react'; + +import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; +import { parseAsSortingStateString } from '@/utils/queryParsers'; + +import { ClausePopover } from './ClausePopover'; + +const DIRECTION_OPTIONS = [ + { label: 'Asc', value: 'asc' }, + { label: 'Desc', value: 'desc' }, +]; + +/** A single `field ASC|DESC` key, or null for anything the picker can't edit. */ +function parseSimpleSort(orderBy: string) { + const parsed = parseAsSortingStateString.parse(orderBy); + if ( + parsed == null || + parsed.id.startsWith('(') || + splitAndTrimWithBracket(orderBy).length !== 1 + ) { + return null; + } + return parsed; +} + +export function SortPopover({ + value, + defaultValue, + fieldOptions, + onApply, + tableConnection, + sourceId, + dateRange, +}: { + /** The ORDER BY expression in the search form. */ + value: string; + /** The source's ORDER BY, used while `value` is empty. */ + defaultValue: string; + fieldOptions: string[]; + onApply: (orderBy: string) => void; + tableConnection: TableConnection | undefined; + sourceId?: string; + dateRange?: [Date, Date]; +}) { + const [draft, setDraft] = useState(value); + + const current = parseSimpleSort(value || defaultValue); + const parsed = parseSimpleSort(draft || defaultValue); + const [field, setField] = useState(parsed?.id ?? ''); + + const setPick = (id: string, desc: boolean) => { + setField(id); + if (id.trim()) { + setDraft(parseAsSortingStateString.serialize({ id: id.trim(), desc })); + } + }; + + return ( + } + initialMode={current != null ? 'pick' : 'sql'} + onOpen={() => { + setDraft(value); + setField(current?.id ?? ''); + }} + onApply={() => onApply(draft)} + data-testid="search-sort-button" + renderPick={() => ( + + {parsed == null && ( + + Custom sort. Edit it in SQL, or pick a field to replace it. + + )} + + setPick(id, parsed?.desc ?? true)} + data={fieldOptions} + limit={50} + comboboxProps={{ withinPortal: false }} + style={{ flex: 1 }} + data-testid="search-sort-field-input" + /> + setPick(field, direction === 'desc')} + data={DIRECTION_OPTIONS} + data-testid="search-sort-direction" + /> + + + )} + renderSql={apply => ( + + + + )} + /> + ); +} diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx new file mode 100644 index 0000000000..fe5fa9687e --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -0,0 +1,100 @@ +import React from 'react'; +import { MantineProvider } from '@mantine/core'; +import { fireEvent, render, screen, waitFor } from '@testing-library/react'; + +import { ColumnsPopover } from '@/components/SearchResultsToolbar/ColumnsPopover'; + +jest.mock('@/components/SQLEditor/SQLInlineEditor', () => ({ + __esModule: true, + default: ({ + value, + onChange, + label, + }: { + value: string; + onChange: (value: string) => void; + label: string; + }) => ( + onChange(e.target.value)} + /> + ), +})); + +function renderPopover( + props: Partial> = {}, +) { + const onApply = jest.fn(); + render( + + + , + ); + return { onApply }; +} + +const openPopover = () => + fireEvent.click(screen.getByTestId('search-columns-button')); + +describe('ColumnsPopover', () => { + it('shows the column count and falls back to the default SELECT', () => { + renderPopover({ value: '' }); + expect(screen.getByTestId('search-columns-button')).toHaveTextContent( + 'Columns (3)', + ); + }); + + it('removes a column and reports it on apply', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByLabelText('Remove Body')); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith('Timestamp', ['Body']); + }); + + it('adds a picked field', async () => { + const { onApply } = renderPopover(); + openPopover(); + const input = await screen.findByPlaceholderText('Add column'); + fireEvent.change(input, { target: { value: 'Severity' } }); + fireEvent.click(await screen.findByText('SeverityText')); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith('Timestamp, Body, SeverityText', []); + }); + + it('edits the SELECT on the SQL tab', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByText('SQL')); + fireEvent.change(screen.getByLabelText('SELECT'), { + target: { value: 'count()' }, + }); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith('count()', ['Timestamp', 'Body']); + }); + + it('discards the draft on cancel', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByLabelText('Remove Body')); + fireEvent.click(screen.getByText('Cancel')); + await waitFor(() => + expect( + screen.queryByTestId('search-columns-button-popover'), + ).not.toBeInTheDocument(), + ); + openPopover(); + expect(await screen.findByLabelText('Remove Body')).toBeInTheDocument(); + expect(onApply).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx new file mode 100644 index 0000000000..fbb42523b6 --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -0,0 +1,92 @@ +import React from 'react'; +import { MantineProvider } from '@mantine/core'; +import { fireEvent, render, screen } from '@testing-library/react'; + +import { SortPopover } from '@/components/SearchResultsToolbar/SortPopover'; + +jest.mock('@/components/SQLEditor/SQLInlineEditor', () => ({ + __esModule: true, + default: ({ + value, + onChange, + label, + }: { + value: string; + onChange: (value: string) => void; + label: string; + }) => ( + onChange(e.target.value)} + /> + ), +})); + +function renderPopover( + props: Partial> = {}, +) { + const onApply = jest.fn(); + render( + + + , + ); + return { onApply }; +} + +const openPopover = () => + fireEvent.click(screen.getByTestId('search-sort-button')); + +describe('SortPopover', () => { + it('labels the button with the parsed field and direction', () => { + renderPopover({ value: 'Body ASC' }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + 'Sort: Body asc', + ); + }); + + it('flips the direction from the picker', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByText('Asc')); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith('Timestamp ASC'); + }); + + it('opens on the SQL tab for a custom ORDER BY', async () => { + const custom = '(TimestampTime, Timestamp) DESC'; + const { onApply } = renderPopover({ value: custom, defaultValue: custom }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + /^Sort$/, + ); + openPopover(); + const editor = await screen.findByLabelText('ORDER BY'); + expect(editor).toHaveValue(custom); + fireEvent.change(editor, { target: { value: 'Body ASC' } }); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith('Body ASC'); + }); + + it('treats a multi-key ORDER BY as custom', () => { + renderPopover({ value: 'ServiceName ASC, Timestamp DESC' }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + /^Sort$/, + ); + }); + + it('does not apply on cancel', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByText('Asc')); + fireEvent.click(screen.getByText('Cancel')); + expect(onApply).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts b/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts new file mode 100644 index 0000000000..a7c15d4f44 --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts @@ -0,0 +1,36 @@ +import { useMemo } from 'react'; +import { ColumnMeta } from '@hyperdx/common-utils/dist/clickhouse'; +import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; + +import { + getSqlSourceColumnKeys, + getSqlSourceKeys, +} from '@/components/AdhocDashboardFilter/useAdhocFilterOptions'; +import { useAllFields } from '@/hooks/useMetadata'; + +/** The source's fields as SQL expressions, for the Pick tabs. */ +export function useClauseFieldOptions({ + tableConnection, + columns, + dateRange, + timestampValueExpression, +}: { + tableConnection: TableConnection | undefined; + columns: ColumnMeta[] | undefined; + dateRange?: [Date, Date]; + timestampValueExpression?: string; +}): string[] { + const { data: fields } = useAllFields(tableConnection, { + dateRange, + timestampValueExpression, + }); + + return useMemo(() => { + if (columns == null) return []; + const keys = + fields != null + ? getSqlSourceKeys(fields, columns) + : getSqlSourceColumnKeys(columns); + return Array.from(new Set(keys)).sort(); + }, [fields, columns]); +} diff --git a/packages/app/tests/e2e/features/search/saved-search.spec.ts b/packages/app/tests/e2e/features/search/saved-search.spec.ts index 9201f730d3..610c189a2c 100644 --- a/packages/app/tests/e2e/features/search/saved-search.spec.ts +++ b/packages/app/tests/e2e/features/search/saved-search.spec.ts @@ -98,10 +98,10 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify custom SELECT is preserved', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'upper(ServiceName) as service_name', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('upper(ServiceName) as service_name'); }); }, ); @@ -140,11 +140,11 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify different source has its own default SELECT', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).not.toContainText( - 'lower(Body) as body_lower', - ); - await expect(selectEditor).toContainText('Timestamp'); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .not.toContain('lower(Body) as body_lower'); + await expect.poll(selectValue).toContain('Timestamp'); }); await test.step('Navigate back to saved search', async () => { @@ -153,12 +153,12 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify saved search SELECT is restored', async () => { - const selectEditor = searchPage.getSELECTEditor(); + const selectValue = () => searchPage.getSelectValue(); // Verifies the fix: SELECT restores to saved search's custom value - await expect(selectEditor).toContainText('lower(Body) as body_lower'); - await expect(selectEditor).toContainText( - 'Timestamp, Body, lower(Body)', - ); + await expect.poll(selectValue).toContain('lower(Body) as body_lower'); + await expect + .poll(selectValue) + .toContain('Timestamp, Body, lower(Body)'); }); }, ); @@ -186,11 +186,11 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify SELECT changed to the new source default', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).not.toContainText( - 'lower(ServiceName) as service_name', - ); - await expect(selectEditor).toContainText('Timestamp'); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .not.toContain('lower(ServiceName) as service_name'); + await expect.poll(selectValue).toContain('Timestamp'); }); await test.step('Switch back to original source via dropdown', async () => { @@ -201,10 +201,10 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify SELECT is search custom SELECT', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'lower(ServiceName) as service_name', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('lower(ServiceName) as service_name'); }); }, ); @@ -255,9 +255,9 @@ test.describe('Saved Search Functionality', () => { expect(savedSearchParams.has('to')).toBe(false); await expect(searchPage.input).toHaveValue('SeverityText:info'); - await expect(searchPage.getOrderByEditor()).toContainText( - customOrderBy, - ); + await expect + .poll(() => searchPage.getOrderByValue()) + .toContain(customOrderBy); // Capture the saved search URL (without query params) savedSearchUrl = page.url().split('?')[0]; @@ -289,8 +289,8 @@ test.describe('Saved Search Functionality', () => { await expect(whereInput).toHaveValue('SeverityText:info'); // Verify ORDER BY is restored - const orderByEditor = searchPage.getOrderByEditor(); - await expect(orderByEditor).toContainText('ServiceName ASC'); + const orderByValue = () => searchPage.getOrderByValue(); + await expect.poll(orderByValue).toContain('ServiceName ASC'); // Verify search results are visible (search executed automatically) await searchPage.table.waitForRowsToPopulate(); @@ -343,11 +343,11 @@ test.describe('Saved Search Functionality', () => { await searchPage.table.waitForRowsToPopulate(true); // Verify SELECT content - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'upper(ServiceName) as service_name', - ); - await expect(selectEditor).toContainText('Timestamp, Body'); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('upper(ServiceName) as service_name'); + await expect.poll(selectValue).toContain('Timestamp, Body'); }); }, ); @@ -401,9 +401,9 @@ test.describe('Saved Search Functionality', () => { }); await test.step('The tweak survives, in the form and in the URL', async () => { - await expect(searchPage.getSELECTEditor()).toContainText( - 'lower(Body) as body_lower', - ); + await expect + .poll(() => searchPage.getSelectValue()) + .toContain('lower(Body) as body_lower'); expect(new URL(page.url()).searchParams.get('select')).toContain( 'lower(Body)', ); @@ -427,10 +427,10 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify default SELECT is loaded', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'Timestamp, ServiceName, SeverityText, Body', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('Timestamp, ServiceName, SeverityText, Body'); }); await test.step('Navigate to dashboards page', async () => { @@ -444,10 +444,10 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify default SELECT is loaded', async () => { - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'Timestamp, ServiceName, SeverityText, Body', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('Timestamp, ServiceName, SeverityText, Body'); }); }, ); @@ -531,16 +531,16 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify ORDER BY changed to second source default', async () => { - const orderByEditor = searchPage.getOrderByEditor(); + const orderByValue = () => searchPage.getOrderByValue(); // Should not contain the custom ORDER BY from the saved search - await expect(orderByEditor).not.toHaveText('Body DESC', { - timeout: 5000, - }); - await expect(orderByEditor).toHaveText(/(Timestamp|timestamp)/i, { - timeout: 5000, - }); + await expect + .poll(orderByValue, { timeout: 5000 }) + .not.toBe('Body DESC'); + await expect + .poll(orderByValue, { timeout: 5000 }) + .toMatch(/(Timestamp|timestamp)/i); }); await test.step('Switch back to original source', async () => { @@ -556,8 +556,8 @@ test.describe('Saved Search Functionality', () => { }); await test.step('Verify ORDER BY restored to saved search custom value', async () => { - const orderByEditor = searchPage.getOrderByEditor(); - await expect(orderByEditor).toHaveText('Body DESC', { timeout: 5000 }); + const orderByValue = () => searchPage.getOrderByValue(); + await expect.poll(orderByValue, { timeout: 5000 }).toBe('Body DESC'); }); }, ); @@ -780,10 +780,10 @@ test.describe('Saved Search Functionality', () => { await test.step('Verify the new search preserved the SELECT', async () => { await searchPage.table.waitForRowsToPopulate(); - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'upper(ServiceName) as service_upper', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('upper(ServiceName) as service_upper'); }); await test.step('Verify the new search preserved the WHERE', async () => { @@ -796,10 +796,10 @@ test.describe('Saved Search Functionality', () => { await searchPage.table.waitForRowsToPopulate(); await expect(searchPage.input).toHaveValue('SeverityText:info'); - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toContainText( - 'upper(ServiceName) as service_upper', - ); + const selectValue = () => searchPage.getSelectValue(); + await expect + .poll(selectValue) + .toContain('upper(ServiceName) as service_upper'); }); }, ); diff --git a/packages/app/tests/e2e/features/search/search.spec.ts b/packages/app/tests/e2e/features/search/search.spec.ts index 3f72a5cba8..7ed7f20497 100644 --- a/packages/app/tests/e2e/features/search/search.spec.ts +++ b/packages/app/tests/e2e/features/search/search.spec.ts @@ -314,10 +314,7 @@ test.describe('Search', { tag: '@search' }, () => { expect(url, 'URL should contain select parameter').toContain('select='); expect(url, 'URL should contain alias "message"').toContain('message'); - // Verify SELECT editor content using page object - const selectEditor = searchPage.getSELECTEditor(); - await expect(selectEditor).toBeVisible(); - const selectValue = await selectEditor.textContent(); + const selectValue = await searchPage.getSelectValue(); expect(selectValue, 'SELECT should contain alias').toContain( 'Body as message', diff --git a/packages/app/tests/e2e/features/shared/input-focus.spec.ts b/packages/app/tests/e2e/features/shared/input-focus.spec.ts index 984d80f7ea..1812e7ce83 100644 --- a/packages/app/tests/e2e/features/shared/input-focus.spec.ts +++ b/packages/app/tests/e2e/features/shared/input-focus.spec.ts @@ -41,12 +41,14 @@ test.describe('Query input focus states', { tag: '@search' }, () => { const searchPage = new SearchPage(page); await searchPage.goto(); + await searchPage.openSelectEditor(); const selectBlurred = await searchPage.getSelectBorderColor(); await searchPage.getSELECTEditor().focus(); await expect .poll(() => searchPage.getSelectBorderColor()) .not.toBe(selectBlurred); + await searchPage.openOrderByEditor(); const orderByBlurred = await searchPage.getOrderByBorderColor(); await searchPage.getOrderByEditor().focus(); await expect diff --git a/packages/app/tests/e2e/features/shared/multiline.spec.ts b/packages/app/tests/e2e/features/shared/multiline.spec.ts index 0696d75cef..df0df202bb 100644 --- a/packages/app/tests/e2e/features/shared/multiline.spec.ts +++ b/packages/app/tests/e2e/features/shared/multiline.spec.ts @@ -60,10 +60,11 @@ test.describe('Multiline Input', { tag: '@search' }, () => { const searchPage = new SearchPage(page); await searchPage.goto(); - for (const field of [ - searchPage.selectClauseField(), - searchPage.orderByClauseField(), - ]) { + for (const [open, field] of [ + [() => searchPage.openSelectEditor(), searchPage.selectClauseField()], + [() => searchPage.openOrderByEditor(), searchPage.orderByClauseField()], + ] as const) { + await open(); await expect(field.focusTarget).toBeVisible(); await searchPage.clearClause(field); await expectExpandsAndStaysExpanded(page, field); diff --git a/packages/app/tests/e2e/page-objects/SearchPage.ts b/packages/app/tests/e2e/page-objects/SearchPage.ts index 4c79e3bf99..74c7ebfa85 100644 --- a/packages/app/tests/e2e/page-objects/SearchPage.ts +++ b/packages/app/tests/e2e/page-objects/SearchPage.ts @@ -450,13 +450,55 @@ export class SearchPage { return this.whereInput.borderColors(); } + get columnsButton() { + return this.page.getByTestId('search-columns-button'); + } + + get sortButton() { + return this.page.getByTestId('search-sort-button'); + } + + /** The SELECT the table runs with; the Columns button carries it as its title. */ + async getSelectValue(): Promise { + return (await this.columnsButton.getAttribute('title')) ?? ''; + } + + async getOrderByValue(): Promise { + return (await this.sortButton.getAttribute('title')) ?? ''; + } + /** - * Get SELECT editor (CodeMirror) + * Get SELECT editor (CodeMirror). It lives on the SQL tab of the Columns + * popover, so call `openSelectEditor` first. */ getSELECTEditor() { return this.page.getByTestId('search-select-input').locator('.cm-content'); } + async openSelectEditor() { + return this.openClauseSqlTab( + 'search-columns-button', + this.getSELECTEditor(), + ); + } + + async openOrderByEditor() { + return this.openClauseSqlTab('search-sort-button', this.getOrderByEditor()); + } + + private async openClauseSqlTab(testId: string, editor: Locator) { + const popover = this.page.getByTestId(`${testId}-popover`); + if (!(await popover.isVisible())) { + await this.page.getByTestId(testId).click(); + } + await popover + .getByTestId(`${testId}-mode`) + .getByText('SQL', { exact: true }) + .click(); + await editor.waitFor({ state: 'visible' }); + return editor; + } + async getSelectBorderColor(): Promise { return this.selectClauseField().visibleBox.evaluate( el => getComputedStyle(el).borderTopColor, @@ -502,29 +544,36 @@ export class SearchPage { } /** - * Set custom SELECT columns + * Set custom SELECT columns through the Columns popover's SQL tab and apply + * it, which also runs the search. */ async setCustomSELECT(selectStatement: string) { - const selectEditor = this.getSELECTEditor(); + const selectEditor = await this.openSelectEditor(); await selectEditor.click({ clickCount: 3 }); // Select all // Insert atomically rather than per-keystroke: under load CodeMirror can // drop individual keys from keyboard.type (e.g. "Timestamp" -> "Timstamp"), // which then gets faithfully saved and fails later assertions. await this.page.keyboard.insertText(selectStatement); - // Dismiss the autocomplete popup so it can't linger and overlay the next - // control (e.g. the Save Search button). - await dismissSqlAutocomplete(this.page); + await this.applyClause('search-columns-button'); } /** - * Set custom ORDER BY clause + * Set custom ORDER BY through the Sort popover's SQL tab and apply it. */ async setCustomOrderBy(orderByStatement: string) { - const orderByEditor = this.getOrderByEditor(); + const orderByEditor = await this.openOrderByEditor(); await orderByEditor.click({ clickCount: 3 }); // Select all - await this.page.keyboard.type(orderByStatement); - // CLoses Autocomplete Modal if open - await this.page.keyboard.press('Escape'); + await this.page.keyboard.insertText(orderByStatement); + await this.applyClause('search-sort-button'); + } + + private async applyClause(testId: string) { + // Blur rather than Escape: Escape also closes the popover, dropping the draft. + await dismissSqlAutocomplete(this.page); + await this.page.getByTestId(`${testId}-apply`).click(); + await this.page + .getByTestId(`${testId}-popover`) + .waitFor({ state: 'hidden' }); } /** From e6459aa2b5c53889f9da5779018f81cc7b3e693d Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 13:15:11 +0100 Subject: [PATCH 03/14] feat(app): refine columns and sort popovers and the search form row Show the source SELECT and ORDER BY as editor text, add a column only when Add is clicked, and let columns be reordered. Sort pick lists tuple fields, including function calls. Both popovers can reset to the source default. The search form keeps WHERE on its own line, with Update and Alerts at the end of the source row. Co-authored-by: Cursor --- packages/app/src/DBSearchPage.tsx | 71 +++-- .../SearchResultsToolbar/ClausePopover.tsx | 40 ++- .../SearchResultsToolbar/ColumnsPopover.tsx | 203 +++++++++++--- .../SearchResultsToolbar/SortPopover.tsx | 258 ++++++++++++++---- .../__tests__/ColumnsPopover.test.tsx | 60 +++- .../__tests__/SortPopover.test.tsx | 81 +++++- 6 files changed, 560 insertions(+), 153 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 5f1f3c6c4e..98cfede1de 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2408,7 +2408,7 @@ function DBSearchPageContent() { className={searchPageStyles.searchForm} > {/* */} - + - setIsSourceSchemaPreviewOpen(false)} - /> - <> + {!savedSearchId ? ( @@ -2450,7 +2443,6 @@ function DBSearchPageContent() { onClick={() => { setSaveSearchModalState('update'); }} - style={{ flexShrink: 0 }} > Update @@ -2461,7 +2453,6 @@ function DBSearchPageContent() { variant="secondary" size="xs" onClick={openAlertModal} - style={{ flexShrink: 0 }} > Alerts @@ -2469,33 +2460,25 @@ function DBSearchPageContent() { )} - + - - - + + + + setIsSourceSchemaPreviewOpen(false)} + /> + + void; onApply: () => void; + /** Restore the source default in the draft. Apply still has to confirm it. */ + onReset: () => void; + resetDisabled?: boolean; renderPick: (apply: () => void) => ReactNode; renderSql: (apply: () => void) => ReactNode; 'data-testid': string; @@ -84,22 +89,33 @@ export function ClausePopover({ data-testid={`${testId}-mode`} /> {mode === 'pick' ? renderPick(apply) : renderSql(apply)} - + - + + + + diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index bcd1fd422d..1f5c51aa72 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -1,21 +1,96 @@ import { useMemo, useState } from 'react'; +import { + DndContext, + type DragEndEvent, + MouseSensor, + TouchSensor, + useSensor, + useSensors, +} from '@dnd-kit/core'; +import { + arrayMove, + SortableContext, + useSortable, + verticalListSortingStrategy, +} from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; import { ActionIcon, Autocomplete, + Box, + Button, Group, ScrollArea, Stack, Text, } from '@mantine/core'; -import { IconColumns, IconX } from '@tabler/icons-react'; +import { IconColumns, IconGripVertical, IconX } from '@tabler/icons-react'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; import { withMapKeyAlias } from '@/utils'; import { ClausePopover } from './ClausePopover'; +const columnId = (item: string, index: number) => `${index}:${item}`; + +function SortableColumn({ + id, + label, + onRemove, +}: { + id: string; + label: string; + onRemove: () => void; +}) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); + + return ( + + + + + + + + {label} + + + + + + + + ); +} + export function ColumnsPopover({ value, defaultValue, @@ -54,10 +129,11 @@ export function ColumnsPopover({ const addColumn = (column: string) => { const trimmed = column.trim(); - if (!trimmed) return; - setDraft( - [...items, withMapKeyAlias(trimmed, items, knownColumns)].join(', '), - ); + if (trimmed && !items.includes(trimmed)) { + setDraft( + [...items, withMapKeyAlias(trimmed, items, knownColumns)].join(', '), + ); + } setSearch(''); }; @@ -65,6 +141,23 @@ export function ColumnsPopover({ setDraft(items.filter(i => i !== item).join(', ')); }; + const columnIds = items.map(columnId); + const sensors = useSensors( + useSensor(MouseSensor, { activationConstraint: { distance: 8 } }), + useSensor(TouchSensor, { + activationConstraint: { delay: 200, tolerance: 5 }, + }), + ); + + const reorderColumns = (event: DragEndEvent) => { + const { active, over } = event; + if (!over || active.id === over.id) return; + const from = columnIds.indexOf(String(active.id)); + const to = columnIds.indexOf(String(over.id)); + if (from === -1 || to === -1) return; + setDraft(arrayMove(items, from, to).join(', ')); + }; + return ( 0 ? `Columns (${count})` : 'Columns'} @@ -72,13 +165,29 @@ export function ColumnsPopover({ icon={} initialMode="pick" onOpen={() => { - setDraft(value); + // The form stores "" while the source default is in use. Show that + // default as the editor value; Apply keeps "" unless it was edited. + setDraft(value || defaultValue); setSearch(''); }} + onReset={() => { + setDraft(defaultValue); + setSearch(''); + }} + resetDisabled={draft.trim() === defaultValue.trim()} onApply={() => { - const next = effective(draft); + const baseline = value || defaultValue; + // An empty form value means "use the source default", so resetting + // stores "" instead of a copy of that default. + const submitted = + draft.trim() === defaultValue.trim() + ? '' + : draft === baseline + ? value + : draft; + const next = effective(submitted); onApply( - draft, + submitted, effective(value).filter(item => !next.includes(item)), ); }} @@ -91,41 +200,51 @@ export function ColumnsPopover({ No columns selected. ) : ( - - {items.map(item => ( - - - {item} - - removeColumn(item)} - aria-label={`Remove ${item}`} - > - - - - ))} - + + + + {items.map((item, index) => ( + removeColumn(item)} + /> + ))} + + + )} - + + + + + + Select a column, or type an expression such as upper(Body) as + message, then click Add. + )} renderSql={apply => ( @@ -134,7 +253,7 @@ export function ColumnsPopover({ tableConnection={tableConnection} value={draft} onChange={setDraft} - placeholder={defaultValue || 'SELECT Columns'} + placeholder="SELECT" onSubmit={apply} label="SELECT" size="xs" diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index d7fe3e119d..a044b730cb 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -1,14 +1,16 @@ -import { useState } from 'react'; +import { useRef, useState } from 'react'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; import { + ActionIcon, Autocomplete, Group, + ScrollArea, SegmentedControl, Stack, Text, } from '@mantine/core'; -import { IconArrowsSort } from '@tabler/icons-react'; +import { IconArrowsSort, IconX } from '@tabler/icons-react'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; import { parseAsSortingStateString } from '@/utils/queryParsers'; @@ -20,17 +22,67 @@ const DIRECTION_OPTIONS = [ { label: 'Desc', value: 'desc' }, ]; -/** A single `field ASC|DESC` key, or null for anything the picker can't edit. */ -function parseSimpleSort(orderBy: string) { - const parsed = parseAsSortingStateString.parse(orderBy); - if ( - parsed == null || - parsed.id.startsWith('(') || - splitAndTrimWithBracket(orderBy).length !== 1 - ) { - return null; +type SortKey = { id: string; desc: boolean }; +type SortRow = SortKey & { rowId: string }; + +let rowSeq = 0; +const toRows = (keys: SortKey[] | null): SortRow[] | null => + keys?.map(key => ({ ...key, rowId: `sort-${rowSeq++}` })) ?? null; + +/** + * Sort keys the picker can edit. A parenthesized list with one direction, + * `(toDateTime(Timestamp), Timestamp) DESC`, is several fields sharing that + * direction, including function calls. Anything without a plain ASC/DESC on + * each field stays in SQL. + */ +function parseSortKeys(orderBy: string): SortKey[] | null { + const trimmed = orderBy.trim(); + if (!trimmed) return []; + + const tuple = trimmed.match(/^\(([\s\S]+)\)\s+(asc|desc)$/i); + if (tuple) { + const ids = splitAndTrimWithBracket(tuple[1]); + if (ids.length > 1 && ids.every(id => id.length > 0)) { + const desc = tuple[2].toUpperCase() === 'DESC'; + return ids.map(id => ({ id, desc })); + } + } + + const keys: SortKey[] = []; + for (const part of splitAndTrimWithBracket(trimmed)) { + const parsed = parseAsSortingStateString.parse(part); + if (parsed == null || parsed.id.length === 0) return null; + keys.push({ id: parsed.id, desc: parsed.desc }); + } + return keys; +} + +function serializeSortKeys(keys: SortKey[]) { + return keys + .filter(key => key.id.trim()) + .map(key => + parseAsSortingStateString.serialize({ + id: key.id.trim(), + desc: key.desc, + }), + ) + .join(', '); +} + +function sameKeys(a: SortKey[], b: SortKey[]) { + return ( + a.length === b.length && + a.every((key, i) => key.id === b[i].id && key.desc === b[i].desc) + ); +} + +function sortLabel(orderBy: string) { + const keys = parseSortKeys(orderBy); + if (keys == null || keys.length === 0) return 'Sort'; + if (keys.length === 1) { + return `Sort: ${keys[0].id} ${keys[0].desc ? 'desc' : 'asc'}`; } - return parsed; + return `Sort: ${keys.length} fields`; } export function SortPopover({ @@ -52,63 +104,152 @@ export function SortPopover({ sourceId?: string; dateRange?: [Date, Date]; }) { - const [draft, setDraft] = useState(value); + const shown = value || defaultValue; + const [draft, setDraft] = useState(shown); + const [keys, setKeys] = useState(() => + toRows(parseSortKeys(shown)), + ); + const [search, setSearch] = useState(''); + // Autocomplete writes the chosen option back into the input after + // onOptionSubmit. Ignore that write so the field clears. + const ignoreNextChangeRef = useRef(false); - const current = parseSimpleSort(value || defaultValue); - const parsed = parseSimpleSort(draft || defaultValue); - const [field, setField] = useState(parsed?.id ?? ''); + const baseline = value || defaultValue; + const used = new Set((keys ?? []).map(key => key.id)); + const addOptions = fieldOptions.filter(option => !used.has(option)); - const setPick = (id: string, desc: boolean) => { - setField(id); - if (id.trim()) { - setDraft(parseAsSortingStateString.serialize({ id: id.trim(), desc })); - } + const reset = () => { + const next = value || defaultValue; + setDraft(next); + setKeys(toRows(parseSortKeys(next))); + setSearch(''); + }; + + const commitKeys = (next: SortRow[]) => { + setKeys(next); + const originalKeys = parseSortKeys(baseline); + // Keep `(a, b) DESC` until a field actually changes, so Apply doesn't + // rewrite the source default into separate keys. + setDraft( + originalKeys != null && sameKeys(next, originalKeys) + ? baseline + : serializeSortKeys(next), + ); + }; + + const addKey = (id: string) => { + const trimmed = id.trim(); + if (!trimmed || used.has(trimmed)) return; + commitKeys([ + ...(keys ?? []), + { id: trimmed, desc: true, rowId: `sort-${rowSeq++}` }, + ]); + setSearch(''); }; return ( } - initialMode={current != null ? 'pick' : 'sql'} - onOpen={() => { - setDraft(value); - setField(current?.id ?? ''); + initialMode={parseSortKeys(baseline) != null ? 'pick' : 'sql'} + onOpen={reset} + onReset={() => { + setDraft(defaultValue); + setKeys(toRows(parseSortKeys(defaultValue))); + setSearch(''); }} - onApply={() => onApply(draft)} + resetDisabled={draft.trim() === defaultValue.trim()} + onApply={() => + onApply( + draft.trim() === defaultValue.trim() + ? '' + : draft === baseline + ? value + : draft, + ) + } data-testid="search-sort-button" renderPick={() => ( - {parsed == null && ( + {keys == null && ( - Custom sort. Edit it in SQL, or pick a field to replace it. + Custom sort. Edit it in SQL. )} - - setPick(id, parsed?.desc ?? true)} - data={fieldOptions} - limit={50} - comboboxProps={{ withinPortal: false }} - style={{ flex: 1 }} - data-testid="search-sort-field-input" - /> - setPick(field, direction === 'desc')} - data={DIRECTION_OPTIONS} - data-testid="search-sort-direction" - /> - + {keys != null && keys.length > 0 && ( + + + {keys.map((key, index) => ( + + { + const next = keys.slice(); + next[index] = { ...key, id }; + commitKeys(next); + }} + data={fieldOptions.filter( + option => option === key.id || !used.has(option), + )} + limit={50} + comboboxProps={{ withinPortal: false }} + style={{ flex: 1 }} + /> + { + const next = keys.slice(); + next[index] = { ...key, desc: direction === 'desc' }; + commitKeys(next); + }} + data={DIRECTION_OPTIONS} + data-testid="search-sort-direction" + /> + + commitKeys(keys.filter((_, i) => i !== index)) + } + aria-label={`Remove ${key.id}`} + > + + + + ))} + + + )} + { + if (ignoreNextChangeRef.current) { + ignoreNextChangeRef.current = false; + return; + } + setSearch(next); + }} + data={addOptions} + limit={50} + onOptionSubmit={id => { + ignoreNextChangeRef.current = true; + addKey(id); + }} + comboboxProps={{ withinPortal: false }} + data-testid="search-sort-add-input" + /> )} renderSql={apply => ( @@ -116,8 +257,11 @@ export function SortPopover({ { + setDraft(sql); + setKeys(toRows(parseSortKeys(sql))); + }} + placeholder="ORDER BY" onSubmit={apply} label="ORDER BY" size="xs" diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index fe5fa9687e..707246b1df 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -54,6 +54,15 @@ describe('ColumnsPopover', () => { ); }); + it('offers a drag handle for each column', async () => { + renderPopover(); + openPopover(); + expect( + await screen.findByLabelText('Reorder Timestamp'), + ).toBeInTheDocument(); + expect(screen.getByLabelText('Reorder Body')).toBeInTheDocument(); + }); + it('removes a column and reports it on apply', async () => { const { onApply } = renderPopover(); openPopover(); @@ -62,16 +71,63 @@ describe('ColumnsPopover', () => { expect(onApply).toHaveBeenCalledWith('Timestamp', ['Body']); }); - it('adds a picked field', async () => { + it('fills the input from a suggestion and adds only on Add', async () => { const { onApply } = renderPopover(); openPopover(); - const input = await screen.findByPlaceholderText('Add column'); + const input = await screen.findByPlaceholderText('Search columns'); fireEvent.change(input, { target: { value: 'Severity' } }); fireEvent.click(await screen.findByText('SeverityText')); + expect(input).toHaveValue('SeverityText'); + expect( + screen.queryByLabelText('Remove SeverityText'), + ).not.toBeInTheDocument(); + fireEvent.click(screen.getByTestId('search-columns-add-button')); + expect(input).toHaveValue(''); + expect(screen.getByLabelText('Remove SeverityText')).toBeInTheDocument(); fireEvent.click(screen.getByTestId('search-columns-button-apply')); expect(onApply).toHaveBeenCalledWith('Timestamp, Body, SeverityText', []); }); + it('adds a typed expression such as an alias', async () => { + const { onApply } = renderPopover(); + openPopover(); + const input = await screen.findByPlaceholderText('Search columns'); + fireEvent.change(input, { + target: { value: 'upper(Body) as message' }, + }); + fireEvent.click(screen.getByTestId('search-columns-add-button')); + expect(input).toHaveValue(''); + expect(screen.getByText('upper(Body) as message')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith( + 'Timestamp, Body, upper(Body) as message', + [], + ); + }); + + it('resets a changed column list to the source default', async () => { + const { onApply } = renderPopover(); + openPopover(); + fireEvent.click(await screen.findByLabelText('Remove Body')); + fireEvent.click(screen.getByTestId('search-columns-button-reset')); + expect(screen.getByLabelText('Remove ServiceName')).toBeInTheDocument(); + expect(screen.getByTestId('search-columns-button-reset')).toBeDisabled(); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith('', []); + }); + + it('shows the default SELECT as the SQL value', async () => { + renderPopover({ value: '' }); + openPopover(); + expect( + await screen.findByTestId('search-columns-button-reset'), + ).toBeDisabled(); + fireEvent.click(await screen.findByText('SQL')); + expect(screen.getByLabelText('SELECT')).toHaveValue( + 'Timestamp, ServiceName, Body', + ); + }); + it('edits the SELECT on the SQL tab', async () => { const { onApply } = renderPopover(); openPopover(); diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index fbb42523b6..49be9700da 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -61,8 +61,22 @@ describe('SortPopover', () => { expect(onApply).toHaveBeenCalledWith('Timestamp ASC'); }); + it('lists function calls inside a tuple sort', async () => { + const orderBy = '(toDateTime(Timestamp), Timestamp) DESC'; + renderPopover({ value: orderBy, defaultValue: orderBy }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + 'Sort: 2 fields', + ); + openPopover(); + expect( + await screen.findByDisplayValue('toDateTime(Timestamp)'), + ).toBeInTheDocument(); + expect(screen.getByDisplayValue('Timestamp')).toBeInTheDocument(); + expect(screen.queryByTestId('search-sort-custom')).not.toBeInTheDocument(); + }); + it('opens on the SQL tab for a custom ORDER BY', async () => { - const custom = '(TimestampTime, Timestamp) DESC'; + const custom = 'Timestamp DESC NULLS LAST'; const { onApply } = renderPopover({ value: custom, defaultValue: custom }); expect(screen.getByTestId('search-sort-button')).toHaveTextContent( /^Sort$/, @@ -70,16 +84,75 @@ describe('SortPopover', () => { openPopover(); const editor = await screen.findByLabelText('ORDER BY'); expect(editor).toHaveValue(custom); - fireEvent.change(editor, { target: { value: 'Body ASC' } }); + fireEvent.click(screen.getByText('Pick')); + expect(screen.getByTestId('search-sort-custom')).toBeInTheDocument(); + fireEvent.click(screen.getByText('SQL')); + fireEvent.change(screen.getByLabelText('ORDER BY'), { + target: { value: 'Body ASC' }, + }); fireEvent.click(screen.getByTestId('search-sort-button-apply')); expect(onApply).toHaveBeenCalledWith('Body ASC'); }); - it('treats a multi-key ORDER BY as custom', () => { + it('shows the source default as the SQL value, not a placeholder', async () => { + const orderBy = '(TimestampTime, Timestamp) DESC'; + const { onApply } = renderPopover({ value: '', defaultValue: orderBy }); + openPopover(); + fireEvent.click(await screen.findByText('SQL')); + expect(screen.getByLabelText('ORDER BY')).toHaveValue(orderBy); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith(''); + }); + + it('lists every field of a tuple sort and can add another', async () => { + const { onApply } = renderPopover({ + value: '', + defaultValue: '(TimestampTime, Timestamp) DESC', + fieldOptions: ['Body', 'Timestamp', 'TimestampTime'], + }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + 'Sort: 2 fields', + ); + openPopover(); + expect( + await screen.findByDisplayValue('TimestampTime'), + ).toBeInTheDocument(); + expect(screen.getByDisplayValue('Timestamp')).toBeInTheDocument(); + + const addSort = screen.getByPlaceholderText('Add sort'); + fireEvent.change(addSort, { + target: { value: 'Bo' }, + }); + fireEvent.click(await screen.findByText('Body')); + expect(addSort).toHaveValue(''); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith( + 'TimestampTime DESC, Timestamp DESC, Body DESC', + ); + }); + + it('lists every key of a multi-field sort', async () => { renderPopover({ value: 'ServiceName ASC, Timestamp DESC' }); expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - /^Sort$/, + 'Sort: 2 fields', ); + openPopover(); + expect(await screen.findByDisplayValue('ServiceName')).toBeInTheDocument(); + expect(screen.getByDisplayValue('Timestamp')).toBeInTheDocument(); + expect(screen.getByLabelText('Remove ServiceName')).toBeInTheDocument(); + }); + + it('resets a changed sort to the source default', async () => { + const { onApply } = renderPopover({ + value: 'Body ASC', + defaultValue: 'Timestamp DESC', + }); + openPopover(); + fireEvent.click(await screen.findByTestId('search-sort-button-reset')); + expect(await screen.findByDisplayValue('Timestamp')).toBeInTheDocument(); + expect(screen.getByTestId('search-sort-button-reset')).toBeDisabled(); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith(''); }); it('does not apply on cancel', async () => { From 006d39365aa0c8ad4416619063c8b0249c6c1b1a Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 13:41:39 +0100 Subject: [PATCH 04/14] fix(app): wrap long column names in the columns popover Co-authored-by: Cursor --- .../SearchResultsToolbar/ColumnsPopover.tsx | 40 ++++++++++--------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 1f5c51aa72..0ead732870 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -22,7 +22,6 @@ import { Box, Button, Group, - ScrollArea, Stack, Text, } from '@mantine/core'; @@ -62,27 +61,30 @@ function SortableColumn({ opacity: isDragging ? 0.5 : 1, }} > - - - - - - - {label} - - + + + + + + {label} + @@ -194,7 +196,7 @@ export function ColumnsPopover({ data-testid="search-columns-button" renderPick={() => ( - + {items.length === 0 ? ( No columns selected. @@ -218,7 +220,7 @@ export function ColumnsPopover({ )} - + Date: Fri, 16 Oct 2026 14:41:06 +0100 Subject: [PATCH 05/14] fix(app): keep column and sort picks valid SQL Suggested names with spaces or hyphens were inserted raw, an emptied column list snapped back to the source default, and a sort of two tuples was parsed as one broken list. Co-authored-by: Cursor --- .../SearchResultsToolbar/ColumnsPopover.tsx | 12 ++-- .../SearchResultsToolbar/SortPopover.tsx | 19 ++++-- .../__tests__/ColumnsPopover.test.tsx | 21 +++++++ .../__tests__/SortPopover.test.tsx | 17 ++++++ .../__tests__/useClauseFieldOptions.test.tsx | 61 +++++++++++++++++++ .../useClauseFieldOptions.ts | 29 ++++++--- 6 files changed, 139 insertions(+), 20 deletions(-) create mode 100644 packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 0ead732870..e9319eedfa 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -118,11 +118,13 @@ export function ColumnsPopover({ const [draft, setDraft] = useState(value); const [search, setSearch] = useState(''); - const effective = (select: string) => + // An empty stored SELECT means "use the source default". An empty draft does + // not: the user may have removed every column before adding a replacement. + const storedColumns = (select: string) => splitAndTrimWithBracket(select || defaultValue); - const count = effective(value).length; - const items = effective(draft); + const count = storedColumns(value).length; + const items = splitAndTrimWithBracket(draft); const options = useMemo( () => fieldOptions.filter(option => !items.includes(option)), @@ -187,10 +189,10 @@ export function ColumnsPopover({ : draft === baseline ? value : draft; - const next = effective(submitted); + const next = storedColumns(submitted); onApply( submitted, - effective(value).filter(item => !next.includes(item)), + storedColumns(value).filter(item => !next.includes(item)), ); }} data-testid="search-columns-button" diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index a044b730cb..d668687bc7 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -1,6 +1,7 @@ import { useRef, useState } from 'react'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { findBalancedParens } from '@hyperdx/common-utils/dist/variables'; import { ActionIcon, Autocomplete, @@ -32,18 +33,24 @@ const toRows = (keys: SortKey[] | null): SortRow[] | null => /** * Sort keys the picker can edit. A parenthesized list with one direction, * `(toDateTime(Timestamp), Timestamp) DESC`, is several fields sharing that - * direction, including function calls. Anything without a plain ASC/DESC on - * each field stays in SQL. + * direction, including function calls. The parentheses have to wrap that whole + * expression: `(a, b) ASC, (c, d) DESC` is two keys, not one list. Anything + * without a plain ASC/DESC on each field stays in SQL. */ function parseSortKeys(orderBy: string): SortKey[] | null { const trimmed = orderBy.trim(); if (!trimmed) return []; - const tuple = trimmed.match(/^\(([\s\S]+)\)\s+(asc|desc)$/i); - if (tuple) { - const ids = splitAndTrimWithBracket(tuple[1]); + const direction = trimmed.match(/^(.*)\s+(asc|desc)$/i); + const expr = direction?.[1].trim() ?? ''; + if ( + direction && + expr.startsWith('(') && + findBalancedParens(expr, 0) === expr.length - 1 + ) { + const ids = splitAndTrimWithBracket(expr.slice(1, -1)); if (ids.length > 1 && ids.every(id => id.length > 0)) { - const desc = tuple[2].toUpperCase() === 'DESC'; + const desc = direction[2].toUpperCase() === 'DESC'; return ids.map(id => ({ id, desc })); } } diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index 707246b1df..e72bbac3ff 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -63,6 +63,27 @@ describe('ColumnsPopover', () => { expect(screen.getByLabelText('Reorder Body')).toBeInTheDocument(); }); + it('stays empty after the last column is removed', async () => { + renderPopover({ + value: 'Timestamp', + defaultValue: 'Timestamp, ServiceName, Body', + }); + openPopover(); + fireEvent.click(await screen.findByLabelText('Remove Timestamp')); + expect(screen.getByText('No columns selected.')).toBeInTheDocument(); + expect( + screen.queryByLabelText('Remove ServiceName'), + ).not.toBeInTheDocument(); + + const input = screen.getByPlaceholderText('Search columns'); + fireEvent.change(input, { target: { value: 'Body' } }); + fireEvent.click(screen.getByTestId('search-columns-add-button')); + expect(screen.getByLabelText('Remove Body')).toBeInTheDocument(); + expect( + screen.queryByLabelText('Remove ServiceName'), + ).not.toBeInTheDocument(); + }); + it('removes a column and reports it on apply', async () => { const { onApply } = renderPopover(); openPopover(); diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index 49be9700da..feec3cab50 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -131,6 +131,23 @@ describe('SortPopover', () => { ); }); + it('keeps separate tuple keys instead of merging them', async () => { + const orderBy = '(a, b) ASC, (c, d) DESC'; + const { onApply } = renderPopover({ + value: orderBy, + defaultValue: orderBy, + }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + 'Sort: 2 fields', + ); + openPopover(); + expect(await screen.findByDisplayValue('(a, b)')).toBeInTheDocument(); + expect(screen.getByDisplayValue('(c, d)')).toBeInTheDocument(); + fireEvent.click(screen.getAllByText('Desc')[0]); + fireEvent.click(screen.getByTestId('search-sort-button-apply')); + expect(onApply).toHaveBeenCalledWith('(a, b) DESC, (c, d) DESC'); + }); + it('lists every key of a multi-field sort', async () => { renderPopover({ value: 'ServiceName ASC, Timestamp DESC' }); expect(screen.getByTestId('search-sort-button')).toHaveTextContent( diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx new file mode 100644 index 0000000000..f13af74133 --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx @@ -0,0 +1,61 @@ +import { ColumnMeta, JSDataType } from '@hyperdx/common-utils/dist/clickhouse'; +import { renderHook } from '@testing-library/react'; + +import { useClauseFieldOptions } from '@/components/SearchResultsToolbar/useClauseFieldOptions'; +import { useAllFields } from '@/hooks/useMetadata'; + +jest.mock('@/hooks/useMetadata', () => ({ + useAllFields: jest.fn(), +})); + +const column = (name: string, type: string): ColumnMeta => ({ + name, + type, + codec_expression: '', + comment: '', + default_expression: '', + default_type: '', + ttl_expression: '', +}); + +const columns = [ + column('ServiceName', 'LowCardinality(String)'), + column('service-name', 'String'), + column('my-map', 'Map(String, String)'), +]; + +describe('useClauseFieldOptions', () => { + it('quotes column names that are not bare identifiers', () => { + jest.mocked(useAllFields).mockReturnValue({ + data: [ + { path: ['ServiceName'], type: 'String', jsType: JSDataType.String }, + { path: ['service-name'], type: 'String', jsType: JSDataType.String }, + { path: ['my-map', 'k'], type: 'String', jsType: null }, + ], + isFieldMetadataDisabled: false, + } as unknown as ReturnType); + + const { result } = renderHook(() => + useClauseFieldOptions({ tableConnection: undefined, columns }), + ); + + expect(result.current).toEqual([ + 'ServiceName', + "`my-map`['k']", + '`service-name`', + ]); + }); + + it('offers scalar columns when field metadata is disabled', () => { + jest.mocked(useAllFields).mockReturnValue({ + data: [], + isFieldMetadataDisabled: true, + } as unknown as ReturnType); + + const { result } = renderHook(() => + useClauseFieldOptions({ tableConnection: undefined, columns }), + ); + + expect(result.current).toEqual(['ServiceName', '`service-name`']); + }); +}); diff --git a/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts b/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts index a7c15d4f44..292844ba7f 100644 --- a/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts +++ b/packages/app/src/components/SearchResultsToolbar/useClauseFieldOptions.ts @@ -6,6 +6,7 @@ import { getSqlSourceColumnKeys, getSqlSourceKeys, } from '@/components/AdhocDashboardFilter/useAdhocFilterOptions'; +import { toQuotedClickHouseKeyExpression } from '@/components/DBSearchPageFilters/utils'; import { useAllFields } from '@/hooks/useMetadata'; /** The source's fields as SQL expressions, for the Pick tabs. */ @@ -20,17 +21,27 @@ export function useClauseFieldOptions({ dateRange?: [Date, Date]; timestampValueExpression?: string; }): string[] { - const { data: fields } = useAllFields(tableConnection, { - dateRange, - timestampValueExpression, - }); + const { data: fields, isFieldMetadataDisabled } = useAllFields( + tableConnection, + { + dateRange, + timestampValueExpression, + }, + ); return useMemo(() => { if (columns == null) return []; + const knownColumns = new Set(columns.map(column => column.name)); + // Field discovery is off for some teams, and `useAllFields` then returns + // [] rather than "still loading". Scalar columns are still known. const keys = - fields != null - ? getSqlSourceKeys(fields, columns) - : getSqlSourceColumnKeys(columns); - return Array.from(new Set(keys)).sort(); - }, [fields, columns]); + isFieldMetadataDisabled || fields == null + ? getSqlSourceColumnKeys(columns) + : getSqlSourceKeys(fields, columns); + return Array.from( + new Set( + keys.map(key => toQuotedClickHouseKeyExpression(key, knownColumns)), + ), + ).sort(); + }, [fields, columns, isFieldMetadataDisabled]); } From e62fcf7a80682bb2ef4402886ce05c8439d1799d Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 14:44:06 +0100 Subject: [PATCH 06/14] fix(app): keep the where clause beside the time controls The where field and the time group each claimed hundreds of pixels, so Live Tail and Run wrapped while the form was still wide. They now share a row until the form itself is under 900px, the compact layout cutoff. Co-authored-by: Cursor --- packages/app/src/DBSearchPage.tsx | 11 +++------ packages/app/styles/SearchPage.module.scss | 27 ++++++++++++++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 98cfede1de..695779f662 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2462,8 +2462,8 @@ function DBSearchPageContent() { )} - - + + - + {isLive && ( diff --git a/packages/app/styles/SearchPage.module.scss b/packages/app/styles/SearchPage.module.scss index c617de5d10..5d3502ab97 100644 --- a/packages/app/styles/SearchPage.module.scss +++ b/packages/app/styles/SearchPage.module.scss @@ -167,4 +167,31 @@ z-index: 4; padding-bottom: var(--mantine-spacing-xs); border-bottom: 1px solid var(--color-border); + + // The where row uses this width. 900px is the compact search cutoff. + container-type: inline-size; +} + +.whereRow { + flex-wrap: wrap; +} + +.whereField { + flex: 1 1 0%; + max-width: 100%; + min-width: 0; +} + +// Stack the where clause once the form itself is under 900px. Wider than +// that, it stays beside the time controls. Matches the compact layout cutoff. +@container (min-width: 900px) { + .whereRow { + flex-wrap: nowrap; + } +} + +@container (max-width: 899px) { + .whereField { + flex-basis: 100%; + } } From 0181a09ff31aa45057156e735fe8756c133665e9 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 14:51:52 +0100 Subject: [PATCH 07/14] fix(app): keep multiline tuple sorts editable in Pick A newline inside a parenthesized sort hid the field controls, because the direction match stopped at the end of the line. Co-authored-by: Cursor --- .../SearchResultsToolbar/SortPopover.tsx | 4 +++- .../__tests__/SortPopover.test.tsx | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index d668687bc7..51cfb9e25b 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -41,7 +41,9 @@ function parseSortKeys(orderBy: string): SortKey[] | null { const trimmed = orderBy.trim(); if (!trimmed) return []; - const direction = trimmed.match(/^(.*)\s+(asc|desc)$/i); + // [\s\S] so a newline inside `(toDateTime(Timestamp),\n Timestamp) DESC` + // still counts as one direction. `.` would miss it and hide the Pick controls. + const direction = trimmed.match(/^([\s\S]*)\s+(asc|desc)$/i); const expr = direction?.[1].trim() ?? ''; if ( direction && diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index feec3cab50..b7387d3961 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -61,6 +61,20 @@ describe('SortPopover', () => { expect(onApply).toHaveBeenCalledWith('Timestamp ASC'); }); + it('lists a tuple sort that spans more than one line', async () => { + const orderBy = '(toDateTime(Timestamp),\n Timestamp) DESC'; + renderPopover({ value: orderBy, defaultValue: orderBy }); + expect(screen.getByTestId('search-sort-button')).toHaveTextContent( + 'Sort: 2 fields', + ); + openPopover(); + expect( + await screen.findByDisplayValue('toDateTime(Timestamp)'), + ).toBeInTheDocument(); + expect(screen.getByDisplayValue('Timestamp')).toBeInTheDocument(); + expect(screen.queryByTestId('search-sort-custom')).not.toBeInTheDocument(); + }); + it('lists function calls inside a tuple sort', async () => { const orderBy = '(toDateTime(Timestamp), Timestamp) DESC'; renderPopover({ value: orderBy, defaultValue: orderBy }); From 5d72317bb09342fa60bf9312b4a69b308449548f Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 15:12:13 +0100 Subject: [PATCH 08/14] fix(app): stay inside the app lint warning budget The field-options test asserted a partial hook result, which added two warnings and pushed the package over its limit of 568. Co-authored-by: Cursor --- .../__tests__/useClauseFieldOptions.test.tsx | 35 ++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx index f13af74133..c044494281 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/useClauseFieldOptions.test.tsx @@ -1,4 +1,5 @@ import { ColumnMeta, JSDataType } from '@hyperdx/common-utils/dist/clickhouse'; +import { Field } from '@hyperdx/common-utils/dist/core/metadata'; import { renderHook } from '@testing-library/react'; import { useClauseFieldOptions } from '@/components/SearchResultsToolbar/useClauseFieldOptions'; @@ -24,16 +25,37 @@ const columns = [ column('my-map', 'Map(String, String)'), ]; +function mockAllFields( + data: Field[] | undefined, + isFieldMetadataDisabled: boolean, +) { + const result: ReturnType = { + data, + error: null, + isError: false, + isPending: false, + isSuccess: true, + isLoading: false, + isFetching: false, + isFieldMetadataDisabled, + fieldsByTableConnection: new Map(), + columnsByTableConnection: new Map(), + errorsByTableConnection: new Map(), + refetch: () => Promise.reject(new Error('unused')), + }; + jest.mocked(useAllFields).mockReturnValue(result); +} + describe('useClauseFieldOptions', () => { it('quotes column names that are not bare identifiers', () => { - jest.mocked(useAllFields).mockReturnValue({ - data: [ + mockAllFields( + [ { path: ['ServiceName'], type: 'String', jsType: JSDataType.String }, { path: ['service-name'], type: 'String', jsType: JSDataType.String }, { path: ['my-map', 'k'], type: 'String', jsType: null }, ], - isFieldMetadataDisabled: false, - } as unknown as ReturnType); + false, + ); const { result } = renderHook(() => useClauseFieldOptions({ tableConnection: undefined, columns }), @@ -47,10 +69,7 @@ describe('useClauseFieldOptions', () => { }); it('offers scalar columns when field metadata is disabled', () => { - jest.mocked(useAllFields).mockReturnValue({ - data: [], - isFieldMetadataDisabled: true, - } as unknown as ReturnType); + mockAllFields([], true); const { result } = renderHook(() => useClauseFieldOptions({ tableConnection: undefined, columns }), From 1d9730cc440177d9a68f7ec5b9de2713e0c30cb5 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 16 Oct 2026 16:43:12 +0100 Subject: [PATCH 09/14] fix(app): show a map key alias before adding the column Picking a map key stored it with an alias, but the input still showed the raw expression. The alias now appears in the input so it can be edited before Add. Co-authored-by: Cursor --- .../SearchResultsToolbar/ColumnsPopover.tsx | 11 ++++++++- .../__tests__/ColumnsPopover.test.tsx | 24 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index e9319eedfa..2eb4c0cc18 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -228,7 +228,16 @@ export function ColumnsPopover({ size="xs" placeholder="Search columns" value={search} - onChange={setSearch} + onChange={next => { + // A picked map key is stored with its alias. Show that alias + // in the input so it can be edited before Add. + const aliased = withMapKeyAlias( + next.trim(), + items, + knownColumns, + ); + setSearch(aliased === next.trim() ? next : aliased); + }} data={options} limit={50} comboboxProps={{ withinPortal: false }} diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index e72bbac3ff..41766bfbe4 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -92,6 +92,30 @@ describe('ColumnsPopover', () => { expect(onApply).toHaveBeenCalledWith('Timestamp', ['Body']); }); + it('shows a map key alias in the input before adding it', async () => { + renderPopover({ + fieldOptions: ["LogAttributes['ads.consent_given']"], + }); + openPopover(); + const input = await screen.findByPlaceholderText('Search columns'); + fireEvent.change(input, { + target: { value: "LogAttributes['ads" }, + }); + fireEvent.click( + await screen.findByText("LogAttributes['ads.consent_given']"), + ); + expect(input).toHaveValue( + `LogAttributes['ads.consent_given'] AS "ads.consent_given"`, + ); + fireEvent.click(screen.getByTestId('search-columns-add-button')); + expect(input).toHaveValue(''); + expect( + screen.getByText( + `LogAttributes['ads.consent_given'] AS "ads.consent_given"`, + ), + ).toBeInTheDocument(); + }); + it('fills the input from a suggestion and adds only on Add', async () => { const { onApply } = renderPopover(); openPopover(); From 4c1260fd95a72b76e0c5b222339746b6d2e344d5 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 12:01:08 +0100 Subject: [PATCH 10/14] fix: adjust styling and sizes in ColumnsPopover for better usability - Changed alignment of Group component to center for improved layout. - Updated ActionIcon sizes from 'sm' to 'xs' and increased icon sizes for better visibility. - Added line height to Text component for enhanced readability. --- .../SearchResultsToolbar/ColumnsPopover.tsx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 2eb4c0cc18..425c1ea7d4 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -61,32 +61,33 @@ function SortableColumn({ opacity: isDragging ? 0.5 : 1, }} > - + - + {label} - + From 0e8a7ae427cc62a6d19f0ae9b87620610467fbc1 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 12:21:45 +0100 Subject: [PATCH 11/14] fix(app): keep column and sort edits from breaking the search Removing an aliased column left it in a multi-field sort, a comma inside a backtick-quoted name was split, and typing a map key rewrote the input. The time controls also wrap so Run stays visible on a narrow screen. Co-authored-by: Cursor --- packages/app/src/DBSearchPage.tsx | 38 +++++++++++-------- packages/app/src/__tests__/utils.test.ts | 17 +++++++++ .../SearchResultsToolbar/ColumnsPopover.tsx | 22 ++++++----- .../SearchResultsToolbar/SortPopover.tsx | 20 ++++++++++ .../__tests__/ColumnsPopover.test.tsx | 12 ++++++ .../__tests__/SortPopover.test.tsx | 8 ++++ packages/app/src/utils.ts | 16 ++++++-- packages/app/styles/SearchPage.module.scss | 15 ++++++++ 8 files changed, 120 insertions(+), 28 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 4c9d9f415d..a5cc06388f 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2517,21 +2517,29 @@ function DBSearchPageContent() { size="xs" /> - - + + + + {isLive && ( diff --git a/packages/app/src/__tests__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts index 864d5ba1b2..fa5cab439d 100644 --- a/packages/app/src/__tests__/utils.test.ts +++ b/packages/app/src/__tests__/utils.test.ts @@ -1534,6 +1534,23 @@ describe('orderByAfterRemovingSelectItem', () => { orderByAfterRemovingSelectItem('Body', 'Body DESC', 'Timestamp DESC'), ).toBe('Body DESC'); }); + + it('drops only the removed alias from a multi-field sort', () => { + expect( + orderByAfterRemovingSelectItem( + item, + '"service.name" ASC, Timestamp DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + expect( + orderByAfterRemovingSelectItem( + item, + '"http.method" DESC, "service.name" ASC', + 'Timestamp DESC', + ), + ).toBe('"http.method" DESC'); + }); }); describe('getLogSeverityLevel', () => { diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 425c1ea7d4..76f653d1eb 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -1,4 +1,4 @@ -import { useMemo, useState } from 'react'; +import { useMemo, useRef, useState } from 'react'; import { DndContext, type DragEndEvent, @@ -118,6 +118,9 @@ export function ColumnsPopover({ }) { const [draft, setDraft] = useState(value); const [search, setSearch] = useState(''); + // Autocomplete writes the chosen option back into the input after + // onOptionSubmit. Ignore that write so a picked map key keeps its alias. + const ignoreNextChangeRef = useRef(false); // An empty stored SELECT means "use the source default". An empty draft does // not: the user may have removed every column before adding a replacement. @@ -230,14 +233,15 @@ export function ColumnsPopover({ placeholder="Search columns" value={search} onChange={next => { - // A picked map key is stored with its alias. Show that alias - // in the input so it can be edited before Add. - const aliased = withMapKeyAlias( - next.trim(), - items, - knownColumns, - ); - setSearch(aliased === next.trim() ? next : aliased); + if (ignoreNextChangeRef.current) { + ignoreNextChangeRef.current = false; + return; + } + setSearch(next); + }} + onOptionSubmit={option => { + ignoreNextChangeRef.current = true; + setSearch(withMapKeyAlias(option, items, knownColumns)); }} data={options} limit={50} diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index 51cfb9e25b..89f0a98692 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -37,9 +37,29 @@ const toRows = (keys: SortKey[] | null): SortRow[] | null => * expression: `(a, b) ASC, (c, d) DESC` is two keys, not one list. Anything * without a plain ASC/DESC on each field stays in SQL. */ +/** A comma inside backticks cannot be split without breaking the identifier. */ +function hasCommaInsideBackticks(input: string): boolean { + let quoted = false; + for (let i = 0; i < input.length; i++) { + if (input[i] !== '`') { + if (quoted && input[i] === ',') return true; + continue; + } + // ClickHouse escapes a backtick by doubling it. + if (quoted && input[i + 1] === '`') { + i += 1; + continue; + } + quoted = !quoted; + } + return false; +} + function parseSortKeys(orderBy: string): SortKey[] | null { const trimmed = orderBy.trim(); if (!trimmed) return []; + // A comma inside a backtick-quoted name would be split into extra fields. + if (hasCommaInsideBackticks(trimmed)) return null; // [\s\S] so a newline inside `(toDateTime(Timestamp),\n Timestamp) DESC` // still counts as one direction. `.` would miss it and hide the Pick controls. diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index 41766bfbe4..bf09f892ea 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -92,6 +92,18 @@ describe('ColumnsPopover', () => { expect(onApply).toHaveBeenCalledWith('Timestamp', ['Body']); }); + it('leaves a typed map subscript unchanged', async () => { + renderPopover({ + fieldOptions: ["LogAttributes['region']"], + }); + openPopover(); + const input = await screen.findByPlaceholderText('Search columns'); + fireEvent.change(input, { + target: { value: "LogAttributes['region']" }, + }); + expect(input).toHaveValue("LogAttributes['region']"); + }); + it('shows a map key alias in the input before adding it', async () => { renderPopover({ fieldOptions: ["LogAttributes['ads.consent_given']"], diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index b7387d3961..eef15af01d 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -89,6 +89,14 @@ describe('SortPopover', () => { expect(screen.queryByTestId('search-sort-custom')).not.toBeInTheDocument(); }); + it('keeps a backtick-quoted field that contains a comma on SQL', async () => { + const orderBy = '(`a,b`, Timestamp) DESC'; + renderPopover({ value: orderBy, defaultValue: orderBy }); + openPopover(); + expect(await screen.findByLabelText('ORDER BY')).toHaveValue(orderBy); + expect(screen.queryByDisplayValue('Timestamp')).not.toBeInTheDocument(); + }); + it('opens on the SQL tab for a custom ORDER BY', async () => { const custom = 'Timestamp DESC NULLS LAST'; const { onApply } = renderPopover({ value: custom, defaultValue: custom }); diff --git a/packages/app/src/utils.ts b/packages/app/src/utils.ts index b8e0e91ea3..89d1cc74d7 100644 --- a/packages/app/src/utils.ts +++ b/packages/app/src/utils.ts @@ -8,6 +8,7 @@ import { TableConnection, unquoteIdentifier, } from '@hyperdx/common-utils/dist/core/metadata'; +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; import { CATEGORICAL_PALETTE_TOKENS, ChartPaletteToken, @@ -1292,8 +1293,8 @@ export const withMapKeyAlias = ( /** * The sort to keep once a SELECT item is removed. Sorting on an aliased column * from the table header orders by the alias itself (`"service.name" DESC`), - * which stops resolving once the item is gone, so that falls back to the - * default sort. + * which stops resolving once the item is gone. Each top-level key that sorts + * by that alias is dropped. The default sort is used only when none remain. */ export const orderByAfterRemovingSelectItem = ( item: string, @@ -1304,8 +1305,15 @@ export const orderByAfterRemovingSelectItem = ( if (alias == null) { return orderBy; } - const sortedBy = orderBy.trim().replace(/\s+(ASC|DESC)$/i, ''); - return sortedBy === `"${alias}"` ? defaultOrderBy : orderBy; + const quoted = `"${alias}"`; + const keys = splitAndTrimWithBracket(orderBy); + const kept = keys.filter( + key => key.replace(/\s+(ASC|DESC)$/i, '') !== quoted, + ); + if (kept.length === keys.length) { + return orderBy; + } + return kept.length === 0 ? defaultOrderBy : kept.join(', '); }; const _useTry = (fn: () => T): [null | Error | unknown, null | T] => { diff --git a/packages/app/styles/SearchPage.module.scss b/packages/app/styles/SearchPage.module.scss index 3be13b9af1..e291a44a94 100644 --- a/packages/app/styles/SearchPage.module.scss +++ b/packages/app/styles/SearchPage.module.scss @@ -186,6 +186,17 @@ min-width: 0; } +.timeControls { + flex: 0 0 auto; + max-width: 100%; +} + +.timePicker { + width: 350px; + max-width: 100%; + min-width: 0; +} + // Stack the where clause once the form itself is under 900px. Wider than // that, it stays beside the time controls. Matches the compact layout cutoff. @container (min-width: 900px) { @@ -198,4 +209,8 @@ .whereField { flex-basis: 100%; } + + .timeControls { + flex-basis: 100%; + } } From a68ea7c110aef9ca4969a9246b8f999c4a4b4d1b Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 13:03:39 +0100 Subject: [PATCH 12/14] feat(app): share one button for group by, columns, and sort A field count collapses to a number on a narrow screen so the three controls still fit. Storybook records when to use each clause. Co-authored-by: Cursor --- packages/app/src/components/DBRowTable.tsx | 4 +- .../SearchGroupBy/SearchGroupBySelect.tsx | 50 +++----- .../SearchResultsToolbar/ClausePopover.tsx | 39 ++++--- .../SearchResultsToolbar/ColumnsPopover.tsx | 29 +++-- .../SearchResultsToolbar/SortPopover.tsx | 28 +++-- .../__tests__/ColumnsPopover.test.tsx | 8 +- .../__tests__/SortPopover.test.tsx | 30 ++--- .../SplitValueButton.module.scss} | 0 .../SplitValueButton.stories.tsx | 108 ++++++++++++++++++ .../SplitValueButton/SplitValueButton.tsx | 91 +++++++++++++++ .../__tests__/SplitValueButton.test.tsx | 53 +++++++++ 11 files changed, 352 insertions(+), 88 deletions(-) rename packages/app/src/components/{SearchGroupBy/SearchGroupBySelect.module.scss => SplitValueButton/SplitValueButton.module.scss} (100%) create mode 100644 packages/app/src/components/SplitValueButton/SplitValueButton.stories.tsx create mode 100644 packages/app/src/components/SplitValueButton/SplitValueButton.tsx create mode 100644 packages/app/src/components/SplitValueButton/__tests__/SplitValueButton.test.tsx diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 32e424873f..0fb7b7d0ca 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -42,7 +42,6 @@ import { import { ActionIcon, Box, - Divider, Flex, Group, Modal, @@ -1133,8 +1132,7 @@ export const RawLogTable = memo( {controlsAboveTable && rowSelectionMenu} {controlsAboveTable && ( - - + {tableControls} )} diff --git a/packages/app/src/components/SearchGroupBy/SearchGroupBySelect.tsx b/packages/app/src/components/SearchGroupBy/SearchGroupBySelect.tsx index 6794ad77fb..d90cf8d5d6 100644 --- a/packages/app/src/components/SearchGroupBy/SearchGroupBySelect.tsx +++ b/packages/app/src/components/SearchGroupBy/SearchGroupBySelect.tsx @@ -6,12 +6,13 @@ import { Group, Popover, SegmentedControl, - Text, TextInput, - UnstyledButton, } from '@mantine/core'; -import { IconChevronDown } from '@tabler/icons-react'; +import { + fieldListSummary, + SplitValueButton, +} from '@/components/SplitValueButton/SplitValueButton'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; import { GroupByFieldList } from './GroupByFieldList'; @@ -23,16 +24,8 @@ import { } from './searchGroupBy'; import { useGroupByKeyOptions } from './useGroupByKeyOptions'; -import classes from './SearchGroupBySelect.module.scss'; - type Mode = 'fields' | 'sql'; -function triggerLabel(fields: string[]) { - if (fields.length === 0) return 'none'; - if (fields.length === 1) return fields[0]; - return `${fields.length} fields`; -} - export function SearchGroupBySelect({ source, value, @@ -112,8 +105,6 @@ export function SearchGroupBySelect({ prev.includes(field) ? prev.filter(f => f !== field) : [...prev, field], ); - const label = triggerLabel(appliedFields); - return ( -
- - Group by - - - handleOpenChange(!opened)} - data-testid="search-group-by-button" - aria-label={`Group by ${label}`} - > - - {label} - - - - -
+ + handleOpenChange(!opened)} + data-testid="search-group-by-button" + /> + - + /> diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 76f653d1eb..f3dcaf9a84 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -21,12 +21,14 @@ import { Autocomplete, Box, Button, + Code, Group, Stack, Text, } from '@mantine/core'; -import { IconColumns, IconGripVertical, IconX } from '@tabler/icons-react'; +import { IconGripVertical, IconX } from '@tabler/icons-react'; +import { fieldListSummary } from '@/components/SplitValueButton/SplitValueButton'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; import { withMapKeyAlias } from '@/utils'; @@ -61,7 +63,18 @@ function SortableColumn({ opacity: isDragging ? 0.5 : 1, }} > - + splitAndTrimWithBracket(select || defaultValue); - const count = storedColumns(value).length; + const shown = storedColumns(value); const items = splitAndTrimWithBracket(draft); const options = useMemo( @@ -168,9 +181,11 @@ export function ColumnsPopover({ return ( 0 ? `Columns (${count})` : 'Columns'} + name="Columns" + summary={fieldListSummary(shown)} + count={shown.length} + dimmed={value.trim() === ''} title={value || defaultValue} - icon={} initialMode="pick" onOpen={() => { // The form stores "" while the source default is in use. Show that @@ -260,8 +275,8 @@ export function ColumnsPopover({ - Select a column, or type an expression such as upper(Body) as - message, then click Add. + Select a column, or type an expression such as{' '} + upper(Body) as message, then click Add. )} diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index 89f0a98692..6524d6d16f 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -11,7 +11,7 @@ import { Stack, Text, } from '@mantine/core'; -import { IconArrowsSort, IconX } from '@tabler/icons-react'; +import { IconX } from '@tabler/icons-react'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; import { parseAsSortingStateString } from '@/utils/queryParsers'; @@ -62,7 +62,7 @@ function parseSortKeys(orderBy: string): SortKey[] | null { if (hasCommaInsideBackticks(trimmed)) return null; // [\s\S] so a newline inside `(toDateTime(Timestamp),\n Timestamp) DESC` - // still counts as one direction. `.` would miss it and hide the Pick controls. + // still counts as one direction. `.` would miss it and hide the Fields controls. const direction = trimmed.match(/^([\s\S]*)\s+(asc|desc)$/i); const expr = direction?.[1].trim() ?? ''; if ( @@ -105,13 +105,22 @@ function sameKeys(a: SortKey[], b: SortKey[]) { ); } -function sortLabel(orderBy: string) { +function sortSummary(orderBy: string): { summary: string; count: number } { const keys = parseSortKeys(orderBy); - if (keys == null || keys.length === 0) return 'Sort'; + if (keys == null) { + const summary = orderBy.trim() || 'none'; + // An expression the field list cannot split stays one value. A number + // would invent a field count the user cannot see in the list. + return { summary, count: summary === 'none' ? 0 : 1 }; + } + if (keys.length === 0) return { summary: 'none', count: 0 }; if (keys.length === 1) { - return `Sort: ${keys[0].id} ${keys[0].desc ? 'desc' : 'asc'}`; + return { + summary: `${keys[0].id} ${keys[0].desc ? 'desc' : 'asc'}`, + count: 1, + }; } - return `Sort: ${keys.length} fields`; + return { summary: `${keys.length} fields`, count: keys.length }; } export function SortPopover({ @@ -144,6 +153,7 @@ export function SortPopover({ const ignoreNextChangeRef = useRef(false); const baseline = value || defaultValue; + const shownSort = sortSummary(baseline); const used = new Set((keys ?? []).map(key => key.id)); const addOptions = fieldOptions.filter(option => !used.has(option)); @@ -178,9 +188,11 @@ export function SortPopover({ return ( } initialMode={parseSortKeys(baseline) != null ? 'pick' : 'sql'} onOpen={reset} onReset={() => { diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index bf09f892ea..8fb7fcb15c 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -49,8 +49,8 @@ const openPopover = () => describe('ColumnsPopover', () => { it('shows the column count and falls back to the default SELECT', () => { renderPopover({ value: '' }); - expect(screen.getByTestId('search-columns-button')).toHaveTextContent( - 'Columns (3)', + expect(screen.getByTestId('search-columns-button')).toHaveAccessibleName( + 'Columns 3 fields', ); }); @@ -154,7 +154,9 @@ describe('ColumnsPopover', () => { }); fireEvent.click(screen.getByTestId('search-columns-add-button')); expect(input).toHaveValue(''); - expect(screen.getByText('upper(Body) as message')).toBeInTheDocument(); + expect( + screen.getByLabelText('Remove upper(Body) as message'), + ).toBeInTheDocument(); fireEvent.click(screen.getByTestId('search-columns-button-apply')); expect(onApply).toHaveBeenCalledWith( 'Timestamp, Body, upper(Body) as message', diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index eef15af01d..369c35b7ae 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -48,8 +48,8 @@ const openPopover = () => describe('SortPopover', () => { it('labels the button with the parsed field and direction', () => { renderPopover({ value: 'Body ASC' }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: Body asc', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort Body asc', ); }); @@ -64,8 +64,8 @@ describe('SortPopover', () => { it('lists a tuple sort that spans more than one line', async () => { const orderBy = '(toDateTime(Timestamp),\n Timestamp) DESC'; renderPopover({ value: orderBy, defaultValue: orderBy }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: 2 fields', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort 2 fields', ); openPopover(); expect( @@ -78,8 +78,8 @@ describe('SortPopover', () => { it('lists function calls inside a tuple sort', async () => { const orderBy = '(toDateTime(Timestamp), Timestamp) DESC'; renderPopover({ value: orderBy, defaultValue: orderBy }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: 2 fields', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort 2 fields', ); openPopover(); expect( @@ -100,13 +100,13 @@ describe('SortPopover', () => { it('opens on the SQL tab for a custom ORDER BY', async () => { const custom = 'Timestamp DESC NULLS LAST'; const { onApply } = renderPopover({ value: custom, defaultValue: custom }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - /^Sort$/, + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + `Sort ${custom}`, ); openPopover(); const editor = await screen.findByLabelText('ORDER BY'); expect(editor).toHaveValue(custom); - fireEvent.click(screen.getByText('Pick')); + fireEvent.click(screen.getByText('Fields')); expect(screen.getByTestId('search-sort-custom')).toBeInTheDocument(); fireEvent.click(screen.getByText('SQL')); fireEvent.change(screen.getByLabelText('ORDER BY'), { @@ -132,8 +132,8 @@ describe('SortPopover', () => { defaultValue: '(TimestampTime, Timestamp) DESC', fieldOptions: ['Body', 'Timestamp', 'TimestampTime'], }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: 2 fields', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort 2 fields', ); openPopover(); expect( @@ -159,8 +159,8 @@ describe('SortPopover', () => { value: orderBy, defaultValue: orderBy, }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: 2 fields', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort 2 fields', ); openPopover(); expect(await screen.findByDisplayValue('(a, b)')).toBeInTheDocument(); @@ -172,8 +172,8 @@ describe('SortPopover', () => { it('lists every key of a multi-field sort', async () => { renderPopover({ value: 'ServiceName ASC, Timestamp DESC' }); - expect(screen.getByTestId('search-sort-button')).toHaveTextContent( - 'Sort: 2 fields', + expect(screen.getByTestId('search-sort-button')).toHaveAccessibleName( + 'Sort 2 fields', ); openPopover(); expect(await screen.findByDisplayValue('ServiceName')).toBeInTheDocument(); diff --git a/packages/app/src/components/SearchGroupBy/SearchGroupBySelect.module.scss b/packages/app/src/components/SplitValueButton/SplitValueButton.module.scss similarity index 100% rename from packages/app/src/components/SearchGroupBy/SearchGroupBySelect.module.scss rename to packages/app/src/components/SplitValueButton/SplitValueButton.module.scss diff --git a/packages/app/src/components/SplitValueButton/SplitValueButton.stories.tsx b/packages/app/src/components/SplitValueButton/SplitValueButton.stories.tsx new file mode 100644 index 0000000000..1ea0ab32fb --- /dev/null +++ b/packages/app/src/components/SplitValueButton/SplitValueButton.stories.tsx @@ -0,0 +1,108 @@ +import { Group, Stack, Text } from '@mantine/core'; +import type { Meta, StoryObj } from '@storybook/nextjs'; + +import { SplitValueButton } from './SplitValueButton'; + +const meta: Meta = { + title: 'Components/SplitValueButton', + component: SplitValueButton, + parameters: { + layout: 'padded', + docs: { + description: { + component: + 'The shared trigger for Group by, Columns, and Sort. Use it when a search control shows the current value of a clause and opens an editor. Do not use it for an action such as Save, Run, or Apply.', + }, + }, + }, +}; + +export default meta; +type Story = StoryObj; + +const noop = () => {}; + +export const WhenToUse: Story = { + render: () => ( + + + Use this button for a search clause whose value is one field, or a count + of fields. The name stays fixed. The value is what you press. + + + + Group by splits the histogram. One series for each value of the field. + + + + + + Columns chooses which columns the results table shows, and their + order. + + + + + + Sort sets the order of the result rows. One field includes its + direction. + + + + + + On a narrow screen a count is only the number. One field keeps its + name, and an empty clause stays none. + + + + + + + + + ), +}; diff --git a/packages/app/src/components/SplitValueButton/SplitValueButton.tsx b/packages/app/src/components/SplitValueButton/SplitValueButton.tsx new file mode 100644 index 0000000000..5815600b58 --- /dev/null +++ b/packages/app/src/components/SplitValueButton/SplitValueButton.tsx @@ -0,0 +1,91 @@ +import { ComponentPropsWithoutRef, Ref } from 'react'; +import cx from 'classnames'; +import { Text, UnstyledButton } from '@mantine/core'; +import { IconChevronDown } from '@tabler/icons-react'; + +import { useCompactViewport } from '@/components/CompactViewport/useCompactViewport'; + +import classes from './SplitValueButton.module.scss'; + +/** One field by name, several as a count, or none. */ +export function fieldListSummary(fields: string[]): string { + if (fields.length === 0) return 'none'; + if (fields.length === 1) return fields[0]; + return `${fields.length} fields`; +} + +type SplitValueButtonProps = { + /** Fixed name, such as Group by, Columns, or Sort. */ + name: string; + /** Desktop value: a field name, "3 fields", or "none". */ + summary: string; + /** How many fields the summary counts. Drives the narrow-screen number. */ + count: number; + /** The clause is still the source default, so the value is quiet. */ + dimmed?: boolean; + /** Full clause, shown on hover when the value is only a summary. */ + title?: string; + onClick: () => void; + /** Story and test override. Otherwise follows the compact viewport. */ + compact?: boolean; + 'data-testid': string; + ref?: Ref; +} & Omit, 'onClick' | 'title'>; + +/** + * Split button for a search clause: a fixed name, then the current value. + * + * Use it for Group by, Columns, and Sort. The name says which clause it is. + * The value is one field, or "3 fields" when there are several. On a narrow + * screen that count is only the number, so the row still fits. + * + * Group by splits the histogram, one series per value. Columns chooses and + * orders the results table. Sort sets the row order, and a single field + * includes its direction. + * + * Do not use it for an action such as Save, Run, or Apply. + */ +export function SplitValueButton({ + name, + summary, + count, + dimmed, + title, + onClick, + compact, + 'data-testid': testId, + className, + ref, + ...others +}: SplitValueButtonProps) { + const viewportCompact = useCompactViewport(); + const isCompact = compact ?? viewportCompact; + const shown = isCompact && count > 1 ? String(count) : summary; + + return ( +
+ + {name} + + + + {shown} + + + +
+ ); +} diff --git a/packages/app/src/components/SplitValueButton/__tests__/SplitValueButton.test.tsx b/packages/app/src/components/SplitValueButton/__tests__/SplitValueButton.test.tsx new file mode 100644 index 0000000000..e43815f63e --- /dev/null +++ b/packages/app/src/components/SplitValueButton/__tests__/SplitValueButton.test.tsx @@ -0,0 +1,53 @@ +import { screen } from '@testing-library/react'; + +import { SplitValueButton } from '@/components/SplitValueButton/SplitValueButton'; + +describe('SplitValueButton', () => { + it('shows a field count as words on a wide screen', () => { + renderWithMantine( + {}} + data-testid="columns" + />, + ); + expect(screen.getByTestId('columns')).toHaveTextContent('3 fields'); + expect(screen.getByTestId('columns')).toHaveAccessibleName( + 'Columns 3 fields', + ); + }); + + it('shows only the number on a narrow screen', () => { + renderWithMantine( + {}} + data-testid="columns" + />, + ); + expect(screen.getByTestId('columns')).toHaveTextContent('3'); + expect(screen.getByTestId('columns')).toHaveAccessibleName( + 'Columns 3 fields', + ); + }); + + it('keeps a single field name on a narrow screen', () => { + renderWithMantine( + {}} + data-testid="group-by" + />, + ); + expect(screen.getByTestId('group-by')).toHaveTextContent('SeverityText'); + }); +}); From 997803907564c763696872fc5142b53417b0bfd3 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 13:07:38 +0100 Subject: [PATCH 13/14] fix(app): keep backtick-quoted sort names when a column is removed Splitting the remaining ORDER BY on every comma rewrote `a,b` as `a, b`. Sort parsing now lives beside the popover so the component stays under 300 lines. Co-authored-by: Cursor --- packages/app/src/__tests__/utils.test.ts | 10 ++ .../SearchResultsToolbar/SortPopover.tsx | 117 ++---------------- .../SearchResultsToolbar/sortClause.ts | 112 +++++++++++++++++ packages/app/src/utils.ts | 15 ++- 4 files changed, 145 insertions(+), 109 deletions(-) create mode 100644 packages/app/src/components/SearchResultsToolbar/sortClause.ts diff --git a/packages/app/src/__tests__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts index fa5cab439d..586e475844 100644 --- a/packages/app/src/__tests__/utils.test.ts +++ b/packages/app/src/__tests__/utils.test.ts @@ -1551,6 +1551,16 @@ describe('orderByAfterRemovingSelectItem', () => { ), ).toBe('"http.method" DESC'); }); + + it('keeps a comma inside a backtick-quoted sort name', () => { + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS "message"', + '"message" ASC, `a,b` DESC', + 'Timestamp DESC', + ), + ).toBe('`a,b` DESC'); + }); }); describe('getLogSeverityLevel', () => { diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index 6524d6d16f..28c6a15f8d 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -1,7 +1,5 @@ import { useRef, useState } from 'react'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; -import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; -import { findBalancedParens } from '@hyperdx/common-utils/dist/variables'; import { ActionIcon, Autocomplete, @@ -14,115 +12,23 @@ import { import { IconX } from '@tabler/icons-react'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; -import { parseAsSortingStateString } from '@/utils/queryParsers'; import { ClausePopover } from './ClausePopover'; +import { + newSortRow, + parseSortKeys, + sameKeys, + serializeSortKeys, + SortRow, + sortSummary, + toRows, +} from './sortClause'; const DIRECTION_OPTIONS = [ { label: 'Asc', value: 'asc' }, { label: 'Desc', value: 'desc' }, ]; -type SortKey = { id: string; desc: boolean }; -type SortRow = SortKey & { rowId: string }; - -let rowSeq = 0; -const toRows = (keys: SortKey[] | null): SortRow[] | null => - keys?.map(key => ({ ...key, rowId: `sort-${rowSeq++}` })) ?? null; - -/** - * Sort keys the picker can edit. A parenthesized list with one direction, - * `(toDateTime(Timestamp), Timestamp) DESC`, is several fields sharing that - * direction, including function calls. The parentheses have to wrap that whole - * expression: `(a, b) ASC, (c, d) DESC` is two keys, not one list. Anything - * without a plain ASC/DESC on each field stays in SQL. - */ -/** A comma inside backticks cannot be split without breaking the identifier. */ -function hasCommaInsideBackticks(input: string): boolean { - let quoted = false; - for (let i = 0; i < input.length; i++) { - if (input[i] !== '`') { - if (quoted && input[i] === ',') return true; - continue; - } - // ClickHouse escapes a backtick by doubling it. - if (quoted && input[i + 1] === '`') { - i += 1; - continue; - } - quoted = !quoted; - } - return false; -} - -function parseSortKeys(orderBy: string): SortKey[] | null { - const trimmed = orderBy.trim(); - if (!trimmed) return []; - // A comma inside a backtick-quoted name would be split into extra fields. - if (hasCommaInsideBackticks(trimmed)) return null; - - // [\s\S] so a newline inside `(toDateTime(Timestamp),\n Timestamp) DESC` - // still counts as one direction. `.` would miss it and hide the Fields controls. - const direction = trimmed.match(/^([\s\S]*)\s+(asc|desc)$/i); - const expr = direction?.[1].trim() ?? ''; - if ( - direction && - expr.startsWith('(') && - findBalancedParens(expr, 0) === expr.length - 1 - ) { - const ids = splitAndTrimWithBracket(expr.slice(1, -1)); - if (ids.length > 1 && ids.every(id => id.length > 0)) { - const desc = direction[2].toUpperCase() === 'DESC'; - return ids.map(id => ({ id, desc })); - } - } - - const keys: SortKey[] = []; - for (const part of splitAndTrimWithBracket(trimmed)) { - const parsed = parseAsSortingStateString.parse(part); - if (parsed == null || parsed.id.length === 0) return null; - keys.push({ id: parsed.id, desc: parsed.desc }); - } - return keys; -} - -function serializeSortKeys(keys: SortKey[]) { - return keys - .filter(key => key.id.trim()) - .map(key => - parseAsSortingStateString.serialize({ - id: key.id.trim(), - desc: key.desc, - }), - ) - .join(', '); -} - -function sameKeys(a: SortKey[], b: SortKey[]) { - return ( - a.length === b.length && - a.every((key, i) => key.id === b[i].id && key.desc === b[i].desc) - ); -} - -function sortSummary(orderBy: string): { summary: string; count: number } { - const keys = parseSortKeys(orderBy); - if (keys == null) { - const summary = orderBy.trim() || 'none'; - // An expression the field list cannot split stays one value. A number - // would invent a field count the user cannot see in the list. - return { summary, count: summary === 'none' ? 0 : 1 }; - } - if (keys.length === 0) return { summary: 'none', count: 0 }; - if (keys.length === 1) { - return { - summary: `${keys[0].id} ${keys[0].desc ? 'desc' : 'asc'}`, - count: 1, - }; - } - return { summary: `${keys.length} fields`, count: keys.length }; -} - export function SortPopover({ value, defaultValue, @@ -179,10 +85,7 @@ export function SortPopover({ const addKey = (id: string) => { const trimmed = id.trim(); if (!trimmed || used.has(trimmed)) return; - commitKeys([ - ...(keys ?? []), - { id: trimmed, desc: true, rowId: `sort-${rowSeq++}` }, - ]); + commitKeys([...(keys ?? []), newSortRow(trimmed, true)]); setSearch(''); }; diff --git a/packages/app/src/components/SearchResultsToolbar/sortClause.ts b/packages/app/src/components/SearchResultsToolbar/sortClause.ts new file mode 100644 index 0000000000..ba586497f0 --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/sortClause.ts @@ -0,0 +1,112 @@ +import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { findBalancedParens } from '@hyperdx/common-utils/dist/variables'; + +import { parseAsSortingStateString } from '@/utils/queryParsers'; + +export type SortKey = { id: string; desc: boolean }; +export type SortRow = SortKey & { rowId: string }; + +let rowSeq = 0; + +export function newSortRow(id: string, desc: boolean): SortRow { + return { id, desc, rowId: `sort-${rowSeq++}` }; +} + +export const toRows = (keys: SortKey[] | null): SortRow[] | null => + keys?.map(key => newSortRow(key.id, key.desc)) ?? null; + +/** A comma inside backticks cannot be split without breaking the identifier. */ +function hasCommaInsideBackticks(input: string): boolean { + let quoted = false; + for (let i = 0; i < input.length; i++) { + if (input[i] !== '`') { + if (quoted && input[i] === ',') return true; + continue; + } + // ClickHouse escapes a backtick by doubling it. + if (quoted && input[i + 1] === '`') { + i += 1; + continue; + } + quoted = !quoted; + } + return false; +} + +/** + * Sort keys the picker can edit. A parenthesized list with one direction, + * `(toDateTime(Timestamp), Timestamp) DESC`, is several fields sharing that + * direction, including function calls. The parentheses have to wrap that whole + * expression: `(a, b) ASC, (c, d) DESC` is two keys, not one list. Anything + * without a plain ASC/DESC on each field stays in SQL. + */ +export function parseSortKeys(orderBy: string): SortKey[] | null { + const trimmed = orderBy.trim(); + if (!trimmed) return []; + // A comma inside a backtick-quoted name would be split into extra fields. + if (hasCommaInsideBackticks(trimmed)) return null; + + // [\s\S] so a newline inside `(toDateTime(Timestamp),\n Timestamp) DESC` + // still counts as one direction. `.` would miss it and hide the Fields controls. + const direction = trimmed.match(/^([\s\S]*)\s+(asc|desc)$/i); + const expr = direction?.[1].trim() ?? ''; + if ( + direction && + expr.startsWith('(') && + findBalancedParens(expr, 0) === expr.length - 1 + ) { + const ids = splitAndTrimWithBracket(expr.slice(1, -1)); + if (ids.length > 1 && ids.every(id => id.length > 0)) { + const desc = direction[2].toUpperCase() === 'DESC'; + return ids.map(id => ({ id, desc })); + } + } + + const keys: SortKey[] = []; + for (const part of splitAndTrimWithBracket(trimmed)) { + const parsed = parseAsSortingStateString.parse(part); + if (parsed == null || parsed.id.length === 0) return null; + keys.push({ id: parsed.id, desc: parsed.desc }); + } + return keys; +} + +export function serializeSortKeys(keys: SortKey[]) { + return keys + .filter(key => key.id.trim()) + .map(key => + parseAsSortingStateString.serialize({ + id: key.id.trim(), + desc: key.desc, + }), + ) + .join(', '); +} + +export function sameKeys(a: SortKey[], b: SortKey[]) { + return ( + a.length === b.length && + a.every((key, i) => key.id === b[i].id && key.desc === b[i].desc) + ); +} + +export function sortSummary(orderBy: string): { + summary: string; + count: number; +} { + const keys = parseSortKeys(orderBy); + if (keys == null) { + const summary = orderBy.trim() || 'none'; + // An expression the field list cannot split stays one value. A number + // would invent a field count the user cannot see in the list. + return { summary, count: summary === 'none' ? 0 : 1 }; + } + if (keys.length === 0) return { summary: 'none', count: 0 }; + if (keys.length === 1) { + return { + summary: `${keys[0].id} ${keys[0].desc ? 'desc' : 'asc'}`, + count: 1, + }; + } + return { summary: `${keys.length} fields`, count: keys.length }; +} diff --git a/packages/app/src/utils.ts b/packages/app/src/utils.ts index 89d1cc74d7..eedfa12d1f 100644 --- a/packages/app/src/utils.ts +++ b/packages/app/src/utils.ts @@ -8,7 +8,11 @@ import { TableConnection, unquoteIdentifier, } from '@hyperdx/common-utils/dist/core/metadata'; -import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; +import { + replaceBacktickedIdentifiers, + restoreReplacements, + splitAndTrimWithBracket, +} from '@hyperdx/common-utils/dist/core/utils'; import { CATEGORICAL_PALETTE_TOKENS, ChartPaletteToken, @@ -1306,7 +1310,14 @@ export const orderByAfterRemovingSelectItem = ( return orderBy; } const quoted = `"${alias}"`; - const keys = splitAndTrimWithBracket(orderBy); + // A comma inside a backtick-quoted name is not a separator. Tokenize those + // names before splitting so joining the kept keys cannot insert a space + // inside one. The shared splitter stays unaware of backticks. + const { sqlWithReplacements, replacements } = + replaceBacktickedIdentifiers(orderBy); + const keys = splitAndTrimWithBracket(sqlWithReplacements).map(key => + restoreReplacements(key, replacements.quotedText), + ); const kept = keys.filter( key => key.replace(/\s+(ASC|DESC)$/i, '') !== quoted, ); From 2ac10de01cf7172b0332e36f73d96b3c6ccfeba6 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 14:27:07 +0100 Subject: [PATCH 14/14] fix(app): keep quoted column names and custom sorts intact The column list split backtick-quoted names on commas, and Add sort replaced a clause the field list could not parse. The column row moved out so ColumnsPopover stays under 300 lines. Co-authored-by: Cursor --- packages/app/src/__tests__/utils.test.ts | 11 +++ .../SearchResultsToolbar/ColumnsPopover.tsx | 83 +------------------ .../SearchResultsToolbar/SortPopover.tsx | 48 ++++++----- .../SearchResultsToolbar/SortableColumn.tsx | 75 +++++++++++++++++ .../__tests__/ColumnsPopover.test.tsx | 12 +++ .../__tests__/SortPopover.test.tsx | 3 + packages/app/src/utils.ts | 22 +++-- 7 files changed, 145 insertions(+), 109 deletions(-) create mode 100644 packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx diff --git a/packages/app/src/__tests__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts index 586e475844..92774a7183 100644 --- a/packages/app/src/__tests__/utils.test.ts +++ b/packages/app/src/__tests__/utils.test.ts @@ -30,6 +30,7 @@ import { parseTimestampToMs, resolveConditionalColor, sortingStateToOrderByString, + splitClauseList, stripTrailingSlash, useQueryHistory, withMapKeyAlias, @@ -1506,6 +1507,16 @@ describe('isColumnInSelect', () => { }); }); +describe('splitClauseList', () => { + it('keeps a comma inside a backtick-quoted name', () => { + expect(splitClauseList('Timestamp, `a,b`, Body')).toEqual([ + 'Timestamp', + '`a,b`', + 'Body', + ]); + }); +}); + describe('orderByAfterRemovingSelectItem', () => { const item = `ResourceAttributes['service.name'] AS "service.name"`; diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index f3dcaf9a84..375a0e5dcf 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -10,14 +10,10 @@ import { import { arrayMove, SortableContext, - useSortable, verticalListSortingStrategy, } from '@dnd-kit/sortable'; -import { CSS } from '@dnd-kit/utilities'; import { TableConnection } from '@hyperdx/common-utils/dist/core/metadata'; -import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils'; import { - ActionIcon, Autocomplete, Box, Button, @@ -26,87 +22,16 @@ import { Stack, Text, } from '@mantine/core'; -import { IconGripVertical, IconX } from '@tabler/icons-react'; import { fieldListSummary } from '@/components/SplitValueButton/SplitValueButton'; import SQLInlineEditor from '@/components/SQLEditor/SQLInlineEditor'; -import { withMapKeyAlias } from '@/utils'; +import { splitClauseList, withMapKeyAlias } from '@/utils'; import { ClausePopover } from './ClausePopover'; +import { SortableColumn } from './SortableColumn'; const columnId = (item: string, index: number) => `${index}:${item}`; -function SortableColumn({ - id, - label, - onRemove, -}: { - id: string; - label: string; - onRemove: () => void; -}) { - const { - attributes, - listeners, - setNodeRef, - transform, - transition, - isDragging, - } = useSortable({ id }); - - return ( - - - - - - - {label} - - - - - - - ); -} - export function ColumnsPopover({ value, defaultValue, @@ -138,10 +63,10 @@ export function ColumnsPopover({ // An empty stored SELECT means "use the source default". An empty draft does // not: the user may have removed every column before adding a replacement. const storedColumns = (select: string) => - splitAndTrimWithBracket(select || defaultValue); + splitClauseList(select || defaultValue); const shown = storedColumns(value); - const items = splitAndTrimWithBracket(draft); + const items = splitClauseList(draft); const options = useMemo( () => fieldOptions.filter(option => !items.includes(option)), diff --git a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx index 28c6a15f8d..0a58fa7acc 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortPopover.tsx @@ -84,8 +84,10 @@ export function SortPopover({ const addKey = (id: string) => { const trimmed = id.trim(); - if (!trimmed || used.has(trimmed)) return; - commitKeys([...(keys ?? []), newSortRow(trimmed, true)]); + // A clause the field list cannot split, such as `Timestamp DESC NULLS LAST`, + // stays intact. Adding a field here would replace the whole clause. + if (keys == null || !trimmed || used.has(trimmed)) return; + commitKeys([...keys, newSortRow(trimmed, true)]); setSearch(''); }; @@ -174,26 +176,28 @@ export function SortPopover({ )} - { - if (ignoreNextChangeRef.current) { - ignoreNextChangeRef.current = false; - return; - } - setSearch(next); - }} - data={addOptions} - limit={50} - onOptionSubmit={id => { - ignoreNextChangeRef.current = true; - addKey(id); - }} - comboboxProps={{ withinPortal: false }} - data-testid="search-sort-add-input" - /> + {keys != null && ( + { + if (ignoreNextChangeRef.current) { + ignoreNextChangeRef.current = false; + return; + } + setSearch(next); + }} + data={addOptions} + limit={50} + onOptionSubmit={id => { + ignoreNextChangeRef.current = true; + addKey(id); + }} + comboboxProps={{ withinPortal: false }} + data-testid="search-sort-add-input" + /> + )} )} renderSql={apply => ( diff --git a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx new file mode 100644 index 0000000000..6df50d85e5 --- /dev/null +++ b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx @@ -0,0 +1,75 @@ +import { useSortable } from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; +import { ActionIcon, Box, Group, Text } from '@mantine/core'; +import { IconGripVertical, IconX } from '@tabler/icons-react'; + +export function SortableColumn({ + id, + label, + onRemove, +}: { + id: string; + label: string; + onRemove: () => void; +}) { + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id }); + + return ( + + + + + + + {label} + + + + + + + ); +} diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index 8fb7fcb15c..1be855de79 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -84,6 +84,18 @@ describe('ColumnsPopover', () => { ).not.toBeInTheDocument(); }); + it('keeps a backtick-quoted name when another column is removed', async () => { + const { onApply } = renderPopover({ + value: 'Timestamp, `a,b`, Body', + defaultValue: 'Timestamp', + }); + openPopover(); + fireEvent.click(await screen.findByLabelText('Remove Body')); + expect(screen.getByLabelText('Remove `a,b`')).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith('Timestamp, `a,b`', ['Body']); + }); + it('removes a column and reports it on apply', async () => { const { onApply } = renderPopover(); openPopover(); diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx index 369c35b7ae..d1ec5d1409 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/SortPopover.test.tsx @@ -108,6 +108,9 @@ describe('SortPopover', () => { expect(editor).toHaveValue(custom); fireEvent.click(screen.getByText('Fields')); expect(screen.getByTestId('search-sort-custom')).toBeInTheDocument(); + expect( + screen.queryByTestId('search-sort-add-input'), + ).not.toBeInTheDocument(); fireEvent.click(screen.getByText('SQL')); fireEvent.change(screen.getByLabelText('ORDER BY'), { target: { value: 'Body ASC' }, diff --git a/packages/app/src/utils.ts b/packages/app/src/utils.ts index eedfa12d1f..1eb769dbf3 100644 --- a/packages/app/src/utils.ts +++ b/packages/app/src/utils.ts @@ -1294,6 +1294,19 @@ export const withMapKeyAlias = ( return `${column} AS "${key}"`; }; +/** + * Split a SELECT or ORDER BY list. A comma inside a backtick-quoted name is + * not a separator. Those names are tokenized first so a later join cannot + * insert a space inside one. The shared splitter stays unaware of backticks. + */ +export function splitClauseList(input: string): string[] { + const { sqlWithReplacements, replacements } = + replaceBacktickedIdentifiers(input); + return splitAndTrimWithBracket(sqlWithReplacements).map(part => + restoreReplacements(part, replacements.quotedText), + ); +} + /** * The sort to keep once a SELECT item is removed. Sorting on an aliased column * from the table header orders by the alias itself (`"service.name" DESC`), @@ -1310,14 +1323,7 @@ export const orderByAfterRemovingSelectItem = ( return orderBy; } const quoted = `"${alias}"`; - // A comma inside a backtick-quoted name is not a separator. Tokenize those - // names before splitting so joining the kept keys cannot insert a space - // inside one. The shared splitter stays unaware of backticks. - const { sqlWithReplacements, replacements } = - replaceBacktickedIdentifiers(orderBy); - const keys = splitAndTrimWithBracket(sqlWithReplacements).map(key => - restoreReplacements(key, replacements.quotedText), - ); + const keys = splitClauseList(orderBy); const kept = keys.filter( key => key.replace(/\s+(ASC|DESC)$/i, '') !== quoted, );