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/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 5c53b3f1ee..86cddca461 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -9266,11 +9266,13 @@ describe('External API v2 Dashboards - new format', () => { ['a SQL filter over a Metric source', () => adhocFilter(), 'metric'], ['a PromQL filter over a Trace source', promqlAdhocFilter, 'trace'], ] as const)('rejects %s', async (_label, makeFilter, kind) => { - const sourceId = { - promql: promqlSource, - metric: metricSource, - trace: traceSource, - }[kind]._id.toString(); + const source = + kind === 'promql' + ? promqlSource + : kind === 'metric' + ? metricSource + : traceSource; + const sourceId = source._id.toString(); const response = await authRequest('post', BASE_URL) .send( createMockDashboard(traceSource._id.toString(), { diff --git a/packages/api/src/utils/__tests__/filterSources.test.ts b/packages/api/src/utils/__tests__/filterSources.test.ts index b89b06d35b..2f0ae1445c 100644 --- a/packages/api/src/utils/__tests__/filterSources.test.ts +++ b/packages/api/src/utils/__tests__/filterSources.test.ts @@ -103,10 +103,7 @@ describe('getChangedFilterSourceRefs', () => { it('checks a filter without an ID, or with a new one', () => { const { id: _id, ...withoutId } = adhoc(); expect( - getChangedFilterSourceRefs( - [withoutId as DashboardFilter, adhoc({ id: 'new' })], - [adhoc()], - ), + getChangedFilterSourceRefs([withoutId, adhoc({ id: 'new' })], [adhoc()]), ).toEqual([ { id: 'logs', kinds: sql }, { id: 'logs', kinds: sql }, diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 0710231e52..52faf92b57 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -123,10 +123,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'; @@ -153,8 +155,10 @@ import { TimeZoneOverrideProvider } from '@/timeZoneOverride'; import { formatDurationMs, orderByAfterRemovingSelectItem, + orderByAfterRemovingSelectItems, QUERY_LOCAL_STORAGE, selectItemExpression, + selectItemsWithRemovedAlias, useLocalStorage, usePrevious, withMapKeyAlias, @@ -545,8 +549,19 @@ function SaveSearchModalComponent({ id: searchedConfig.source, kinds: [SourceKind.Log, SourceKind.Trace], }); + // An empty SELECT or sort means the saved clause when one is loaded, else the + // source default, as the results table reads it. Save what the table runs. + const savedClauses = + savedSearch != null && savedSearch.source === searchedConfig.source + ? savedSearch + : undefined; const effectiveSelect = - searchedConfig.select || sourceObj?.defaultTableSelectExpression || ''; + searchedConfig.select || + savedClauses?.select || + sourceObj?.defaultTableSelectExpression || + ''; + const effectiveOrderBy = + searchedConfig.orderBy || savedClauses?.orderBy || ''; const onSubmit = (e: FormEvent) => { e.preventDefault(); @@ -566,7 +581,7 @@ function SaveSearchModalComponent({ whereLanguage: searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene', source: searchedConfig.source ?? '', - orderBy: searchedConfig.orderBy ?? '', + orderBy: effectiveOrderBy, filters: searchedConfig.filters ?? [], tags: tags, }, @@ -594,7 +609,7 @@ function SaveSearchModalComponent({ whereLanguage: searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene', source: searchedConfig.source ?? '', - orderBy: searchedConfig.orderBy ?? '', + orderBy: effectiveOrderBy, filters: searchedConfig.filters ?? [], tags: tags, }); @@ -1205,9 +1220,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 @@ -1991,6 +2003,7 @@ function DBSearchPageContent() { selected, orderBy, defaultSearchConfig.orderBy ?? '', + defaultOrderBy ?? '', ); if (nextOrderBy !== orderBy) { setValue('orderBy', nextOrderBy); @@ -2004,6 +2017,7 @@ function DBSearchPageContent() { setValue, getValues, defaultSearchConfig.orderBy, + defaultOrderBy, onSubmit, ], ); @@ -2355,6 +2369,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); @@ -2492,51 +2515,100 @@ function DBSearchPageContent() { [setValue, setNewSourceModalClosed], ); - const columnFields = (allowMultiline: boolean, stacked: boolean) => { - const select = ( - - ); - const orderBy = ( - - ); - if (stacked) { - return ( - <> - {select} - {orderBy} - + // The dropdown source can move before the URL source does. An empty SELECT + // is shown as this default, so it has to follow the dropdown, the same way + // the sort default follows useDefaultOrderBy(inputSource). + const savedSelect = + savedSearchId && + savedSearch?.id === savedSearchId && + inputSource === savedSearch.source + ? savedSearch.select + : undefined; + const sourceDefaultSelect = + inputSourceObj?.kind === SourceKind.Log || + inputSourceObj?.kind === SourceKind.Trace + ? inputSourceObj.defaultTableSelectExpression + : undefined; + const defaultSelect = savedSelect ?? sourceDefaultSelect ?? ''; + + const applySelect = useCallback( + (select: string, removedItems: string[]) => { + setValue('select', select); + setValue( + 'orderBy', + orderByAfterRemovingSelectItems( + // An empty SELECT means the default, so keep the sorts on aliases + // that default still defines. + selectItemsWithRemovedAlias(removedItems, select || defaultSelect), + getValues('orderBy') ?? '', + defaultSearchConfig.orderBy ?? '', + defaultOrderBy ?? '', + ), ); - } - return ( - <> - {select} - {orderBy} - - ); - }; + onSubmit(); + }, + [ + setValue, + getValues, + defaultSearchConfig.orderBy, + defaultOrderBy, + defaultSelect, + 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. Memoized so a where + // keystroke, which re-renders this page, does not hand the results table a + // new element and defeat its memo. + const resultsClauseEditors = useMemo( + () => + analysisMode === 'results' ? ( + + + + + ) : null, + [ + analysisMode, + inputSelect, + defaultSelect, + clauseFieldOptions, + knownColumns, + applySelect, + inputSourceTableConnection, + inputSource, + searchedTimeRange, + inputOrderBy, + defaultSearchConfig.orderBy, + applyOrderBy, + ], + ); return ( - setIsSourceSchemaPreviewOpen(false)} - /> - {!isCompact && columnFields(true, false)} - <> + {!savedSearchId ? ( @@ -2724,7 +2790,6 @@ function DBSearchPageContent() { onClick={() => { setSaveSearchModalState('update'); }} - style={{ flexShrink: 0 }} > Update @@ -2735,7 +2800,6 @@ function DBSearchPageContent() { variant="secondary" size="xs" onClick={openAlertModal} - style={{ flexShrink: 0 }} > Alerts @@ -2743,74 +2807,53 @@ function DBSearchPageContent() { )} - {isCompact && ( - - )} - + - {isCompact && columnsOpen && ( - - {columnFields(false, true)} - - )} - - - + + + - + + + {isLive && ( @@ -2834,6 +2877,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 && ( @@ -3277,6 +3348,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 37e1f1774d..bd1b703a7b 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/__tests__/DBSearchPage.saveSearch.test.tsx b/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx index 864c55d9f4..49835bd421 100644 --- a/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx +++ b/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx @@ -11,9 +11,11 @@ const mockSetSearchedConfig = jest .fn() .mockResolvedValue(new URLSearchParams()); const mockCreateSavedSearch = jest.fn(); +const mockUpdateSavedSearch = jest.fn(); let mockSearchedConfig: Record = {}; let mockSources: any[] = []; +let mockSavedSearch: Record | undefined; jest.mock('@/layout', () => ({ withAppNav: (component: unknown) => component, @@ -98,8 +100,11 @@ jest.mock('@/savedSearch', () => ({ isPending: false, }), useDeleteSavedSearch: () => ({ mutate: jest.fn() }), - useSavedSearch: () => ({ data: undefined }), - useUpdateSavedSearch: () => ({ mutate: jest.fn(), isPending: false }), + useSavedSearch: () => ({ data: mockSavedSearch }), + useUpdateSavedSearch: () => ({ + mutate: (...args: unknown[]) => mockUpdateSavedSearch(...args), + isPending: false, + }), })); jest.mock('@/searchFilters', () => ({ @@ -232,10 +237,21 @@ jest.mock('@tanstack/react-query', () => ({ useIsFetching: () => 0, })); +// The page loads column options for the Columns popover. This suite is about +// saving a search, and its React Query mock does not cover that lookup. +jest.mock('@/components/SearchResultsToolbar/useClauseFieldOptions', () => ({ + useClauseFieldOptions: () => [], +})); + +jest.mock('@/useConfirm', () => ({ + useConfirm: () => jest.fn(), +})); + describe('DBSearchPage save search flow', () => { beforeEach(() => { jest.clearAllMocks(); mockCreateSavedSearch.mockResolvedValue({ id: 'new-saved-search' }); + mockSavedSearch = undefined; mockSearchedConfig = { source: 'log-source', where: 'level:error', @@ -284,6 +300,50 @@ describe('DBSearchPage save search flow', () => { }); }); + it('keeps a saved search clause when Update follows a blank Apply', async () => { + window.history.pushState( + {}, + '', + '/search/saved-1?from=100&to=200&isLive=false', + ); + mockSavedSearch = { + id: 'saved-1', + name: 'Errors', + source: 'log-source', + select: 'Body', + where: 'level:error', + whereLanguage: 'lucene', + orderBy: 'Body DESC', + filters: [], + tags: [], + }; + // Apply stores "" when the draft matches the default, which on a saved + // search is its own clause. + mockSearchedConfig = { + ...mockSearchedConfig, + select: '', + orderBy: '', + }; + const user = userEvent.setup(); + render(, { + wrapper: ({ children }) => {children}, + }); + + await user.click(await screen.findByTestId('update-search-button')); + await user.click(await screen.findByTestId('save-search-submit-button')); + + await waitFor(() => { + expect(mockUpdateSavedSearch).toHaveBeenCalledWith( + expect.objectContaining({ + id: 'saved-1', + select: 'Body', + orderBy: 'Body DESC', + }), + expect.anything(), + ); + }); + }); + it('drains queued query-string updates before navigating', async () => { await saveSearchAs('Errors'); diff --git a/packages/app/src/__tests__/searchFilters.test.ts b/packages/app/src/__tests__/searchFilters.test.ts index 798a4fed23..2036379ff5 100644 --- a/packages/app/src/__tests__/searchFilters.test.ts +++ b/packages/app/src/__tests__/searchFilters.test.ts @@ -12,6 +12,23 @@ enableMapSet(); type ConditionFilter = { type: 'sql' | 'lucene'; condition: string }; +function filterConditions(value: unknown): string[] { + if (!Array.isArray(value)) { + throw new Error('expected a filter list'); + } + return value.map(filter => { + if ( + typeof filter !== 'object' || + filter == null || + !('condition' in filter) || + typeof filter.condition !== 'string' + ) { + throw new Error('expected a condition filter'); + } + return filter.condition; + }); +} + describe('searchFilters', () => { describe('parseQuery', () => { it('empty query', () => { @@ -1013,9 +1030,7 @@ describe('searchFilters', () => { result.current.setFilterValue('source_name', 'EMAIL_SERVICE'); }); - const conditions = ( - onFilterChange.mock.lastCall![0] as ConditionFilter[] - ).map(f => f.condition); + const conditions = filterConditions(onFilterChange.mock.lastCall?.[0]); // Re-persisting must not rewrite the existing key into Map bracket form // (`message['email']`), which ClickHouse rejects for a JSON column. expect(conditions).toContain( @@ -1041,9 +1056,7 @@ describe('searchFilters', () => { result.current.setFilterValue('source_name', 'EMAIL_SERVICE'); }); - const conditions = ( - onFilterChange.mock.lastCall![0] as ConditionFilter[] - ).map(f => f.condition); + const conditions = filterConditions(onFilterChange.mock.lastCall?.[0]); expect(conditions).toContain(arrayPathCondition); }); diff --git a/packages/app/src/__tests__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts index 64a8d3e08d..a75a320c9f 100644 --- a/packages/app/src/__tests__/utils.test.ts +++ b/packages/app/src/__tests__/utils.test.ts @@ -26,9 +26,11 @@ import { mapKeyBy, mergePath, orderByAfterRemovingSelectItem, + orderByAfterRemovingSelectItems, orderByStringToSortingState, parseTimestampToMs, resolveConditionalColor, + selectItemsWithRemovedAlias, sortingStateToOrderByString, stripTrailingSlash, useQueryHistory, @@ -1616,6 +1618,129 @@ describe('orderByAfterRemovingSelectItem', () => { ).toBe('"http.method" DESC'); }); + it('drops a sort on an alias written without quotes', () => { + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + 'message DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + '`message` ASC, Timestamp DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + }); + + it('keeps a sort when the alias is still in the new SELECT', () => { + expect( + selectItemsWithRemovedAlias( + ['upper(Body) AS message'], + 'lower(Body) AS message', + ), + ).toEqual([]); + expect( + selectItemsWithRemovedAlias( + ['upper(Body) as message'], + 'upper(Body) AS message', + ), + ).toEqual([]); + expect( + selectItemsWithRemovedAlias( + ['upper(Body) AS message'], + 'lower(Body) AS "message"', + ), + ).toEqual([]); + expect( + orderByAfterRemovingSelectItems( + selectItemsWithRemovedAlias( + ['upper(Body) AS message'], + 'lower(Body) AS message', + ), + 'message DESC', + 'Timestamp DESC', + ), + ).toBe('message DESC'); + expect( + selectItemsWithRemovedAlias( + ['upper(Body) AS message', 'Body'], + 'lower(Body) AS note', + ), + ).toEqual(['upper(Body) AS message', 'Body']); + }); + + it('keeps a sort on an alias the default SELECT still defines after Reset', () => { + const defaultSelect = 'upper(Body) AS message, Timestamp'; + expect( + orderByAfterRemovingSelectItems( + selectItemsWithRemovedAlias(['lower(Body) AS message'], defaultSelect), + 'message DESC', + '', + 'Timestamp DESC', + ), + ).toBe('message DESC'); + }); + + it('does not restore a saved sort that still names the removed alias', () => { + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + 'message DESC', + 'message DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + 'message DESC', + 'message DESC, ServiceName ASC', + 'Timestamp DESC', + ), + ).toBe('ServiceName ASC'); + }); + + it('strips a saved sort when the form sort is empty', () => { + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + '', + 'message DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + '', + 'message DESC, ServiceName ASC', + 'Timestamp DESC', + ), + ).toBe('ServiceName ASC'); + expect( + orderByAfterRemovingSelectItem( + 'upper(Body) AS message', + '', + 'Timestamp DESC', + 'ServiceName ASC', + ), + ).toBe(''); + }); + + it('strips every removed alias from the saved sort at once', () => { + expect( + orderByAfterRemovingSelectItems( + ['upper(Body) AS message', 'lower(ServiceName) AS service'], + 'message DESC', + 'message DESC, service DESC', + 'Timestamp DESC', + ), + ).toBe('Timestamp DESC'); + }); + it('keeps a comma inside a backtick-quoted sort name', () => { expect( orderByAfterRemovingSelectItem( diff --git a/packages/app/src/components/DBRowTable.tsx b/packages/app/src/components/DBRowTable.tsx index 10e3904b7a..ceb202524d 100644 --- a/packages/app/src/components/DBRowTable.tsx +++ b/packages/app/src/components/DBRowTable.tsx @@ -37,13 +37,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, @@ -394,6 +394,8 @@ export const RawLogTable = memo( rowActions, variant = 'default', onRemoveColumn, + toolbarLeading, + controlsAboveTable = false, }: { wrapLines?: boolean; displayedColumns: string[]; @@ -439,6 +441,10 @@ export const RawLogTable = memo( rowActions?: (row: Record) => React.ReactNode; 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(); @@ -1039,8 +1045,111 @@ 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 } /> ); @@ -1768,6 +1797,8 @@ function DBSqlRowTableComponent({ tableId, errorVariant, onResolvedColumnsChange, + toolbarLeading, + controlsAboveTable, }: { config: BuilderChartConfigWithDateRange; sourceId?: string; @@ -1801,6 +1832,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 } = @@ -2049,6 +2082,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/src/components/SearchResultsToolbar/ClausePopover.tsx b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx index 0c7450e259..e36dc26d80 100644 --- a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx @@ -1,7 +1,10 @@ -import { type ReactNode, useState } from 'react'; +import { type ReactNode, useRef, useState } from 'react'; +import { completionStatus } from '@codemirror/autocomplete'; +import { EditorView } from '@codemirror/view'; import { Button, Group, Popover, SegmentedControl, Stack } from '@mantine/core'; import { SplitValueButton } from '@/components/SplitValueButton/SplitValueButton'; +import { useConfirm } from '@/useConfirm'; export type ClauseMode = 'pick' | 'sql'; @@ -28,14 +31,47 @@ export const clauseResetDisabled = matchesDefault; export const clauseApplyDisabled = (draft: string) => draft.trim() === ''; +// Wide enough for the column list on a desktop, narrow enough to stay on a +// phone. The button sits to the right of the nav rail, so a fixed width runs +// off the right edge and clips Apply. +const POPOVER_MAX_WIDTH = 440; + +/** + * The draft differs from the clause the editor opened with. Apply stores a + * matching default as "", so comparing against that form treats an untouched + * saved search, whose stored clause already equals the default, as dirty. + */ +export const clauseDirty = ( + draft: string, + value: string, + defaultValue: string, +) => draft.trim() !== (value || defaultValue).trim(); + const MODE_OPTIONS = [ { label: 'Fields', value: 'pick' }, { label: 'SQL', value: 'sql' }, ]; +// CodeMirror and the Fields autocomplete both close their own list on Escape, +// but the popover sees the key first. Let that Escape through while a list is +// open, so it does not close the popover or discard a draft. +const nestedListHandlesEscape = (target: EventTarget | null) => { + if (!(target instanceof Element)) return false; + if ( + target.closest('[aria-expanded="true"], [data-combobox-dropdown]') != null + ) + return true; + const editor = target.closest('.cm-editor'); + if (!(editor instanceof HTMLElement)) return false; + if (editor.querySelector('.cm-tooltip-autocomplete') != null) return true; + const view = EditorView.findFromDOM(editor); + return view != null && completionStatus(view.state) != null; +}; + /** * A toolbar button that edits one query clause in a popover. Edits stay in a - * draft owned by the caller until Apply, so closing the popover discards them. + * draft owned by the caller until Apply. Closing with unsaved edits asks + * first. Cancel discards them without asking. */ export function ClausePopover({ name, @@ -44,6 +80,7 @@ export function ClausePopover({ dimmed, title, initialMode, + dirty, onOpen, onApply, onReset, @@ -65,6 +102,8 @@ export function ClausePopover({ title: string; /** The tab to show each time the popover opens. */ initialMode: ClauseMode; + /** The draft would change the stored clause, so closing asks first. */ + dirty: boolean; /** Reset the caller's draft to the current value. */ onOpen: () => void; onApply: () => void; @@ -77,8 +116,12 @@ export function ClausePopover({ renderSql: (apply: () => void) => ReactNode; 'data-testid': string; }) { + const confirm = useConfirm(); const [opened, setOpened] = useState(false); const [mode, setMode] = useState(initialMode); + // The confirm dialog sits outside this popover, so its own clicks look like + // another dismiss. Ignore those while it is open. + const confirmingRef = useRef(false); const open = () => { onOpen(); @@ -86,6 +129,21 @@ export function ClausePopover({ setOpened(true); }; + const requestClose = () => { + if (confirmingRef.current) return; + if (!dirty) { + setOpened(false); + return; + } + confirmingRef.current = true; + void confirm('Discard unsaved changes?', 'Discard', { + variant: 'danger', + }).then(discard => { + confirmingRef.current = false; + if (discard) setOpened(false); + }); + }; + const apply = () => { if (applyDisabled) return; onApply(); @@ -95,11 +153,35 @@ export function ClausePopover({ return ( { + if (!next) requestClose(); + }} position="bottom-start" - width={440} shadow="md" withinPortal + // Escape is handled below, so a completion list can take the key first. + closeOnEscape={false} + // Let shift move the dropdown past the button's edge, so a dropdown + // wider than the space to the right slides left instead of overflowing. + middlewares={{ + shift: { + padding: 8, + limiter: { + fn: ({ x, y }) => ({ x, y }), + }, + }, + size: { + padding: 8, + apply({ availableWidth, availableHeight, elements }) { + if (availableWidth > 0) { + elements.floating.style.maxWidth = `${availableWidth}px`; + } + if (availableHeight > 0) { + elements.floating.style.maxHeight = `${availableHeight}px`; + } + }, + }, + }} > (opened ? setOpened(false) : open())} + onClick={() => (opened ? requestClose() : open())} data-testid={testId} /> - + { + if (event.key !== 'Escape') return; + if (nestedListHandlesEscape(event.target)) return; + requestClose(); + }} + > {mode === 'pick' ? renderPick(apply) : renderSql(apply)} - + - +