TimeSrv.ts 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // Libraries
  2. import _ from 'lodash';
  3. // Utils
  4. import kbn from 'app/core/utils/kbn';
  5. import coreModule from 'app/core/core_module';
  6. import * as dateMath from '@grafana/ui/src/utils/datemath';
  7. // Types
  8. import { TimeRange, RawTimeRange } from '@grafana/ui';
  9. import { ITimeoutService, ILocationService } from 'angular';
  10. import { ContextSrv } from 'app/core/services/context_srv';
  11. import { DashboardModel } from '../state/DashboardModel';
  12. import { toUtc, dateTime, isDateTime } from '@grafana/ui/src/utils/moment_wrapper';
  13. export class TimeSrv {
  14. time: any;
  15. refreshTimer: any;
  16. refresh: any;
  17. oldRefresh: boolean;
  18. dashboard: Partial<DashboardModel>;
  19. timeAtLoad: any;
  20. private autoRefreshBlocked: boolean;
  21. /** @ngInject */
  22. constructor(
  23. $rootScope: any,
  24. private $timeout: ITimeoutService,
  25. private $location: ILocationService,
  26. private timer: any,
  27. private contextSrv: ContextSrv
  28. ) {
  29. // default time
  30. this.time = { from: '6h', to: 'now' };
  31. $rootScope.$on('zoom-out', this.zoomOut.bind(this));
  32. $rootScope.$on('$routeUpdate', this.routeUpdated.bind(this));
  33. document.addEventListener('visibilitychange', () => {
  34. if (this.autoRefreshBlocked && document.visibilityState === 'visible') {
  35. this.autoRefreshBlocked = false;
  36. this.refreshDashboard();
  37. }
  38. });
  39. }
  40. init(dashboard: Partial<DashboardModel>) {
  41. this.timer.cancelAll();
  42. this.dashboard = dashboard;
  43. this.time = dashboard.time;
  44. this.refresh = dashboard.refresh;
  45. this.initTimeFromUrl();
  46. this.parseTime();
  47. // remember time at load so we can go back to it
  48. this.timeAtLoad = _.cloneDeep(this.time);
  49. if (this.refresh) {
  50. this.setAutoRefresh(this.refresh);
  51. }
  52. }
  53. private parseTime() {
  54. // when absolute time is saved in json it is turned to a string
  55. if (_.isString(this.time.from) && this.time.from.indexOf('Z') >= 0) {
  56. this.time.from = dateTime(this.time.from).utc();
  57. }
  58. if (_.isString(this.time.to) && this.time.to.indexOf('Z') >= 0) {
  59. this.time.to = dateTime(this.time.to).utc();
  60. }
  61. }
  62. private parseUrlParam(value: any) {
  63. if (value.indexOf('now') !== -1) {
  64. return value;
  65. }
  66. if (value.length === 8) {
  67. return toUtc(value, 'YYYYMMDD');
  68. }
  69. if (value.length === 15) {
  70. return toUtc(value, 'YYYYMMDDTHHmmss');
  71. }
  72. if (!isNaN(value)) {
  73. const epoch = parseInt(value, 10);
  74. return toUtc(epoch);
  75. }
  76. return null;
  77. }
  78. private initTimeFromUrl() {
  79. const params = this.$location.search();
  80. if (params.from) {
  81. this.time.from = this.parseUrlParam(params.from) || this.time.from;
  82. }
  83. if (params.to) {
  84. this.time.to = this.parseUrlParam(params.to) || this.time.to;
  85. }
  86. // if absolute ignore refresh option saved to dashboard
  87. if (params.to && params.to.indexOf('now') === -1) {
  88. this.refresh = false;
  89. this.dashboard.refresh = false;
  90. }
  91. // but if refresh explicitly set then use that
  92. if (params.refresh) {
  93. this.refresh = params.refresh || this.refresh;
  94. }
  95. }
  96. private routeUpdated() {
  97. const params = this.$location.search();
  98. const urlRange = this.timeRangeForUrl();
  99. // check if url has time range
  100. if (params.from && params.to) {
  101. // is it different from what our current time range?
  102. if (params.from !== urlRange.from || params.to !== urlRange.to) {
  103. // issue update
  104. this.initTimeFromUrl();
  105. this.setTime(this.time, true);
  106. }
  107. } else if (this.timeHasChangedSinceLoad()) {
  108. this.setTime(this.timeAtLoad, true);
  109. }
  110. }
  111. private timeHasChangedSinceLoad() {
  112. return this.timeAtLoad && (this.timeAtLoad.from !== this.time.from || this.timeAtLoad.to !== this.time.to);
  113. }
  114. setAutoRefresh(interval: any) {
  115. this.dashboard.refresh = interval;
  116. this.cancelNextRefresh();
  117. if (interval) {
  118. const intervalMs = kbn.interval_to_ms(interval);
  119. this.refreshTimer = this.timer.register(
  120. this.$timeout(() => {
  121. this.startNextRefreshTimer(intervalMs);
  122. this.refreshDashboard();
  123. }, intervalMs)
  124. );
  125. }
  126. // update url inside timeout to so that a digest happens after (called from react)
  127. this.$timeout(() => {
  128. const params = this.$location.search();
  129. if (interval) {
  130. params.refresh = interval;
  131. this.$location.search(params);
  132. } else if (params.refresh) {
  133. delete params.refresh;
  134. this.$location.search(params);
  135. }
  136. });
  137. }
  138. refreshDashboard() {
  139. this.dashboard.timeRangeUpdated(this.timeRange());
  140. }
  141. private startNextRefreshTimer(afterMs: number) {
  142. this.cancelNextRefresh();
  143. this.refreshTimer = this.timer.register(
  144. this.$timeout(() => {
  145. this.startNextRefreshTimer(afterMs);
  146. if (this.contextSrv.isGrafanaVisible()) {
  147. this.refreshDashboard();
  148. } else {
  149. this.autoRefreshBlocked = true;
  150. }
  151. }, afterMs)
  152. );
  153. }
  154. private cancelNextRefresh() {
  155. this.timer.cancel(this.refreshTimer);
  156. }
  157. setTime(time: RawTimeRange, fromRouteUpdate?: boolean) {
  158. _.extend(this.time, time);
  159. // disable refresh if zoom in or zoom out
  160. if (isDateTime(time.to)) {
  161. this.oldRefresh = this.dashboard.refresh || this.oldRefresh;
  162. this.setAutoRefresh(false);
  163. } else if (this.oldRefresh && this.oldRefresh !== this.dashboard.refresh) {
  164. this.setAutoRefresh(this.oldRefresh);
  165. this.oldRefresh = null;
  166. }
  167. // update url
  168. if (fromRouteUpdate !== true) {
  169. const urlRange = this.timeRangeForUrl();
  170. const urlParams = this.$location.search();
  171. urlParams.from = urlRange.from;
  172. urlParams.to = urlRange.to;
  173. this.$location.search(urlParams);
  174. }
  175. this.$timeout(this.refreshDashboard.bind(this), 0);
  176. }
  177. timeRangeForUrl() {
  178. const range = this.timeRange().raw;
  179. if (isDateTime(range.from)) {
  180. range.from = range.from.valueOf().toString();
  181. }
  182. if (isDateTime(range.to)) {
  183. range.to = range.to.valueOf().toString();
  184. }
  185. return range;
  186. }
  187. timeRange(): TimeRange {
  188. // make copies if they are moment (do not want to return out internal moment, because they are mutable!)
  189. const raw = {
  190. from: isDateTime(this.time.from) ? dateTime(this.time.from) : this.time.from,
  191. to: isDateTime(this.time.to) ? dateTime(this.time.to) : this.time.to,
  192. };
  193. const timezone = this.dashboard && this.dashboard.getTimezone();
  194. return {
  195. from: dateMath.parse(raw.from, false, timezone),
  196. to: dateMath.parse(raw.to, true, timezone),
  197. raw: raw,
  198. };
  199. }
  200. zoomOut(e: any, factor: number) {
  201. const range = this.timeRange();
  202. const timespan = range.to.valueOf() - range.from.valueOf();
  203. const center = range.to.valueOf() - timespan / 2;
  204. const to = center + (timespan * factor) / 2;
  205. const from = center - (timespan * factor) / 2;
  206. this.setTime({ from: toUtc(from), to: toUtc(to) });
  207. }
  208. }
  209. let singleton: TimeSrv;
  210. export function setTimeSrv(srv: TimeSrv) {
  211. singleton = srv;
  212. }
  213. export function getTimeSrv(): TimeSrv {
  214. return singleton;
  215. }
  216. coreModule.service('timeSrv', TimeSrv);