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 2a90cae9c6..afa66ebca6 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'; @@ -1144,9 +1146,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 @@ -2176,6 +2175,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); @@ -2313,51 +2321,73 @@ 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], + ); + + // 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 ?? ''; + + // 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 ? ( @@ -2545,7 +2569,6 @@ function DBSearchPageContent() { onClick={() => { setSaveSearchModalState('update'); }} - style={{ flexShrink: 0 }} > Update @@ -2556,7 +2579,6 @@ function DBSearchPageContent() { variant="secondary" size="xs" onClick={openAlertModal} - style={{ flexShrink: 0 }} > Alerts @@ -2564,74 +2586,53 @@ function DBSearchPageContent() { )} - {isCompact && ( - - )} - + - {isCompact && columnsOpen && ( - - {columnFields(false, true)} - - )} - - - + + + - + + + {isLive && ( @@ -2655,6 +2656,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 && ( @@ -3052,6 +3081,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__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts index ee74129dcd..5d53e5847c 100644 --- a/packages/app/src/__tests__/utils.test.ts +++ b/packages/app/src/__tests__/utils.test.ts @@ -1582,6 +1582,23 @@ 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 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 c20b1586ec..c914823428 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, @@ -393,6 +393,8 @@ export const RawLogTable = memo( getRowWhere, variant = 'default', onRemoveColumn, + toolbarLeading, + controlsAboveTable = false, }: { wrapLines?: boolean; displayedColumns: string[]; @@ -436,6 +438,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(); @@ -1036,8 +1042,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 } /> ); @@ -1760,6 +1789,8 @@ function DBSqlRowTableComponent({ tableId, errorVariant, onResolvedColumnsChange, + toolbarLeading, + controlsAboveTable, }: { config: BuilderChartConfigWithDateRange; sourceId?: string; @@ -1793,6 +1824,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 } = @@ -2041,6 +2074,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..d2050ad2c9 100644 --- a/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx +++ b/packages/app/src/components/SearchResultsToolbar/ClausePopover.tsx @@ -1,7 +1,8 @@ -import { type ReactNode, useState } from 'react'; +import { type ReactNode, useRef, useState } from 'react'; 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,6 +29,13 @@ export const clauseResetDisabled = matchesDefault; export const clauseApplyDisabled = (draft: string) => draft.trim() === ''; +/** Apply would write a different clause than the one currently stored. */ +export const clauseDirty = ( + draft: string, + value: string, + defaultValue: string, +) => storedClause(draft, value, defaultValue) !== value; + const MODE_OPTIONS = [ { label: 'Fields', value: 'pick' }, { label: 'SQL', value: 'sql' }, @@ -35,7 +43,8 @@ const MODE_OPTIONS = [ /** * 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 a draft that would change the + * stored clause asks first. Cancel discards it without asking. */ export function ClausePopover({ name, @@ -44,6 +53,7 @@ export function ClausePopover({ dimmed, title, initialMode, + dirty, onOpen, onApply, onReset, @@ -65,6 +75,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 +89,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 +102,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,7 +126,9 @@ export function ClausePopover({ return ( { + if (!next) requestClose(); + }} position="bottom-start" width={440} shadow="md" @@ -108,7 +141,7 @@ export function ClausePopover({ count={count} dimmed={dimmed} title={title} - onClick={() => (opened ? setOpened(false) : open())} + onClick={() => (opened ? requestClose() : open())} data-testid={testId} /> @@ -123,7 +156,21 @@ export function ClausePopover({ data-testid={`${testId}-mode`} /> {mode === 'pick' ? renderPick(apply) : renderSql(apply)} - +