interval_variable.ts 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import _ from 'lodash';
  2. import kbn from 'app/core/utils/kbn';
  3. import { Variable, assignModelProperties, variableTypes } from './variable';
  4. export class IntervalVariable implements Variable {
  5. name: string;
  6. auto_count: number; // tslint:disable-line variable-name
  7. auto_min: number; // tslint:disable-line variable-name
  8. options: any;
  9. auto: boolean;
  10. query: string;
  11. refresh: number;
  12. current: any;
  13. skipUrlSync: boolean;
  14. defaults = {
  15. type: 'interval',
  16. name: '',
  17. hide: 0,
  18. label: '',
  19. refresh: 2,
  20. options: [],
  21. current: {},
  22. query: '1m,10m,30m,1h,6h,12h,1d,7d,14d,30d',
  23. auto: false,
  24. auto_min: '10s',
  25. auto_count: 30,
  26. skipUrlSync: false,
  27. };
  28. /** @ngInject */
  29. constructor(private model, private timeSrv, private templateSrv, private variableSrv) {
  30. assignModelProperties(this, model, this.defaults);
  31. this.refresh = 2;
  32. }
  33. getSaveModel() {
  34. assignModelProperties(this.model, this, this.defaults);
  35. return this.model;
  36. }
  37. setValue(option) {
  38. this.updateAutoValue();
  39. return this.variableSrv.setOptionAsCurrent(this, option);
  40. }
  41. updateAutoValue() {
  42. if (!this.auto) {
  43. return;
  44. }
  45. // add auto option if missing
  46. if (this.options.length && this.options[0].text !== 'auto') {
  47. this.options.unshift({
  48. text: 'auto',
  49. value: '$__auto_interval_' + this.name,
  50. });
  51. }
  52. const res = kbn.calculateInterval(this.timeSrv.timeRange(), this.auto_count, this.auto_min);
  53. this.templateSrv.setGrafanaVariable('$__auto_interval_' + this.name, res.interval);
  54. // for backward compatibility, to be removed eventually
  55. this.templateSrv.setGrafanaVariable('$__auto_interval', res.interval);
  56. }
  57. updateOptions() {
  58. // extract options between quotes and/or comma
  59. this.options = _.map(this.query.match(/(["'])(.*?)\1|\w+/g), function(text) {
  60. text = text.replace(/["']+/g, '');
  61. return { text: text.trim(), value: text.trim() };
  62. });
  63. this.updateAutoValue();
  64. return this.variableSrv.validateVariableSelectionState(this);
  65. }
  66. dependsOn(variable) {
  67. return false;
  68. }
  69. setValueFromUrl(urlValue) {
  70. this.updateAutoValue();
  71. return this.variableSrv.setOptionFromUrl(this, urlValue);
  72. }
  73. getValueForUrl() {
  74. return this.current.value;
  75. }
  76. }
  77. variableTypes['interval'] = {
  78. name: 'Interval',
  79. ctor: IntervalVariable,
  80. description: 'Define a timespan interval (ex 1m, 1h, 1d)',
  81. };