From 92d736665acdec75efc0f489f58b1159e497c095 Mon Sep 17 00:00:00 2001 From: Dominik Prokop Date: Fri, 10 Sep 2021 13:05:34 +0200 Subject: [PATCH] TimeSrv: Do not update URL multiple times for same, consecutive range updates (#39083) --- .../dashboard/services/TimeSrv.test.ts | 21 ++++++++++++++++++- .../features/dashboard/services/TimeSrv.ts | 7 +++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/public/app/features/dashboard/services/TimeSrv.test.ts b/public/app/features/dashboard/services/TimeSrv.test.ts index bbb7f4c52d2..4838a8a2436 100644 --- a/public/app/features/dashboard/services/TimeSrv.test.ts +++ b/public/app/features/dashboard/services/TimeSrv.test.ts @@ -1,7 +1,7 @@ import { TimeSrv } from './TimeSrv'; import { ContextSrvStub } from 'test/specs/helpers'; import { isDateTime, dateTime } from '@grafana/data'; -import { locationService } from '@grafana/runtime'; +import { HistoryWrapper, locationService, setLocationService } from '@grafana/runtime'; jest.mock('app/core/core', () => ({ appEvents: { @@ -12,6 +12,7 @@ jest.mock('app/core/core', () => ({ describe('timeSrv', () => { let timeSrv: TimeSrv; let _dashboard: any; + const pushSpy = jest.fn(); beforeEach(() => { _dashboard = { @@ -22,6 +23,17 @@ describe('timeSrv', () => { }; timeSrv = new TimeSrv(new ContextSrvStub() as any); timeSrv.init(_dashboard); + + beforeEach(() => { + pushSpy.mockClear(); + + setLocationService(new HistoryWrapper()); + const origPush = locationService.push; + locationService.push = (args: any) => { + pushSpy(); + origPush(args); + }; + }); }); describe('timeRange', () => { @@ -219,6 +231,13 @@ describe('timeSrv', () => { timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); expect(_dashboard.refresh).toBe('10s'); }); + + it('should update location only once for consecutive calls with the same range', () => { + timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); + timeSrv.setTime({ from: 'now-1h', to: 'now-10s' }); + + expect(pushSpy).toHaveBeenCalledTimes(1); + }); }); describe('pauseAutoRefresh', () => { diff --git a/public/app/features/dashboard/services/TimeSrv.ts b/public/app/features/dashboard/services/TimeSrv.ts index a33751f1f31..c493627855a 100644 --- a/public/app/features/dashboard/services/TimeSrv.ts +++ b/public/app/features/dashboard/services/TimeSrv.ts @@ -285,6 +285,13 @@ export class TimeSrv { const urlRange = this.timeRangeForUrl(); const urlParams = locationService.getSearch(); + const from = urlParams.get('from'); + const to = urlParams.get('to'); + + if (from && to && from === urlRange.from.toString() && to === urlRange.to.toString()) { + return; + } + urlParams.set('from', urlRange.from.toString()); urlParams.set('to', urlRange.to.toString());