Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/chart-table-edited-order-by.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/app': patch
---

fix: run an edited Order By on a chart table instead of the last column header sort
96 changes: 0 additions & 96 deletions packages/app/src/__tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
TLogSource,
TSource,
} from '@hyperdx/common-utils/dist/types';
import { SortingState } from '@tanstack/react-table';
import { act, renderHook } from '@testing-library/react';

import { MetricsDataType, NumberFormat } from '@/types';
Expand All @@ -29,10 +28,8 @@ import {
mapKeyBy,
mergePath,
orderByAfterRemovingSelectItem,
orderByStringToSortingState,
parseTimestampToMs,
resolveConditionalColor,
sortingStateToOrderByString,
stripTrailingSlash,
useQueryHistory,
withMapKeyAlias,
Expand Down Expand Up @@ -1209,99 +1206,6 @@ describe('useQueryHistory', () => {
});
});

describe('sortingStateToOrderByString', () => {
it('returns undefined for null input', () => {
expect(sortingStateToOrderByString(null)).toBeUndefined();
});

it('returns undefined for empty array', () => {
const sortingState: SortingState = [];
expect(sortingStateToOrderByString(sortingState)).toBeUndefined();
});

it('converts sorting state with desc: false to ASC order', () => {
const sortingState: SortingState = [{ id: 'timestamp', desc: false }];
expect(sortingStateToOrderByString(sortingState)).toBe('timestamp ASC');
});

it('converts sorting state with desc: true to DESC order', () => {
const sortingState: SortingState = [{ id: 'timestamp', desc: true }];
expect(sortingStateToOrderByString(sortingState)).toBe('timestamp DESC');
});

it('handles column names with special characters', () => {
const sortingState: SortingState = [{ id: 'user_count', desc: false }];
expect(sortingStateToOrderByString(sortingState)).toBe('user_count ASC');
});
});

describe('orderByStringToSortingState', () => {
it('returns undefined for undefined input', () => {
expect(orderByStringToSortingState(undefined)).toBeUndefined();
});

it('returns undefined for empty string', () => {
expect(orderByStringToSortingState('')).toBeUndefined();
});

it('converts "column ASC" to sorting state with desc: false', () => {
const result = orderByStringToSortingState('timestamp ASC');
expect(result).toEqual([{ id: 'timestamp', desc: false }]);
});

it('converts "column DESC" to sorting state with desc: true', () => {
const result = orderByStringToSortingState('timestamp DESC');
expect(result).toEqual([{ id: 'timestamp', desc: true }]);
});

it('handles case insensitive direction keywords', () => {
expect(orderByStringToSortingState('col asc')).toEqual([
{ id: 'col', desc: false },
]);
expect(orderByStringToSortingState('col Asc')).toEqual([
{ id: 'col', desc: false },
]);
expect(orderByStringToSortingState('col desc')).toEqual([
{ id: 'col', desc: true },
]);
expect(orderByStringToSortingState('col Desc')).toEqual([
{ id: 'col', desc: true },
]);
expect(orderByStringToSortingState('col DESC')).toEqual([
{ id: 'col', desc: true },
]);
});

it('returns undefined for invalid format without direction', () => {
expect(orderByStringToSortingState('timestamp')).toBeUndefined();
});

it('returns undefined for invalid format with wrong number of parts', () => {
expect(orderByStringToSortingState('col name ASC')).toBeUndefined();
});

it('returns undefined for invalid direction keyword', () => {
expect(orderByStringToSortingState('col INVALID')).toBeUndefined();
});

it('handles column names with underscores', () => {
const result = orderByStringToSortingState('user_count DESC');
expect(result).toEqual([{ id: 'user_count', desc: true }]);
});

it('handles column names with numbers', () => {
const result = orderByStringToSortingState('col123 ASC');
expect(result).toEqual([{ id: 'col123', desc: false }]);
});

it('round-trips correctly with sortingStateToOrderByString', () => {
const originalSort: SortingState = [{ id: 'service_name', desc: true }];
const orderByString = sortingStateToOrderByString(originalSort);
const roundTripSort = orderByStringToSortingState(orderByString);
expect(roundTripSort).toEqual(originalSort);
});
});

describe('mapKeyBy', () => {
it('returns a map', () => {
const result = mapKeyBy([{ id: 'a' }, { id: 'b' }], 'id');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,16 +48,14 @@ import {
isSingleExpression,
useSource,
} from '@/source';
import {
orderByStringToSortingState,
sortingStateToOrderByString,
} from '@/utils';

import { QueryPreviewAccordion } from './QueryPreviewAccordion';
import {
buildRenderedPromqlExpression,
buildSampleEventsConfig,
isQueryReady,
orderByToTableSortState,
tableSortStateToOrderBy,
tabQueriesData,
} from './utils';

Expand Down Expand Up @@ -228,7 +226,7 @@ export function ChartPreviewPanel({

const onTableSortingChange = useCallback(
(sortState: SortingState | null) => {
setValue('orderBy', sortingStateToOrderByString(sortState) ?? '');
setValue('orderBy', tableSortStateToOrderBy(sortState));
onSubmit();
},
[setValue, onSubmit],
Expand All @@ -240,8 +238,8 @@ export function ChartPreviewPanel({
isBuilderChartConfig(queriedConfig) &&
queriedConfig.orderBy &&
typeof queriedConfig.orderBy === 'string'
? orderByStringToSortingState(queriedConfig.orderBy)
: undefined,
? orderByToTableSortState(queriedConfig.orderBy)
: [],
[queriedConfig],
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,11 @@ import {
displayTypeToActiveTab,
getPreviewBlockingFilters,
isQueryReady,
orderByToTableSortState,
resolvePreviewVariables,
resolveTilePreviewFilters,
seriesToFilters,
tableSortStateToOrderBy,
tabQueriesData,
TABS_WITH_GENERATED_SQL,
withBroadcastFilters,
Expand Down Expand Up @@ -1353,3 +1355,49 @@ describe('buildGroupByConnectionProps', () => {
expect(result).toEqual({ tableConnection });
});
});

describe('table sort state <-> Order By', () => {
it.each([
['"duration min" ASC', { id: '"duration min"', desc: false }],
[
'round(Duration / 1e6, 2) DESC',
{ id: 'round(Duration / 1e6, 2)', desc: true },
],
['Duration desc', { id: 'Duration', desc: true }],
[
'(TimestampTime, Timestamp) DESC',
{ id: '(TimestampTime, Timestamp)', desc: true },
],
['"a, b" ASC', { id: '"a, b"', desc: false }],
[
"arrayElement(Attributes, 'k') DESC",
{ id: "arrayElement(Attributes, 'k')", desc: true },
],
])('parses %s and serializes it back', (orderBy, expected) => {
const sort = orderByToTableSortState(orderBy);
expect(sort).toEqual([expected]);
expect(tableSortStateToOrderBy(sort)).toBe(
orderBy.replace(/desc$/, 'DESC'),
);
});

it.each([
'',
' ',
'Duration',
'(TimestampTime, Timestamp)',
'Duration DESC NULLS LAST',
'Timestamp DESC, ServiceName ASC',
'TimestampTime ASC, Timestamp DESC',
])(
'returns an empty sort for an Order By that is not a single key with a trailing direction (%p)',
orderBy => {
expect(orderByToTableSortState(orderBy)).toEqual([]);
},
);

it('serializes an empty or null sort as an empty Order By', () => {
expect(tableSortStateToOrderBy([])).toBe('');
expect(tableSortStateToOrderBy(null)).toBe('');
});
});
26 changes: 25 additions & 1 deletion packages/app/src/components/DBEditTimeChartForm/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ import {
displayTypeSupportsReducer,
getQueriedPromqlSeries,
} from '@hyperdx/common-utils/dist/core/promql';
import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils';
import {
isTimeSeriesDisplayType,
splitAndTrimWithBracket,
} from '@hyperdx/common-utils/dist/core/utils';
import {
configConsumesBroadcastFilters,
getBlockingRequiredFilters,
Expand Down Expand Up @@ -44,6 +47,7 @@ import {
validateAlertScheduleOffsetMinutes,
} from '@hyperdx/common-utils/dist/types';
import { filterReferencedVariables } from '@hyperdx/common-utils/dist/variables';
import type { SortingState } from '@tanstack/react-table';

import {
convertToCategoricalChartConfig,
Expand All @@ -66,6 +70,7 @@ import {
extendDateRangeToInterval,
intervalToGranularity,
} from '@/utils/alerts';
import { parseAsSortingStateString } from '@/utils/queryParsers';

export const isQueryReady = (
queriedConfig: ChartConfigWithDateRange | undefined,
Expand Down Expand Up @@ -610,3 +615,22 @@ export function buildGroupByConnectionProps({
? { tableConnections: connections, intersectFields: true }
: { tableConnection };
}

/**
* Sort state for the preview table's headers. An Order By that doesn't parse
* (no trailing direction, trailing modifiers, empty, more than one key) yields
* `[]` rather than `undefined`, so DBTableChart doesn't fall back to a stale
* header sort and the typed Order By is queried as written.
*/
export function orderByToTableSortState(orderBy: string): SortingState {
// The parser would read `a DESC, b ASC` as one key with the last direction,
// and pagination takes its time direction from that, not from `a DESC`.
if (splitAndTrimWithBracket(orderBy).length > 1) return [];
const sort = parseAsSortingStateString.parse(orderBy);
return sort ? [sort] : [];
}

export function tableSortStateToOrderBy(sort: SortingState | null): string {
const first = sort?.at(0);
return first ? parseAsSortingStateString.serialize(first) : '';
}
12 changes: 12 additions & 0 deletions packages/app/src/components/DBTableChart.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,18 @@ export default function DBTableChart({
}) {
const [sort, setSort] = useState<SortingState>([]);

// A header sort only overrides the Order By it was clicked against. Clear it
// when the config's own Order By changes (e.g. the tile was edited), so it
// can't come back if the Order By is later changed back.
const configOrderByKey = JSON.stringify(
isBuilderChartConfig(config) ? (config.orderBy ?? null) : null,
);
const [sortOrderByKey, setSortOrderByKey] = useState(configOrderByKey);
if (sortOrderByKey !== configOrderByKey) {
setSortOrderByKey(configOrderByKey);
setSort([]);
}

const { data: source } = useSource({
id: config.source,
});
Expand Down
69 changes: 69 additions & 0 deletions packages/app/src/components/__tests__/DBTableChart.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import React from 'react';
import { isBuilderChartConfig } from '@hyperdx/common-utils/dist/guards';
import { act } from '@testing-library/react';

import DateRangeIndicator from '@/components/charts/DateRangeIndicator';
import DBTableChart from '@/components/DBTableChart';
Expand Down Expand Up @@ -617,6 +619,73 @@ describe('DBTableChart', () => {
});
});

describe('header sort without a controlled sort prop', () => {
const queriedOrderBy = () => {
const config = jest.mocked(useOffsetPaginatedQuery).mock.calls.at(-1)![0];
return isBuilderChartConfig(config) ? config.orderBy : undefined;
};
const clickHeaderSort = () =>
act(() => {
jest
.mocked(Table)
.mock.calls.at(-1)![0]
.onSortingChange?.([{ id: 'ServiceName', desc: false }]);
});
const headerSortOrderBy = [
{ valueExpression: 'ServiceName', ordering: 'ASC' },
];

it('overrides the config Order By while it is unchanged', () => {
const config = { ...baseTestConfig, orderBy: 'Duration DESC' };
const { rerender } = renderWithMantine(<DBTableChart config={config} />);
clickHeaderSort();
expect(queriedOrderBy()).toEqual(headerSortOrderBy);

rerender(
<TestProviders>
<DBTableChart config={{ ...config }} />
</TestProviders>,
);
expect(queriedOrderBy()).toEqual(headerSortOrderBy);
});

it('is dropped when the config Order By changes', () => {
const { rerender } = renderWithMantine(
<DBTableChart
config={{ ...baseTestConfig, orderBy: 'Duration DESC' }}
/>,
);
clickHeaderSort();

rerender(
<TestProviders>
<DBTableChart
config={{ ...baseTestConfig, orderBy: 'ServiceName DESC' }}
/>
</TestProviders>,
);
expect(queriedOrderBy()).toBe('ServiceName DESC');
});

it('stays dropped when the config Order By changes back', () => {
const { rerender } = renderWithMantine(
<DBTableChart
config={{ ...baseTestConfig, orderBy: 'Duration DESC' }}
/>,
);
clickHeaderSort();

for (const orderBy of ['ServiceName DESC', 'Duration DESC']) {
rerender(
<TestProviders>
<DBTableChart config={{ ...baseTestConfig, orderBy }} />
</TestProviders>,
);
}
expect(queriedOrderBy()).toBe('Duration DESC');
});
});

it('does not render DateRangeIndicator when MV optimization has no optimized date range', () => {
// Mock useMVOptimizationExplanation to return data without an optimized config
jest.mocked(useMVOptimizationExplanation).mockReturnValue({
Expand Down
Loading
Loading