grafana/data: Add time range zoom out util

This commit is contained in:
Dominik Prokop 2023-11-24 11:48:18 +01:00
parent 710248674d
commit bc1602db57
2 changed files with 43 additions and 3 deletions

View File

@ -1,8 +1,8 @@
import { RawTimeRange, TimeRange } from '../types/time';
import { timeRangeToRelative } from './rangeutil';
import { timeRangeToRelative, zoomOutTimeRange } from './rangeutil';
import { dateTime, rangeUtil } from './index';
import { dateTime, rangeUtil, toUtc } from './index';
describe('Range Utils', () => {
// These tests probably wrap the dateTimeParser tests to some extent
@ -275,4 +275,32 @@ describe('Range Utils', () => {
expect(relativeTimeRange.to).toEqual(604800);
});
});
describe('zoomOutTimeRange', () => {
it('calculates zoomed time range correctly', () => {
// 07:48:27 on Dec 17 - 07:48:27 on Dec 18
const from = dateTime('2023-12-17T07:48:27.433Z');
const to = dateTime('2023-12-18T07:48:27.433Z');
const timeRange = {
from,
to,
raw: { from, to },
};
// zoom out by 2
const zoomedTimeRange = zoomOutTimeRange(timeRange, 2);
// 19:48:27 on Dec 16 - 19:48:27 on Dec 18
const zoomedFrom = dateTime('2023-12-16T19:48:27.433Z').valueOf();
const zoomedTo = dateTime('2023-12-18T19:48:27.433Z').valueOf();
expect(zoomedTimeRange).toEqual({
from: toUtc(zoomedFrom),
to: toUtc(zoomedTo),
raw: {
from: toUtc(zoomedFrom),
to: toUtc(zoomedTo),
},
});
});
});
});

View File

@ -4,7 +4,7 @@ import { RawTimeRange, TimeRange, TimeZone, IntervalValues, RelativeTimeRange, T
import * as dateMath from './datemath';
import { timeZoneAbbrevation, dateTimeFormat, dateTimeFormatTimeAgo } from './formatter';
import { isDateTime, DateTime, dateTime } from './moment_wrapper';
import { isDateTime, DateTime, dateTime, toUtc } from './moment_wrapper';
import { dateTimeParse } from './parser';
const spans: { [key: string]: { display: string; section?: number } } = {
@ -469,3 +469,15 @@ export function relativeToTimeRange(relativeTimeRange: RelativeTimeRange, now: D
raw: { from, to },
};
}
export function zoomOutTimeRange(timeRange: TimeRange, factor: number): TimeRange {
const timespan = timeRange.to.valueOf() - timeRange.from.valueOf();
const center = timeRange.to.valueOf() - timespan / 2;
// If the timepsan is 0, zooming out would do nothing, so we force a zoom out to 30s
const newTimespan = timespan === 0 ? 30000 : timespan * factor;
const to = center + newTimespan / 2;
const from = center - newTimespan / 2;
return { from: toUtc(from), to: toUtc(to), raw: { from: toUtc(from), to: toUtc(to) } };
}