TimeSrv: Refactor service to have no dependency on angular (#32562)

* TimeSrv: Refactor service to have no dependency on angular

* Fixing reference to function that does not exist

* fixing tests

* Worked around the strange error
pull/32537/head^2
Torkel Ödegaard 5 years ago committed by GitHub
parent 1399b49c16
commit 6fa7c6b206
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 10
      packages/grafana-data/src/field/fieldOverrides.test.ts
  2. 6
      packages/grafana-data/src/utils/location.test.ts
  3. 19
      packages/grafana-data/src/utils/location.ts
  4. 7
      public/app/angular/AngularApp.ts
  5. 9
      public/app/app.ts
  6. 1
      public/app/features/all.ts
  7. 28
      public/app/features/dashboard/services/TimeSrv.test.ts
  8. 57
      public/app/features/dashboard/services/TimeSrv.ts
  9. 5
      public/app/features/dashboard/state/PanelModel.ts
  10. 3
      public/app/features/dashboard/state/actions.ts
  11. 4
      public/app/features/panel/panellinks/link_srv.ts
  12. 14
      public/app/features/panel/panellinks/specs/link_srv.test.ts
  13. 4
      public/app/features/templating/all.ts
  14. 2
      public/app/features/templating/template_srv.ts
  15. 12
      public/app/features/variables/getAllVariableValuesForUrl.test.ts
  16. 6
      public/app/features/variables/getAllVariableValuesForUrl.ts
  17. 5
      public/app/plugins/panel/heatmap/heatmap_ctrl.ts
  18. 13
      public/app/routes/GrafanaCtrl.ts

@ -67,10 +67,8 @@ export const customFieldRegistry: FieldConfigOptionsRegistry = new Registry<Fiel
locationUtil.initialize({ locationUtil.initialize({
config: { appSubUrl: '/subUrl' } as any, config: { appSubUrl: '/subUrl' } as any,
// @ts-ignore getVariablesUrlParams: (() => {}) as any,
buildParamsFromVariables: () => {}, getTimeRangeForUrl: (() => {}) as any,
// @ts-ignore
getTimeRangeForUrl: () => {},
}); });
describe('Global MinMax', () => { describe('Global MinMax', () => {
@ -528,7 +526,7 @@ describe('getLinksSupplier', () => {
it('will replace variables in url and title of the data link', () => { it('will replace variables in url and title of the data link', () => {
locationUtil.initialize({ locationUtil.initialize({
config: {} as any, config: {} as any,
buildParamsFromVariables: (() => {}) as any, getVariablesUrlParams: (() => {}) as any,
getTimeRangeForUrl: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any,
}); });
@ -572,7 +570,7 @@ describe('getLinksSupplier', () => {
it('handles internal links', () => { it('handles internal links', () => {
locationUtil.initialize({ locationUtil.initialize({
config: { appSubUrl: '' } as any, config: { appSubUrl: '' } as any,
buildParamsFromVariables: (() => {}) as any, getVariablesUrlParams: (() => {}) as any,
getTimeRangeForUrl: (() => {}) as any, getTimeRangeForUrl: (() => {}) as any,
}); });

@ -4,10 +4,8 @@ describe('locationUtil', () => {
beforeAll(() => { beforeAll(() => {
locationUtil.initialize({ locationUtil.initialize({
config: { appSubUrl: '/subUrl' } as any, config: { appSubUrl: '/subUrl' } as any,
// @ts-ignore getVariablesUrlParams: (() => {}) as any,
buildParamsFromVariables: () => {}, getTimeRangeForUrl: (() => {}) as any,
// @ts-ignore
getTimeRangeForUrl: () => {},
}); });
}); });

@ -1,10 +1,10 @@
import { GrafanaConfig, RawTimeRange, ScopedVars } from '../types'; import { GrafanaConfig, RawTimeRange, ScopedVars } from '../types';
import { urlUtil } from './url'; import { UrlQueryMap, urlUtil } from './url';
import { textUtil } from '../text'; import { textUtil } from '../text';
let grafanaConfig: GrafanaConfig = { appSubUrl: '' } as any; let grafanaConfig: GrafanaConfig = { appSubUrl: '' } as any;
let getTimeRangeUrlParams: () => RawTimeRange; let getTimeRangeUrlParams: () => RawTimeRange;
let getVariablesUrlParams: (params?: Record<string, any>, scopedVars?: ScopedVars) => string; let getVariablesUrlParams: (scopedVars?: ScopedVars) => UrlQueryMap;
/** /**
* *
@ -35,21 +35,21 @@ const assureBaseUrl = (url: string): string => {
interface LocationUtilDependencies { interface LocationUtilDependencies {
config: GrafanaConfig; config: GrafanaConfig;
getTimeRangeForUrl: () => RawTimeRange; getTimeRangeForUrl: () => RawTimeRange;
buildParamsFromVariables: (params: any, scopedVars?: ScopedVars) => string; getVariablesUrlParams: (scopedVars?: ScopedVars) => UrlQueryMap;
} }
export const locationUtil = { export const locationUtil = {
/** /**
* *
* @param getConfig * @param getConfig
* @param buildParamsFromVariables * @param getAllVariableValuesForUrl
* @param getTimeRangeForUrl * @param getTimeRangeForUrl
* @internal * @internal
*/ */
initialize: ({ config, buildParamsFromVariables, getTimeRangeForUrl }: LocationUtilDependencies) => { initialize: (dependencies: LocationUtilDependencies) => {
grafanaConfig = config; grafanaConfig = dependencies.config;
getTimeRangeUrlParams = getTimeRangeForUrl; getTimeRangeUrlParams = dependencies.getTimeRangeForUrl;
getVariablesUrlParams = buildParamsFromVariables; getVariablesUrlParams = dependencies.getVariablesUrlParams;
}, },
stripBaseFromUrl, stripBaseFromUrl,
assureBaseUrl, assureBaseUrl,
@ -63,8 +63,7 @@ export const locationUtil = {
if (!getVariablesUrlParams) { if (!getVariablesUrlParams) {
return null; return null;
} }
const params = {}; const params = getVariablesUrlParams(scopedVars);
getVariablesUrlParams(params, scopedVars);
return urlUtil.toUrlParams(params); return urlUtil.toUrlParams(params);
}, },
processUrl: (url: string) => { processUrl: (url: string) => {

@ -5,12 +5,14 @@ import 'angular-bindonce';
import 'vendor/bootstrap/bootstrap'; import 'vendor/bootstrap/bootstrap';
import 'vendor/angular-other/angular-strap'; import 'vendor/angular-other/angular-strap';
import { config } from 'app/core/config'; import { config } from 'app/core/config';
import { angularModules } from 'app/core/core_module'; import coreModule, { angularModules } from 'app/core/core_module';
import { DashboardLoaderSrv } from 'app/features/dashboard/services/DashboardLoaderSrv'; import { DashboardLoaderSrv } from 'app/features/dashboard/services/DashboardLoaderSrv';
import { registerAngularDirectives } from 'app/core/core'; import { registerAngularDirectives } from 'app/core/core';
import { initAngularRoutingBridge } from 'app/angular/bridgeReactAngularRouting'; import { initAngularRoutingBridge } from 'app/angular/bridgeReactAngularRouting';
import { monkeyPatchInjectorWithPreAssignedBindings } from 'app/core/injectorMonkeyPatch'; import { monkeyPatchInjectorWithPreAssignedBindings } from 'app/core/injectorMonkeyPatch';
import { extend } from 'lodash'; import { extend } from 'lodash';
import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { getTemplateSrv } from '@grafana/runtime';
export class AngularApp { export class AngularApp {
ngModuleDependencies: any[]; ngModuleDependencies: any[];
@ -83,6 +85,9 @@ export class AngularApp {
// register react angular wrappers // register react angular wrappers
angular.module('grafana.services').service('dashboardLoaderSrv', DashboardLoaderSrv); angular.module('grafana.services').service('dashboardLoaderSrv', DashboardLoaderSrv);
coreModule.factory('timeSrv', () => getTimeSrv());
coreModule.factory('templateSrv', () => getTemplateSrv());
registerAngularDirectives(); registerAngularDirectives();
initAngularRoutingBridge(); initAngularRoutingBridge();
} }

@ -13,6 +13,7 @@ import React from 'react';
import config from 'app/core/config'; import config from 'app/core/config';
// @ts-ignore ignoring this for now, otherwise we would have to extend _ interface with move // @ts-ignore ignoring this for now, otherwise we would have to extend _ interface with move
import { import {
locationUtil,
setLocale, setLocale,
setTimeZoneResolver, setTimeZoneResolver,
standardEditorsRegistry, standardEditorsRegistry,
@ -39,6 +40,8 @@ import { interceptLinkClicks } from './core/navigation/patch/interceptLinkClicks
import { AngularApp } from './angular/AngularApp'; import { AngularApp } from './angular/AngularApp';
import { PanelRenderer } from './features/panel/PanelRenderer'; import { PanelRenderer } from './features/panel/PanelRenderer';
import { QueryRunner } from './features/query/state/QueryRunner'; import { QueryRunner } from './features/query/state/QueryRunner';
import { getTimeSrv } from './features/dashboard/services/TimeSrv';
import { getVariablesUrlParams } from './features/variables/getAllVariableValuesForUrl';
// add move to lodash for backward compatabilty with plugins // add move to lodash for backward compatabilty with plugins
// @ts-ignore // @ts-ignore
@ -79,6 +82,12 @@ export class GrafanaApp {
setQueryRunnerFactory(() => new QueryRunner()); setQueryRunnerFactory(() => new QueryRunner());
setVariableQueryRunner(new VariableQueryRunner()); setVariableQueryRunner(new VariableQueryRunner());
locationUtil.initialize({
config,
getTimeRangeForUrl: getTimeSrv().timeRangeForUrl,
getVariablesUrlParams: getVariablesUrlParams,
});
// intercept anchor clicks and forward it to custom history instead of relying on browser's history // intercept anchor clicks and forward it to custom history instead of relying on browser's history
document.addEventListener('click', interceptLinkClicks); document.addEventListener('click', interceptLinkClicks);

@ -1,5 +1,4 @@
import './annotations/all'; import './annotations/all';
import './templating/all';
import './plugins/all'; import './plugins/all';
import './dashboard'; import './dashboard';
import './panel/all'; import './panel/all';

@ -10,12 +10,6 @@ jest.mock('app/core/core', () => ({
})); }));
describe('timeSrv', () => { describe('timeSrv', () => {
const timer = {
register: jest.fn(),
cancel: jest.fn(),
cancelAll: jest.fn(),
};
let timeSrv: TimeSrv; let timeSrv: TimeSrv;
const _dashboard: any = { const _dashboard: any = {
@ -25,7 +19,7 @@ describe('timeSrv', () => {
}; };
beforeEach(() => { beforeEach(() => {
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
_dashboard.refresh = false; _dashboard.refresh = false;
}); });
@ -50,7 +44,7 @@ describe('timeSrv', () => {
it('should handle relative times', () => { it('should handle relative times', () => {
locationService.push('/d/id?from=now-2d&to=now'); locationService.push('/d/id?from=now-2d&to=now');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -61,7 +55,7 @@ describe('timeSrv', () => {
it('should handle formatted dates', () => { it('should handle formatted dates', () => {
locationService.push('/d/id?from=20140410T052010&to=20140520T031022'); locationService.push('/d/id?from=20140410T052010&to=20140520T031022');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -72,7 +66,7 @@ describe('timeSrv', () => {
it('should ignore refresh if time absolute', () => { it('should ignore refresh if time absolute', () => {
locationService.push('/d/id?from=20140410T052010&to=20140520T031022'); locationService.push('/d/id?from=20140410T052010&to=20140520T031022');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
// dashboard saved with refresh on // dashboard saved with refresh on
_dashboard.refresh = true; _dashboard.refresh = true;
@ -84,7 +78,7 @@ describe('timeSrv', () => {
it('should handle formatted dates without time', () => { it('should handle formatted dates without time', () => {
locationService.push('/d/id?from=20140410&to=20140520'); locationService.push('/d/id?from=20140410&to=20140520');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -95,7 +89,7 @@ describe('timeSrv', () => {
it('should handle epochs', () => { it('should handle epochs', () => {
locationService.push('/d/id?from=1410337646373&to=1410337665699'); locationService.push('/d/id?from=1410337646373&to=1410337665699');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -106,7 +100,7 @@ describe('timeSrv', () => {
it('should handle epochs that look like formatted date without time', () => { it('should handle epochs that look like formatted date without time', () => {
locationService.push('/d/id?from=20149999&to=20159999'); locationService.push('/d/id?from=20149999&to=20159999');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -117,7 +111,7 @@ describe('timeSrv', () => {
it('should handle epochs that look like formatted date', () => { it('should handle epochs that look like formatted date', () => {
locationService.push('/d/id?from=201499991234567&to=201599991234567'); locationService.push('/d/id?from=201499991234567&to=201599991234567');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -128,7 +122,7 @@ describe('timeSrv', () => {
it('should handle bad dates', () => { it('should handle bad dates', () => {
locationService.push('/d/id?from=20151126T00010%3C%2Fp%3E%3Cspan%20class&to=now'); locationService.push('/d/id?from=20151126T00010%3C%2Fp%3E%3Cspan%20class&to=now');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
_dashboard.time.from = 'now-6h'; _dashboard.time.from = 'now-6h';
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
@ -140,7 +134,7 @@ describe('timeSrv', () => {
it('handles time window specfied as interval string', () => { it('handles time window specfied as interval string', () => {
locationService.push('/d/id?time=1410337645000&time.window=10s'); locationService.push('/d/id?time=1410337645000&time.window=10s');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();
@ -151,7 +145,7 @@ describe('timeSrv', () => {
it('handles time window specified in ms', () => { it('handles time window specified in ms', () => {
locationService.push('/d/id?time=1410337645000&time.window=10000'); locationService.push('/d/id?time=1410337645000&time.window=10000');
timeSrv = new TimeSrv(jest.fn() as any, timer, new ContextSrvStub() as any); timeSrv = new TimeSrv(new ContextSrvStub() as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
const time = timeSrv.timeRange(); const time = timeSrv.timeRange();

@ -1,5 +1,4 @@
import _ from 'lodash'; import _ from 'lodash';
import { ITimeoutService } from 'angular';
import { import {
dateMath, dateMath,
dateTime, dateTime,
@ -10,16 +9,14 @@ import {
TimeRange, TimeRange,
toUtc, toUtc,
} from '@grafana/data'; } from '@grafana/data';
import coreModule from 'app/core/core_module';
import { ContextSrv } from 'app/core/services/context_srv';
import { DashboardModel } from '../state/DashboardModel'; import { DashboardModel } from '../state/DashboardModel';
import { getShiftedTimeRange, getZoomedTimeRange } from 'app/core/utils/timePicker'; import { getShiftedTimeRange, getZoomedTimeRange } from 'app/core/utils/timePicker';
import { appEvents } from '../../../core/core';
import { config } from 'app/core/config'; import { config } from 'app/core/config';
import { getRefreshFromUrl } from '../utils/getRefreshFromUrl'; import { getRefreshFromUrl } from '../utils/getRefreshFromUrl';
import { locationService } from '@grafana/runtime'; import { locationService } from '@grafana/runtime';
import { ShiftTimeEvent, ShiftTimeEventPayload, ZoomOutEvent } from '../../../types/events'; import { ShiftTimeEvent, ShiftTimeEventPayload, ZoomOutEvent } from '../../../types/events';
import { contextSrv, ContextSrv } from 'app/core/services/context_srv';
import appEvents from 'app/core/app_events';
export class TimeSrv { export class TimeSrv {
time: any; time: any;
@ -30,14 +27,15 @@ export class TimeSrv {
timeAtLoad: any; timeAtLoad: any;
private autoRefreshBlocked: boolean; private autoRefreshBlocked: boolean;
/** @ngInject */ constructor(private contextSrv: ContextSrv) {
constructor(private $timeout: ITimeoutService, private timer: any, private contextSrv: ContextSrv) {
// default time // default time
this.time = getDefaultTimeRange().raw; this.time = getDefaultTimeRange().raw;
this.refreshDashboard = this.refreshDashboard.bind(this); this.refreshDashboard = this.refreshDashboard.bind(this);
appEvents.subscribe(ZoomOutEvent, (e) => { appEvents.subscribe(ZoomOutEvent, (e) => {
this.zoomOut(e.payload); this.zoomOut(e.payload);
}); });
appEvents.subscribe(ShiftTimeEvent, (e) => { appEvents.subscribe(ShiftTimeEvent, (e) => {
this.shiftTime(e.payload); this.shiftTime(e.payload);
}); });
@ -51,8 +49,6 @@ export class TimeSrv {
} }
init(dashboard: DashboardModel) { init(dashboard: DashboardModel) {
this.timer.cancelAll();
this.dashboard = dashboard; this.dashboard = dashboard;
this.time = dashboard.time; this.time = dashboard.time;
this.refresh = dashboard.refresh; this.refresh = dashboard.refresh;
@ -193,18 +189,16 @@ export class TimeSrv {
setAutoRefresh(interval: any) { setAutoRefresh(interval: any) {
this.dashboard.refresh = interval; this.dashboard.refresh = interval;
this.cancelNextRefresh(); this.stopAutoRefresh();
if (interval) { if (interval) {
const validInterval = this.contextSrv.getValidInterval(interval); const validInterval = this.contextSrv.getValidInterval(interval);
const intervalMs = rangeUtil.intervalToMs(validInterval); const intervalMs = rangeUtil.intervalToMs(validInterval);
this.refreshTimer = this.timer.register( this.refreshTimer = setTimeout(() => {
this.$timeout(() => { this.startNextRefreshTimer(intervalMs);
this.startNextRefreshTimer(intervalMs); this.refreshDashboard();
this.refreshDashboard(); }, intervalMs);
}, intervalMs)
);
} }
if (interval) { if (interval) {
@ -220,21 +214,18 @@ export class TimeSrv {
} }
private startNextRefreshTimer(afterMs: number) { private startNextRefreshTimer(afterMs: number) {
this.cancelNextRefresh(); this.refreshTimer = setTimeout(() => {
this.refreshTimer = this.timer.register( this.startNextRefreshTimer(afterMs);
this.$timeout(() => { if (this.contextSrv.isGrafanaVisible()) {
this.startNextRefreshTimer(afterMs); this.refreshDashboard();
if (this.contextSrv.isGrafanaVisible()) { } else {
this.refreshDashboard(); this.autoRefreshBlocked = true;
} else { }
this.autoRefreshBlocked = true; }, afterMs);
}
}, afterMs)
);
} }
private cancelNextRefresh() { stopAutoRefresh() {
this.timer.cancel(this.refreshTimer); clearTimeout(this.refreshTimer);
} }
setTime(time: RawTimeRange, fromRouteUpdate?: boolean) { setTime(time: RawTimeRange, fromRouteUpdate?: boolean) {
@ -313,14 +304,16 @@ export class TimeSrv {
} }
} }
let singleton: TimeSrv; let singleton: TimeSrv | undefined;
export function setTimeSrv(srv: TimeSrv) { export function setTimeSrv(srv: TimeSrv) {
singleton = srv; singleton = srv;
} }
export function getTimeSrv(): TimeSrv { export function getTimeSrv(): TimeSrv {
if (!singleton) {
singleton = new TimeSrv(contextSrv);
}
return singleton; return singleton;
} }
coreModule.service('timeSrv', TimeSrv);

@ -29,7 +29,7 @@ import {
RenderEvent, RenderEvent,
} from 'app/types/events'; } from 'app/types/events';
import { getTimeSrv } from '../services/TimeSrv'; import { getTimeSrv } from '../services/TimeSrv';
import { getAllVariableValuesForUrl } from '../../variables/getAllVariableValuesForUrl'; import { getVariablesUrlParams } from '../../variables/getAllVariableValuesForUrl';
import { import {
filterFieldConfigOverrides, filterFieldConfigOverrides,
getPanelOptionsWithDefaults, getPanelOptionsWithDefaults,
@ -530,7 +530,8 @@ export class PanelModel implements DataConfigSource {
if (extraVars) { if (extraVars) {
vars = vars ? { ...vars, ...extraVars } : extraVars; vars = vars ? { ...vars, ...extraVars } : extraVars;
} }
const allVariablesParams = getAllVariableValuesForUrl(vars);
const allVariablesParams = getVariablesUrlParams(vars);
const variablesQuery = urlUtil.toUrlParams(allVariablesParams); const variablesQuery = urlUtil.toUrlParams(allVariablesParams);
const timeRangeUrl = urlUtil.toUrlParams(getTimeSrv().timeRangeForUrl()); const timeRangeUrl = urlUtil.toUrlParams(getTimeSrv().timeRangeForUrl());

@ -15,6 +15,7 @@ import { loadPanelPlugin } from 'app/features/plugins/state/actions';
import { DashboardAcl, DashboardAclUpdateDTO, NewDashboardAclItem, PermissionLevel, ThunkResult } from 'app/types'; import { DashboardAcl, DashboardAclUpdateDTO, NewDashboardAclItem, PermissionLevel, ThunkResult } from 'app/types';
import { PanelModel } from './PanelModel'; import { PanelModel } from './PanelModel';
import { cancelVariables } from '../../variables/state/actions'; import { cancelVariables } from '../../variables/state/actions';
import { getTimeSrv } from '../services/TimeSrv';
export function getDashboardPermissions(id: number): ThunkResult<void> { export function getDashboardPermissions(id: number): ThunkResult<void> {
return async (dispatch) => { return async (dispatch) => {
@ -168,6 +169,8 @@ export const cleanUpDashboardAndVariables = (): ThunkResult<void> => (dispatch,
dashboard.destroy(); dashboard.destroy();
} }
getTimeSrv().stopAutoRefresh();
dispatch(cleanUpDashboard()); dispatch(cleanUpDashboard());
dispatch(cancelVariables()); dispatch(cancelVariables());
}; };

@ -24,7 +24,7 @@ import {
VariableSuggestion, VariableSuggestion,
VariableSuggestionsScope, VariableSuggestionsScope,
} from '@grafana/data'; } from '@grafana/data';
import { getAllVariableValuesForUrl } from '../../variables/getAllVariableValuesForUrl'; import { getVariablesUrlParams } from '../../variables/getAllVariableValuesForUrl';
const timeRangeVars = [ const timeRangeVars = [
{ {
@ -280,7 +280,7 @@ export class LinkSrv implements LinkService {
if (link.includeVars) { if (link.includeVars) {
params = { params = {
...params, ...params,
...getAllVariableValuesForUrl(), ...getVariablesUrlParams(),
}; };
} }

@ -19,19 +19,13 @@ describe('linkSrv', () => {
let templateSrv: TemplateSrv; let templateSrv: TemplateSrv;
function initLinkSrv() { function initLinkSrv() {
const timer = {
register: jest.fn(),
cancel: jest.fn(),
cancelAll: jest.fn(),
};
const _dashboard: any = { const _dashboard: any = {
time: { from: 'now-6h', to: 'now' }, time: { from: 'now-6h', to: 'now' },
getTimezone: jest.fn(() => 'browser'), getTimezone: jest.fn(() => 'browser'),
timeRangeUpdated: () => {}, timeRangeUpdated: () => {},
}; };
const timeSrv = new TimeSrv(jest.fn() as any, timer, {} as any); const timeSrv = new TimeSrv({} as any);
timeSrv.init(_dashboard); timeSrv.init(_dashboard);
timeSrv.setTime({ from: 'now-1h', to: 'now' }); timeSrv.setTime({ from: 'now-1h', to: 'now' });
_dashboard.refresh = false; _dashboard.refresh = false;
@ -126,10 +120,8 @@ describe('linkSrv', () => {
({ url, appSubUrl, expected }) => { ({ url, appSubUrl, expected }) => {
locationUtil.initialize({ locationUtil.initialize({
config: { appSubUrl } as any, config: { appSubUrl } as any,
// @ts-ignore getVariablesUrlParams: (() => {}) as any,
buildParamsFromVariables: () => {}, getTimeRangeForUrl: (() => {}) as any,
// @ts-ignore
getTimeRangeForUrl: () => {},
}); });
const link = linkSrv.getDataLinkUIModel( const link = linkSrv.getDataLinkUIModel(

@ -1,4 +0,0 @@
import coreModule from 'app/core/core_module';
import { getTemplateSrv } from './template_srv';
coreModule.factory('templateSrv', () => getTemplateSrv());

@ -329,5 +329,7 @@ export class TemplateSrv implements BaseTemplateSrv {
// Expose the template srv // Expose the template srv
const srv = new TemplateSrv(); const srv = new TemplateSrv();
setTemplateSrv(srv); setTemplateSrv(srv);
export const getTemplateSrv = () => srv; export const getTemplateSrv = () => srv;

@ -1,7 +1,7 @@
import { setTemplateSrv } from '@grafana/runtime'; import { setTemplateSrv } from '@grafana/runtime';
import { variableAdapters } from './adapters'; import { variableAdapters } from './adapters';
import { createQueryVariableAdapter } from './query/adapter'; import { createQueryVariableAdapter } from './query/adapter';
import { getAllVariableValuesForUrl } from './getAllVariableValuesForUrl'; import { getVariablesUrlParams } from './getAllVariableValuesForUrl';
import { initTemplateSrv } from '../../../test/helpers/initTemplateSrv'; import { initTemplateSrv } from '../../../test/helpers/initTemplateSrv';
describe('getAllVariableValuesForUrl', () => { describe('getAllVariableValuesForUrl', () => {
@ -26,7 +26,7 @@ describe('getAllVariableValuesForUrl', () => {
}); });
it('should set multiple url params', () => { it('should set multiple url params', () => {
let params: any = getAllVariableValuesForUrl(); let params: any = getVariablesUrlParams();
expect(params['var-test']).toMatchObject(['val1', 'val2']); expect(params['var-test']).toMatchObject(['val1', 'val2']);
}); });
}); });
@ -48,7 +48,7 @@ describe('getAllVariableValuesForUrl', () => {
}); });
it('should not include template variable value in url', () => { it('should not include template variable value in url', () => {
const params = getAllVariableValuesForUrl(); const params = getVariablesUrlParams();
expect(params['var-test']).toBe(undefined); expect(params['var-test']).toBe(undefined);
}); });
}); });
@ -71,7 +71,7 @@ describe('getAllVariableValuesForUrl', () => {
}); });
it('should not include template variable value in url', () => { it('should not include template variable value in url', () => {
const params = getAllVariableValuesForUrl(); const params = getVariablesUrlParams();
expect(params['var-test']).toBe(undefined); expect(params['var-test']).toBe(undefined);
}); });
}); });
@ -82,7 +82,7 @@ describe('getAllVariableValuesForUrl', () => {
}); });
it('should set scoped value as url params', () => { it('should set scoped value as url params', () => {
const params = getAllVariableValuesForUrl({ const params = getVariablesUrlParams({
test: { value: 'val1', text: 'val1text' }, test: { value: 'val1', text: 'val1text' },
}); });
expect(params['var-test']).toBe('val1'); expect(params['var-test']).toBe('val1');
@ -95,7 +95,7 @@ describe('getAllVariableValuesForUrl', () => {
}); });
it('should not set scoped value as url params', () => { it('should not set scoped value as url params', () => {
const params = getAllVariableValuesForUrl({ const params = getVariablesUrlParams({
test: { name: 'test', value: 'val1', text: 'val1text', skipUrlSync: true }, test: { name: 'test', value: 'val1', text: 'val1text', skipUrlSync: true },
}); });
expect(params['var-test']).toBe(undefined); expect(params['var-test']).toBe(undefined);

@ -1,9 +1,9 @@
import { ScopedVars } from '@grafana/data'; import { ScopedVars, UrlQueryMap } from '@grafana/data';
import { getTemplateSrv } from '@grafana/runtime'; import { getTemplateSrv } from '@grafana/runtime';
import { variableAdapters } from './adapters'; import { variableAdapters } from './adapters';
export function getAllVariableValuesForUrl(scopedVars?: ScopedVars) { export function getVariablesUrlParams(scopedVars?: ScopedVars): UrlQueryMap {
const params: Record<string, string | string[]> = {}; const params: UrlQueryMap = {};
const variables = getTemplateSrv().getVariables(); const variables = getTemplateSrv().getVariables();
// console.log(variables) // console.log(variables)

@ -17,6 +17,8 @@ import { getProcessedDataFrames } from 'app/features/query/state/runRequest';
import { DataProcessor } from '../graph/data_processor'; import { DataProcessor } from '../graph/data_processor';
import { LegacyResponseData, PanelEvents, DataFrame, rangeUtil } from '@grafana/data'; import { LegacyResponseData, PanelEvents, DataFrame, rangeUtil } from '@grafana/data';
import { CoreEvents } from 'app/types'; import { CoreEvents } from 'app/types';
import { TemplateSrv } from 'app/features/templating/template_srv';
import { TimeSrv } from 'app/features/dashboard/services/TimeSrv';
const X_BUCKET_NUMBER_DEFAULT = 30; const X_BUCKET_NUMBER_DEFAULT = 30;
const Y_BUCKET_NUMBER_DEFAULT = 10; const Y_BUCKET_NUMBER_DEFAULT = 10;
@ -125,8 +127,9 @@ export class HeatmapCtrl extends MetricsPanelCtrl {
processor: DataProcessor; // Shared with graph panel processor: DataProcessor; // Shared with graph panel
/** @ngInject */ /** @ngInject */
constructor($scope: any, $injector: auto.IInjectorService) { constructor($scope: any, $injector: auto.IInjectorService, templateSrv: TemplateSrv, timeSrv: TimeSrv) {
super($scope, $injector); super($scope, $injector);
this.selectionActivated = false; this.selectionActivated = false;
_.defaultsDeep(this.panel, panelDefaults); _.defaultsDeep(this.panel, panelDefaults);

@ -5,7 +5,6 @@ import $ from 'jquery';
// Utils and servies // Utils and servies
import { colors } from '@grafana/ui'; import { colors } from '@grafana/ui';
import { import {
getTemplateSrv,
setBackendSrv, setBackendSrv,
setDataSourceSrv, setDataSourceSrv,
setLegacyAngularInjector, setLegacyAngularInjector,
@ -16,7 +15,6 @@ import config from 'app/core/config';
import coreModule from 'app/core/core_module'; import coreModule from 'app/core/core_module';
import { profiler } from 'app/core/profiler'; import { profiler } from 'app/core/profiler';
import appEvents from 'app/core/app_events'; import appEvents from 'app/core/app_events';
import { TimeSrv, setTimeSrv, getTimeSrv } from 'app/features/dashboard/services/TimeSrv';
import { DatasourceSrv } from 'app/features/plugins/datasource_srv'; import { DatasourceSrv } from 'app/features/plugins/datasource_srv';
import { AngularLoader, setAngularLoader } from 'app/core/services/AngularLoader'; import { AngularLoader, setAngularLoader } from 'app/core/services/AngularLoader';
@ -27,7 +25,7 @@ import { UtilSrv } from 'app/core/services/util_srv';
import { ContextSrv } from 'app/core/services/context_srv'; import { ContextSrv } from 'app/core/services/context_srv';
import { DashboardSrv, setDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { DashboardSrv, setDashboardSrv } from 'app/features/dashboard/services/DashboardSrv';
import { IRootScopeService, IAngularEvent, auto } from 'angular'; import { IRootScopeService, IAngularEvent, auto } from 'angular';
import { AppEvent, locationUtil } from '@grafana/data'; import { AppEvent } from '@grafana/data';
import { backendSrv } from 'app/core/services/backend_srv'; import { backendSrv } from 'app/core/services/backend_srv';
import { initGrafanaLive } from 'app/features/live/live'; import { initGrafanaLive } from 'app/features/live/live';
@ -40,7 +38,6 @@ export class GrafanaCtrl {
utilSrv: UtilSrv, utilSrv: UtilSrv,
$rootScope: GrafanaRootScope, $rootScope: GrafanaRootScope,
contextSrv: ContextSrv, contextSrv: ContextSrv,
timeSrv: TimeSrv,
linkSrv: LinkSrv, linkSrv: LinkSrv,
datasourceSrv: DatasourceSrv, datasourceSrv: DatasourceSrv,
dashboardSrv: DashboardSrv, dashboardSrv: DashboardSrv,
@ -51,20 +48,12 @@ export class GrafanaCtrl {
setAngularLoader(angularLoader); setAngularLoader(angularLoader);
setBackendSrv(backendSrv); setBackendSrv(backendSrv);
setDataSourceSrv(datasourceSrv); setDataSourceSrv(datasourceSrv);
setTimeSrv(timeSrv);
setLinkSrv(linkSrv); setLinkSrv(linkSrv);
setDashboardSrv(dashboardSrv); setDashboardSrv(dashboardSrv);
setLegacyAngularInjector($injector); setLegacyAngularInjector($injector);
datasourceSrv.init(config.datasources, config.defaultDatasource); datasourceSrv.init(config.datasources, config.defaultDatasource);
locationUtil.initialize({
config,
getTimeRangeForUrl: getTimeSrv().timeRangeForUrl,
// @ts-ignore
buildParamsFromVariables: getTemplateSrv().fillVariableValuesForUrl,
});
setLocationSrv(locationService); setLocationSrv(locationService);
// Initialize websocket event streaming // Initialize websocket event streaming

Loading…
Cancel
Save