From 01f863c47f51467916a848cc4bf06033a32f6ba9 Mon Sep 17 00:00:00 2001 From: Galen Kistler <109082771+gtk-grafana@users.noreply.github.com> Date: Fri, 25 Jul 2025 16:43:36 -0500 Subject: [PATCH] TableNG: Take nanos into account for column sorting (#108614) * feat(ngTable): support nanos --------- Co-authored-by: Leon Sorokin --- .../components/Table/TableNG/utils.test.ts | 38 +++++++++++++++++++ .../src/components/Table/TableNG/utils.ts | 15 ++++++++ 2 files changed, 53 insertions(+) diff --git a/packages/grafana-ui/src/components/Table/TableNG/utils.test.ts b/packages/grafana-ui/src/components/Table/TableNG/utils.test.ts index 9f48dba7b42..f7bfcf2cc9d 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/utils.test.ts +++ b/packages/grafana-ui/src/components/Table/TableNG/utils.test.ts @@ -1,3 +1,5 @@ +import { SortColumn } from 'react-data-grid'; + import { createDataFrame, createTheme, @@ -30,6 +32,7 @@ import { migrateTableDisplayModeToCellOptions, getColumnTypes, getMaxWrapCell, + applySort, } from './utils'; describe('TableNG utils', () => { @@ -1084,4 +1087,39 @@ describe('TableNG utils', () => { it.todo('should only apply wrapping on idiomatic break characters (space, -, etc)'); }); + + describe('applySort', () => { + it('sorts by nanos', () => { + const frame = createDataFrame({ + fields: [ + { name: 'time', values: [1, 1, 2], nanos: [100, 99, 0] }, + { name: 'value', values: [10, 20, 30] }, + ], + }); + + const sortColumns: SortColumn[] = [ + { + columnKey: 'time', + direction: 'ASC', + }, + ]; + + const records = applySort(frameToRecords(frame), frame.fields, sortColumns); + + expect(records).toMatchObject([ + { + time: 1, + value: 20, + }, + { + time: 1, + value: 10, + }, + { + time: 2, + value: 30, + }, + ]); + }); + }); }); diff --git a/packages/grafana-ui/src/components/Table/TableNG/utils.ts b/packages/grafana-ui/src/components/Table/TableNG/utils.ts index 7ba9cabf855..67f4bf497ed 100644 --- a/packages/grafana-ui/src/components/Table/TableNG/utils.ts +++ b/packages/grafana-ui/src/components/Table/TableNG/utils.ts @@ -342,18 +342,33 @@ export function applySort( return rows; } + const sortNanos = sortColumns.map( + (c) => fields.find((f) => f.type === FieldType.time && getDisplayName(f) === c.columnKey)?.nanos + ); + const compareRows = (a: TableRow, b: TableRow): number => { let result = 0; + for (let i = 0; i < sortColumns.length; i++) { const { columnKey, direction } = sortColumns[i]; const compare = getComparator(columnTypes[columnKey]); const sortDir = direction === 'ASC' ? 1 : -1; result = sortDir * compare(a[columnKey], b[columnKey]); + + if (result === 0) { + const nanos = sortNanos[i]; + + if (nanos !== undefined) { + result = sortDir * (nanos[a.__index] - nanos[b.__index]); + } + } + if (result !== 0) { break; } } + return result; };