From b5442e50fb845340e55eb6481bbeaab12e3cb462 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Wed, 21 Oct 2026 16:55:04 +0100 Subject: [PATCH 01/21] feat(app): mount Columns and Sort on the search page SELECT and ORDER BY move off the query form onto the results table, and the where row wraps under the time controls on a narrow form. Co-authored-by: Cursor --- .changeset/search-columns-sort-popovers.md | 5 + packages/app/src/DBSearchPage.tsx | 263 +++++++++--------- .../DBSearchPage.directTrace.test.tsx | 9 + packages/app/src/components/DBRowTable.tsx | 195 +++++++------ .../components/DBSqlRowTableWithSidebar.tsx | 8 +- packages/app/styles/SearchPage.module.scss | 42 +++ .../e2e/features/search/saved-search.spec.ts | 122 ++++---- .../tests/e2e/features/search/search.spec.ts | 5 +- .../e2e/features/shared/input-focus.spec.ts | 2 + .../e2e/features/shared/multiline.spec.ts | 9 +- .../app/tests/e2e/page-objects/SearchPage.ts | 77 ++++- 11 files changed, 448 insertions(+), 289 deletions(-) create mode 100644 .changeset/search-columns-sort-popovers.md diff --git a/.changeset/search-columns-sort-popovers.md b/.changeset/search-columns-sort-popovers.md new file mode 100644 index 0000000000..6bd0e8ed0e --- /dev/null +++ b/.changeset/search-columns-sort-popovers.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: Edit search SELECT and ORDER BY from Columns and Sort popovers on the results table, and tidy the table controls row diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 9f5f62522c..88d515a8a3 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -112,10 +112,12 @@ import SearchWhereInput, { getStoredLanguage, } from '@/components/SearchInput/SearchWhereInput'; import SearchPageActionBar from '@/components/SearchPageActionBar'; +import { ColumnsPopover } from '@/components/SearchResultsToolbar/ColumnsPopover'; +import { SortPopover } from '@/components/SearchResultsToolbar/SortPopover'; +import { useClauseFieldOptions } from '@/components/SearchResultsToolbar/useClauseFieldOptions'; import SearchTotalCountChart from '@/components/SearchTotalCountChart'; import { TableSourceForm } from '@/components/Sources/SourceForm'; import { SourceSelectControlled } from '@/components/SourceSelect'; -import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; import { Tags } from '@/components/Tags'; import { TimePicker } from '@/components/TimePicker'; import { IS_LOCAL_MODE } from '@/config'; @@ -1146,9 +1148,6 @@ function DBSearchPageContent() { // key from a phone would collapse the sidebar the next time the same // browser opens the page on a desktop. const [isCompactFiltersOpen, setIsCompactFiltersOpen] = useState(false); - // SELECT grows with its text. On a phone that pushes the logs off the - // screen, so the column editors stay closed until the user asks. - const [columnsOpen, setColumnsOpen] = useState(false); const isCompact = useCompactViewport(); const filtersCollapsed = isCompact ? !isCompactFiltersOpen @@ -2171,6 +2170,15 @@ function DBSearchPageContent() { [inputSourceObj], ); + const inputSelect = useWatch({ name: 'select', control }); + const inputOrderBy = useWatch({ name: 'orderBy', control }); + const clauseFieldOptions = useClauseFieldOptions({ + tableConnection: inputSourceTableConnection, + columns: inputSourceColumns, + dateRange: searchedTimeRange, + timestampValueExpression: inputSourceObj?.timestampValueExpression, + }); + const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] = useState(false); @@ -2293,51 +2301,57 @@ function DBSearchPageContent() { [setValue, setNewSourceModalClosed], ); - const columnFields = (allowMultiline: boolean, stacked: boolean) => { - const select = ( - - ); - const orderBy = ( - - ); - if (stacked) { - return ( - <> - {select} - {orderBy} - - ); - } - return ( - <> - {select} - {orderBy} - - ); - }; + const applySelect = useCallback( + (select: string, removedItems: string[]) => { + setValue('select', select); + let orderBy = getValues('orderBy') ?? ''; + for (const item of removedItems) { + orderBy = orderByAfterRemovingSelectItem( + item, + orderBy, + defaultSearchConfig.orderBy ?? '', + ); + } + setValue('orderBy', orderBy); + onSubmit(); + }, + [setValue, getValues, defaultSearchConfig.orderBy, onSubmit], + ); + + const applyOrderBy = useCallback( + (orderBy: string) => { + setValue('orderBy', orderBy); + onSubmit(); + }, + [setValue, onSubmit], + ); + + // 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)} - /> - {!isCompact && columnFields(true, false)} - <> + {!savedSearchId ? ( @@ -2525,7 +2533,6 @@ function DBSearchPageContent() { onClick={() => { setSaveSearchModalState('update'); }} - style={{ flexShrink: 0 }} > Update @@ -2536,7 +2543,6 @@ function DBSearchPageContent() { variant="secondary" size="xs" onClick={openAlertModal} - style={{ flexShrink: 0 }} > Alerts @@ -2544,74 +2550,53 @@ function DBSearchPageContent() { )} - {isCompact && ( - - )} - + - {isCompact && columnsOpen && ( - - {columnFields(false, true)} - - )} - - - + + + - + + + {isLive && ( @@ -2635,6 +2620,22 @@ function DBSearchPageContent() { + setIsSourceSchemaPreviewOpen(false)} + /> + + {!queryReady ? ( - } - title="No data to display" - description="Select a source and click the play button to query data." - /> + + {resultsClauseEditors != null && ( + + {resultsClauseEditors} + + )} + } + title="No data to display" + description="Select a source and click the play button to query data." + /> + ) : ( <> + {resultsClauseEditors != null && ( + + {resultsClauseEditors} + + )}
{whereSuggestions && whereSuggestions.length > 0 && ( @@ -3031,6 +3044,8 @@ function DBSearchPageContent() { selectionResetKey={selectionResetKey} onSelectedRowsChange={onSelectedRowsChange} onResolvedColumnsChange={onResolvedColumnsChange} + toolbarLeading={resultsClauseEditors} + controlsAboveTable /> )} diff --git a/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx b/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx index 5b335588ff..4e7cf0e478 100644 --- a/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx +++ b/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx @@ -196,6 +196,15 @@ jest.mock('@/components/SearchGroupBy/SearchGroupBySelect', () => ({ SearchGroupBySelect: () =>
, })); jest.mock('@/components/SearchPageActionBar', () => () =>
); +jest.mock('@/components/SearchResultsToolbar/ColumnsPopover', () => ({ + ColumnsPopover: () =>
, +})); +jest.mock('@/components/SearchResultsToolbar/SortPopover', () => ({ + SortPopover: () =>
, +})); +jest.mock('@/components/SearchResultsToolbar/useClauseFieldOptions', () => ({ + useClauseFieldOptions: () => [], +})); jest.mock('@/components/SearchTotalCountChart', () => () =>
); jest.mock('@/components/Sources/SourceForm', () => ({ TableSourceForm: () =>
, diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 6e5885b4a8..0fb7b7d0ca 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -40,13 +40,13 @@ import { TSource, } from '@hyperdx/common-utils/dist/types'; import { + ActionIcon, Box, Flex, Group, Modal, Text, Tooltip as MantineTooltip, - UnstyledButton, } from '@mantine/core'; import { IconCode, @@ -389,6 +389,8 @@ export const RawLogTable = memo( getRowWhere, variant = 'default', onRemoveColumn, + toolbarLeading, + controlsAboveTable = false, }: { wrapLines?: boolean; displayedColumns: string[]; @@ -432,6 +434,10 @@ export const RawLogTable = memo( getRowWhere?: (row: Record) => RowWhereResult; variant?: DBRowTableVariant; onRemoveColumn?: (column: string) => void; + /** Rendered on the left of the bar above the table. */ + toolbarLeading?: React.ReactNode; + /** Keep the header actions above the table instead of in the last column. */ + controlsAboveTable?: boolean; }) => { const dedupedRows = useMemo(() => { const lIds = new Set(); @@ -1031,8 +1037,107 @@ export const RawLogTable = memo( [], ); + // Above the scroll area, so a wide table can't scroll these out of view. + const wrapLinesLabel = wrapLinesEnabled ? 'Unwrap lines' : 'Wrap lines'; + const csvLabel = `Download as CSV (max ${maxRows.toLocaleString()} rows)${isLimited ? ', data truncated' : ''}`; + const rowSelectionMenu = enableRowSelection ? ( + + ) : null; + + const tableControls = ( + + {tableId && Object.keys(columnSizeStorage).length > 0 && ( + + setColumnSizeStorage({})} + aria-label="Reset column widths" + > + + + + )} + + setWrapLinesEnabled(prev => !prev)} + aria-label={wrapLinesLabel} + > + {wrapLinesEnabled ? ( + + ) : ( + + )} + + + {config && ( + + handleSqlModalOpen(true)} + aria-label="Show generated SQL" + > + + + + )} + + + + + + + + {onSettingsClick != null && ( + + onSettingsClick()} + aria-label="Settings" + > + + + + )} + {!controlsAboveTable && rowSelectionMenu} + + ); + return ( + {(controlsAboveTable || toolbarLeading != null) && ( + + + {toolbarLeading} + {controlsAboveTable && rowSelectionMenu} + + {controlsAboveTable && ( + + {tableControls} + + )} + + )} {/* Find within page search bar - floating on top right */} - {tableId && - Object.keys(columnSizeStorage).length > 0 && ( - setColumnSizeStorage({})} - title="Reset Column Widths" - display="flex" - > - - - - - )} - {config && ( - handleSqlModalOpen(true)} - title="Show Generated SQL" - tabIndex={0} - display="flex" - > - - - - - )} - - setWrapLinesEnabled(prev => !prev) - } - title={`${wrapLinesEnabled ? 'Disable' : 'Enable'} Wrap Lines`} - display="flex" - > - - {wrapLinesEnabled ? ( - - ) : ( - - )} - - - - - - - - - {onSettingsClick != null && ( - onSettingsClick()} - title="Settings" - display="flex" - > - - - - - )} - {enableRowSelection && ( - - )} - + controlsAboveTable ? undefined : tableControls } /> ); @@ -1677,6 +1702,8 @@ function DBSqlRowTableComponent({ tableId, errorVariant, onResolvedColumnsChange, + toolbarLeading, + controlsAboveTable, }: { config: BuilderChartConfigWithDateRange; sourceId?: string; @@ -1710,6 +1737,8 @@ function DBSqlRowTableComponent({ tableId?: string; errorVariant?: ChartErrorStateVariant; onResolvedColumnsChange?: (meta: ColumnMetaType[]) => void; + toolbarLeading?: React.ReactNode; + controlsAboveTable?: boolean; }) { const { data: me } = api.useMe(); const { toggleColumn, displayedColumns: contextDisplayedColumns } = @@ -2033,6 +2062,8 @@ function DBSqlRowTableComponent({ variant={variant} onRemoveColumn={toggleColumn ? onRemoveColumnFromTable : undefined} tableId={tableId} + toolbarLeading={toolbarLeading} + controlsAboveTable={controlsAboveTable} /> ); diff --git a/packages/app/src/components/DBSqlRowTableWithSidebar.tsx b/packages/app/src/components/DBSqlRowTableWithSidebar.tsx index c683786711..bdb6b34820 100644 --- a/packages/app/src/components/DBSqlRowTableWithSidebar.tsx +++ b/packages/app/src/components/DBSqlRowTableWithSidebar.tsx @@ -1,4 +1,4 @@ -import { useCallback, useState } from 'react'; +import { type ReactNode, useCallback, useState } from 'react'; import { useQueryState } from 'nuqs'; import { ClickHouseQueryError, @@ -50,6 +50,8 @@ interface Props { selectionResetKey?: string; onSelectedRowsChange?: (hasSelectedRows: boolean) => void; onResolvedColumnsChange?: (meta: ColumnMetaType[]) => void; + toolbarLeading?: ReactNode; + controlsAboveTable?: boolean; // Clicking outside the row side panel (and outside `keepOpenSelector`) closes // it. Enabled by default; pass `false` to opt out. closeOnClickOutside?: boolean; @@ -82,6 +84,8 @@ export default function DBSqlRowTableWithSideBar({ selectionResetKey, onSelectedRowsChange, onResolvedColumnsChange, + toolbarLeading, + controlsAboveTable, closeOnClickOutside = true, keepOpenSelector = DEFAULT_KEEP_OPEN_SELECTOR, }: Props) { @@ -163,6 +167,8 @@ export default function DBSqlRowTableWithSideBar({ selectionResetKey={selectionResetKey} onSelectedRowsChange={onSelectedRowsChange} onResolvedColumnsChange={onResolvedColumnsChange} + toolbarLeading={toolbarLeading} + controlsAboveTable={controlsAboveTable} /> ); diff --git a/packages/app/styles/SearchPage.module.scss b/packages/app/styles/SearchPage.module.scss index 713ee35f05..e291a44a94 100644 --- a/packages/app/styles/SearchPage.module.scss +++ b/packages/app/styles/SearchPage.module.scss @@ -171,4 +171,46 @@ 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; +} + +.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) { + .whereRow { + flex-wrap: nowrap; + } +} + +@container (max-width: 899px) { + .whereField { + flex-basis: 100%; + } + + .timeControls { + flex-basis: 100%; + } } 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 5806833fdc..215a24c5e6 100644 --- a/packages/app/tests/e2e/page-objects/SearchPage.ts +++ b/packages/app/tests/e2e/page-objects/SearchPage.ts @@ -459,11 +459,53 @@ 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.locator('.cm-content').first(); + 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 { @@ -505,33 +547,42 @@ export class SearchPage { * Get ORDER BY editor (CodeMirror) */ getOrderByEditor() { - return this.page.locator('.cm-content').nth(1); + return this.page + .getByTestId('search-order-by-input') + .locator('.cm-content'); } /** - * 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' }); } get groupByButton() { From c02c1b60b05b1e64b75cb76e5b1f56959394e430 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 23 Oct 2026 14:48:05 +0100 Subject: [PATCH 02/21] fix(app): let the results toolbar wrap on a narrow screen Columns, Sort, and the table actions move onto another line instead of overlapping when the results panel is narrow. Co-authored-by: Cursor --- packages/app/src/DBSearchPage.tsx | 2 +- packages/app/src/components/DBRowTable.tsx | 8 ++++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 88d515a8a3..d6e1f5b507 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2330,7 +2330,7 @@ function DBSearchPageContent() { // and stay hidden on Event Deltas and Event Patterns. const resultsClauseEditors = analysisMode === 'results' ? ( - + - + {toolbarLeading} {controlsAboveTable && rowSelectionMenu} From 3f6bae38622f082b24d67504b617451a5e6bbc61 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Fri, 23 Oct 2026 15:21:55 +0100 Subject: [PATCH 03/21] fix(app): keep clause Apply above the SQL completion list Typing in the popover reopens the completion list over Apply, so the saved-search click never lands. Co-authored-by: Cursor --- .../SearchResultsToolbar/ClausePopover.tsx | 12 +++++++++++- .../app/tests/e2e/page-objects/SearchPage.ts | 18 +++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx index 0c7450e259..9140882eda 100644 --- a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx @@ -123,7 +123,17 @@ export function ClausePopover({ data-testid={`${testId}-mode`} /> {mode === 'pick' ? renderPick(apply) : renderSql(apply)} - + - + - Select a column, or type an expression such as{' '} - upper(Body) as message and add it to the list. Then - click Apply. + Select a column to add it, or type an expression such as{' '} + upper(Body) as message and click Add. Click a column to + edit it. Then click Apply. )} diff --git a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx index 6df50d85e5..5bb74d0373 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx @@ -1,16 +1,20 @@ +import { useRef, useState } from 'react'; 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'; +import { ActionIcon, Box, Group, Text, TextInput } from '@mantine/core'; +import { IconGripVertical, IconPencil, IconX } from '@tabler/icons-react'; export function SortableColumn({ id, label, onRemove, + onEdit, }: { id: string; label: string; onRemove: () => void; + /** Called with the trimmed expression when an edit changes the column. */ + onEdit?: (next: string) => void; }) { const { attributes, @@ -21,6 +25,28 @@ export function SortableColumn({ isDragging, } = useSortable({ id }); + const [editing, setEditing] = useState(false); + const [draft, setDraft] = useState(label); + // Enter and Escape unmount the input, which can fire blur. Without this the + // edit would be committed (or discarded) a second time. + const finishedRef = useRef(false); + + const startEdit = () => { + if (!onEdit) return; + finishedRef.current = false; + setDraft(label); + setEditing(true); + }; + + const finishEdit = (commit: boolean) => { + if (finishedRef.current) return; + finishedRef.current = true; + setEditing(false); + const next = draft.trim(); + // An empty value reverts, so a column is not removed by accident. + if (commit && next && next !== label) onEdit?.(next); + }; + return ( - - {label} - + {editing ? ( + setDraft(e.currentTarget.value)} + onBlur={() => finishEdit(true)} + onKeyDown={e => { + if (e.key === 'Enter') { + // The search form is an ancestor, so Enter would submit it. + e.preventDefault(); + e.stopPropagation(); + finishEdit(true); + } else if (e.key === 'Escape') { + e.stopPropagation(); + finishEdit(false); + } + }} + autoFocus + ff="monospace" + style={{ flex: 1, minWidth: 0 }} + // Lets ClausePopover pass Escape through instead of discarding. + data-handles-escape + data-testid="search-columns-edit-input" + /> + ) : ( + + {label} + + )} + {onEdit && !editing && ( + + + + )} { expect(input).toHaveValue("LogAttributes['region']"); }); - it('shows a map key alias in the input before adding it', async () => { + it('adds a picked map key with its alias and clears the input', async () => { renderPopover({ fieldOptions: ["LogAttributes['ads.consent_given']"], }); @@ -173,10 +173,6 @@ describe('ColumnsPopover', () => { 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( @@ -185,17 +181,12 @@ describe('ColumnsPopover', () => { ).toBeInTheDocument(); }); - it('fills the input from a suggestion and adds only on Add', async () => { + it('adds a column as soon as a suggestion is picked', async () => { const { onApply } = renderPopover(); openPopover(); 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')); @@ -221,6 +212,85 @@ describe('ColumnsPopover', () => { ); }); + describe('editing a column in place', () => { + const tz = `LogAttributes['tz'] AS "tz"`; + const openWithTz = async () => { + const rendered = renderPopover({ + value: `Timestamp, ${tz}`, + defaultValue: 'Timestamp', + }); + openPopover(); + fireEvent.click(await screen.findByLabelText(`Edit ${tz}`)); + return { + ...rendered, + input: screen.getByTestId('search-columns-edit-input'), + }; + }; + + it('renames an alias on Enter and reports the old item as removed', async () => { + const { onApply, input } = await openWithTz(); + expect(input).toHaveValue(tz); + fireEvent.change(input, { + target: { value: `LogAttributes['tz'] AS "timezone"` }, + }); + fireEvent.keyDown(input, { key: 'Enter' }); + expect( + screen.queryByTestId('search-columns-edit-input'), + ).not.toBeInTheDocument(); + expect( + screen.getByLabelText(`Remove LogAttributes['tz'] AS "timezone"`), + ).toBeInTheDocument(); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith( + `Timestamp, LogAttributes['tz'] AS "timezone"`, + [tz], + ); + }); + + it('commits on blur', async () => { + const { input } = await openWithTz(); + fireEvent.change(input, { + target: { value: `LogAttributes['tz'] AS "zone"` }, + }); + fireEvent.blur(input); + expect( + screen.getByLabelText(`Remove LogAttributes['tz'] AS "zone"`), + ).toBeInTheDocument(); + }); + + it('starts editing when the column text is clicked', async () => { + renderPopover(); + openPopover(); + fireEvent.click(await screen.findByText('Body')); + expect(screen.getByTestId('search-columns-edit-input')).toHaveValue( + 'Body', + ); + }); + + it('cancels on Escape without closing the popover or asking to discard', async () => { + const { input } = await openWithTz(); + fireEvent.change(input, { + target: { value: `LogAttributes['tz'] AS "timezone"` }, + }); + fireEvent.keyDown(input, { key: 'Escape' }); + expect(screen.getByLabelText(`Remove ${tz}`)).toBeInTheDocument(); + expect(confirm).not.toHaveBeenCalled(); + expect( + screen.getByTestId('search-columns-button-popover'), + ).toBeInTheDocument(); + expect( + screen.queryByTestId('search-columns-edit-input'), + ).not.toBeInTheDocument(); + }); + + it('reverts an empty value instead of removing the column', async () => { + const { input } = await openWithTz(); + fireEvent.change(input, { target: { value: ' ' } }); + fireEvent.blur(input); + expect(screen.getByLabelText(`Remove ${tz}`)).toBeInTheDocument(); + }); + }); + it('resets a changed column list to the source default', async () => { const { onApply } = renderPopover(); openPopover(); From 033505ccfa22e5d9dfc5eb11ffe9ca80782684ae Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Mon, 23 Nov 2026 17:06:16 +0000 Subject: [PATCH 19/21] fix(app): wrap long columns while editing in the Columns popover The inline edit field was a single-line input, so a long expression such as a map key with an alias scrolled sideways and was hard to edit. Use an auto-growing textarea in the same monospace font and wrapping as the row, and place the caret at the end. Pasted line breaks are collapsed to spaces because a column is a single expression. --- .../SearchResultsToolbar/SortableColumn.tsx | 27 ++++++++++++++++--- .../__tests__/ColumnsPopover.test.tsx | 15 +++++++++++ 2 files changed, 38 insertions(+), 4 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx index 5bb74d0373..24ce8bb10f 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx @@ -1,7 +1,7 @@ import { useRef, useState } from 'react'; import { useSortable } from '@dnd-kit/sortable'; import { CSS } from '@dnd-kit/utilities'; -import { ActionIcon, Box, Group, Text, TextInput } from '@mantine/core'; +import { ActionIcon, Box, Group, Text, Textarea } from '@mantine/core'; import { IconGripVertical, IconPencil, IconX } from '@tabler/icons-react'; export function SortableColumn({ @@ -79,11 +79,19 @@ export function SortableColumn({ {editing ? ( - setDraft(e.currentTarget.value)} + // A column is one expression. Pasted line breaks would otherwise + // be stored as part of it. + onChange={e => + setDraft(e.currentTarget.value.replace(/\s*\r?\n\s*/g, ' ')) + } + onFocus={e => { + const end = e.currentTarget.value.length; + e.currentTarget.setSelectionRange(end, end); + }} onBlur={() => finishEdit(true)} onKeyDown={e => { if (e.key === 'Enter') { @@ -97,7 +105,18 @@ export function SortableColumn({ } }} autoFocus - ff="monospace" + // Wrap and grow like the row text, so a long expression stays + // readable instead of scrolling sideways. + autosize + minRows={1} + maxRows={8} + styles={{ + input: { + fontFamily: 'var(--mantine-font-family-monospace)', + lineHeight: 1.5, + overflowWrap: 'anywhere', + }, + }} style={{ flex: 1, minWidth: 0 }} // Lets ClausePopover pass Escape through instead of discarding. data-handles-escape diff --git a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx index 8d14f6255a..aee02c4d9a 100644 --- a/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx +++ b/packages/app/src/components/SearchResultsToolbar/__tests__/ColumnsPopover.test.tsx @@ -247,6 +247,21 @@ describe('ColumnsPopover', () => { ); }); + it('edits in a wrapping field and drops pasted line breaks', async () => { + const { onApply, input } = await openWithTz(); + expect(input.tagName).toBe('TEXTAREA'); + fireEvent.change(input, { + target: { value: `LogAttributes['tz']\n AS "timezone"` }, + }); + expect(input).toHaveValue(`LogAttributes['tz'] AS "timezone"`); + fireEvent.keyDown(input, { key: 'Enter' }); + fireEvent.click(screen.getByTestId('search-columns-button-apply')); + expect(onApply).toHaveBeenCalledWith( + `Timestamp, LogAttributes['tz'] AS "timezone"`, + [tz], + ); + }); + it('commits on blur', async () => { const { input } = await openWithTz(); fireEvent.change(input, { From 96559bd7669e23a0327ed7d2ab60403cff3a7e74 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Mon, 23 Nov 2026 17:12:40 +0000 Subject: [PATCH 20/21] fix(app): wrap column suggestions in the Columns popover Long column names such as LogAttributes['browser.resource_timing...'] were clipped in the suggestion list, and the clipped part is the part that tells similar names apart. Let options wrap and widen the dropdown, capped to stay inside the popover. --- .../SearchResultsToolbar/ColumnsPopover.tsx | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 0d2207290a..0d2429ae9a 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -191,7 +191,20 @@ export function ColumnsPopover({ }} data={options} limit={50} - comboboxProps={{ withinPortal: false }} + comboboxProps={{ + withinPortal: false, + // Wider than the input so long names fit, but inside the popover. + width: 'min(400px, calc(100vw - 48px))', + }} + styles={{ + // Column names differ at the end, so clipping hides the part + // that tells them apart. + option: { + whiteSpace: 'normal', + overflowWrap: 'anywhere', + lineHeight: 1.4, + }, + }} style={{ flex: 1 }} data-testid="search-columns-add-input" /> From 2d920b570b92f7029325ed8d13a76251e11c5f54 Mon Sep 17 00:00:00 2001 From: Elizabet Oliveira Date: Mon, 23 Nov 2026 17:26:10 +0000 Subject: [PATCH 21/21] fix(app): ask before discarding an unsaved column edit The inline column edit only reached the popover draft on blur, but the click-outside check runs on mousedown, before blur. A click outside the popover during an edit therefore closed it with no prompt. Unadded search text had the same gap. The edit now lives in ColumnsPopover, so an edit with a changed value and search text not yet added count as unsaved. Escape in the edit field still cancels only that edit, as before. Escape while the suggestion list is open also prompted once search text counted as unsaved. The list is a sibling of its input, so the Escape check missed it. The check now also looks for an open listbox in the same popover. --- .../SearchResultsToolbar/ClausePopover.tsx | 8 +++ .../SearchResultsToolbar/ColumnsPopover.tsx | 36 ++++++++++++-- .../SearchResultsToolbar/SortableColumn.tsx | 45 ++++++++--------- .../__tests__/ColumnsPopover.test.tsx | 49 +++++++++++++++++-- 4 files changed, 109 insertions(+), 29 deletions(-) diff --git a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx index 1e20f2e68b..5cacf767ea 100644 --- a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx @@ -64,6 +64,14 @@ const nestedListHandlesEscape = (target: EventTarget | null) => { ) != null ) return true; + // An Autocomplete list is a sibling of its input, not an ancestor, so the + // checks above miss it. Its listbox is only mounted while it is open. + if ( + target + .closest('[data-testid$="-popover"]') + ?.querySelector('[role="listbox"]') != null + ) + return true; const editor = target.closest('.cm-editor'); if (!(editor instanceof HTMLElement)) return false; if (editor.querySelector('.cm-tooltip-autocomplete') != null) return true; diff --git a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx index 0d2429ae9a..7495a41f79 100644 --- a/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ColumnsPopover.tsx @@ -63,6 +63,11 @@ export function ColumnsPopover({ }) { const [draft, setDraft] = useState(value); const [search, setSearch] = useState(''); + // The row being edited in place. Kept here so the popover can see it as an + // unsaved change before a click outside reads `dirty`. + const [edit, setEdit] = useState<{ index: number; text: string } | null>( + null, + ); // Autocomplete writes the chosen option back into the input after // onOptionSubmit. Ignore that write so the field clears. const ignoreNextChangeRef = useRef(false); @@ -94,10 +99,22 @@ export function ColumnsPopover({ setDraft(items.filter((_, i) => i !== index).join(', ')); }; - const updateColumn = (index: number, next: string) => { - setDraft(items.map((item, i) => (i === index ? next : item)).join(', ')); + const finishEdit = (index: number, next: string | null) => { + setEdit(null); + const trimmed = next?.trim() ?? ''; + // An empty value reverts, so a column is not removed by accident. + if (trimmed && trimmed !== items[index]) { + setDraft( + items.map((item, i) => (i === index ? trimmed : item)).join(', '), + ); + } }; + const pendingEdit = + edit != null && + edit.text.trim() !== '' && + edit.text.trim() !== items[edit.index]; + const columnIds = items.map(columnId); const sensors = useSensors( useSensor(MouseSensor, { activationConstraint: { distance: 8 } }), @@ -124,18 +141,26 @@ export function ColumnsPopover({ title={value || defaultValue} initialMode="pick" onOpen={() => { + setEdit(null); // 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={() => { + setEdit(null); setDraft(defaultValue); setSearch(''); }} resetDisabled={clauseResetDisabled(draft, defaultValue)} applyDisabled={clauseApplyDisabled(draft)} - dirty={clauseDirty(draft, value, defaultValue)} + // A column edit or search text not yet added is unsaved too. A click + // outside reads `dirty` before the edit's blur has committed it. + dirty={ + clauseDirty(draft, value, defaultValue) || + pendingEdit || + search.trim() !== '' + } onApply={() => { const submitted = storedClause(draft, value, defaultValue); const next = storedColumns(submitted); @@ -165,7 +190,10 @@ export function ColumnsPopover({ id={columnId(item, index)} label={item} onRemove={() => removeColumn(index)} - onEdit={next => updateColumn(index, next)} + editText={edit?.index === index ? edit.text : null} + onStartEdit={() => setEdit({ index, text: item })} + onChangeEdit={text => setEdit({ index, text })} + onFinishEdit={next => finishEdit(index, next)} /> ))} diff --git a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx index 24ce8bb10f..752968ab22 100644 --- a/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx +++ b/packages/app/src/components/SearchResultsToolbar/SortableColumn.tsx @@ -1,4 +1,4 @@ -import { useRef, useState } from 'react'; +import { useRef } from 'react'; import { useSortable } from '@dnd-kit/sortable'; import { CSS } from '@dnd-kit/utilities'; import { ActionIcon, Box, Group, Text, Textarea } from '@mantine/core'; @@ -8,13 +8,20 @@ export function SortableColumn({ id, label, onRemove, - onEdit, + editText, + onStartEdit, + onChangeEdit, + onFinishEdit, }: { id: string; label: string; onRemove: () => void; - /** Called with the trimmed expression when an edit changes the column. */ - onEdit?: (next: string) => void; + /** The text being edited, or null when this row is not being edited. */ + editText: string | null; + onStartEdit: () => void; + onChangeEdit: (text: string) => void; + /** Receives the edited text to keep, or null to cancel the edit. */ + onFinishEdit: (next: string | null) => void; }) { const { attributes, @@ -25,26 +32,20 @@ export function SortableColumn({ isDragging, } = useSortable({ id }); - const [editing, setEditing] = useState(false); - const [draft, setDraft] = useState(label); + const editing = editText != null; // Enter and Escape unmount the input, which can fire blur. Without this the - // edit would be committed (or discarded) a second time. + // edit would be finished a second time. const finishedRef = useRef(false); const startEdit = () => { - if (!onEdit) return; finishedRef.current = false; - setDraft(label); - setEditing(true); + onStartEdit(); }; - const finishEdit = (commit: boolean) => { + const finishEdit = (next: string | null) => { if (finishedRef.current) return; finishedRef.current = true; - setEditing(false); - const next = draft.trim(); - // An empty value reverts, so a column is not removed by accident. - if (commit && next && next !== label) onEdit?.(next); + onFinishEdit(next); }; return ( @@ -82,26 +83,26 @@ export function SortableColumn({