variable_srv.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. // Libaries
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. // Utils & Services
  5. import coreModule from 'app/core/core_module';
  6. import { variableTypes } from './variable';
  7. import { Graph } from 'app/core/utils/dag';
  8. export class VariableSrv {
  9. dashboard: any;
  10. variables: any;
  11. /** @ngInject */
  12. constructor(private $rootScope, private $q, private $location, private $injector, private templateSrv) {
  13. // update time variant variables
  14. $rootScope.$on('refresh', this.onDashboardRefresh.bind(this), $rootScope);
  15. $rootScope.$on('template-variable-value-updated', this.updateUrlParamsWithCurrentVariables.bind(this), $rootScope);
  16. }
  17. init(dashboard) {
  18. this.dashboard = dashboard;
  19. // create working class models representing variables
  20. this.variables = dashboard.templating.list = dashboard.templating.list.map(this.createVariableFromModel.bind(this));
  21. this.templateSrv.init(this.variables);
  22. // init variables
  23. for (const variable of this.variables) {
  24. variable.initLock = this.$q.defer();
  25. }
  26. const queryParams = this.$location.search();
  27. return this.$q
  28. .all(
  29. this.variables.map(variable => {
  30. return this.processVariable(variable, queryParams);
  31. })
  32. )
  33. .then(() => {
  34. this.templateSrv.updateTemplateData();
  35. });
  36. }
  37. onDashboardRefresh(evt, payload) {
  38. if (payload && payload.fromVariableValueUpdated) {
  39. return Promise.resolve({});
  40. }
  41. const promises = this.variables.filter(variable => variable.refresh === 2).map(variable => {
  42. const previousOptions = variable.options.slice();
  43. return variable.updateOptions().then(() => {
  44. if (angular.toJson(previousOptions) !== angular.toJson(variable.options)) {
  45. this.$rootScope.$emit('template-variable-value-updated');
  46. }
  47. });
  48. });
  49. return this.$q.all(promises);
  50. }
  51. processVariable(variable, queryParams) {
  52. const dependencies = [];
  53. for (const otherVariable of this.variables) {
  54. if (variable.dependsOn(otherVariable)) {
  55. dependencies.push(otherVariable.initLock.promise);
  56. }
  57. }
  58. return this.$q
  59. .all(dependencies)
  60. .then(() => {
  61. const urlValue = queryParams['var-' + variable.name];
  62. if (urlValue !== void 0) {
  63. return variable.setValueFromUrl(urlValue).then(variable.initLock.resolve);
  64. }
  65. if (variable.refresh === 1 || variable.refresh === 2) {
  66. return variable.updateOptions().then(variable.initLock.resolve);
  67. }
  68. variable.initLock.resolve();
  69. })
  70. .finally(() => {
  71. this.templateSrv.variableInitialized(variable);
  72. delete variable.initLock;
  73. });
  74. }
  75. createVariableFromModel(model) {
  76. const ctor = variableTypes[model.type].ctor;
  77. if (!ctor) {
  78. throw {
  79. message: 'Unable to find variable constructor for ' + model.type,
  80. };
  81. }
  82. const variable = this.$injector.instantiate(ctor, { model: model });
  83. return variable;
  84. }
  85. addVariable(variable) {
  86. this.variables.push(variable);
  87. this.templateSrv.updateTemplateData();
  88. this.dashboard.updateSubmenuVisibility();
  89. }
  90. removeVariable(variable) {
  91. const index = _.indexOf(this.variables, variable);
  92. this.variables.splice(index, 1);
  93. this.templateSrv.updateTemplateData();
  94. this.dashboard.updateSubmenuVisibility();
  95. }
  96. updateOptions(variable) {
  97. return variable.updateOptions();
  98. }
  99. variableUpdated(variable, emitChangeEvents?) {
  100. // if there is a variable lock ignore cascading update because we are in a boot up scenario
  101. if (variable.initLock) {
  102. return this.$q.when();
  103. }
  104. const g = this.createGraph();
  105. const node = g.getNode(variable.name);
  106. let promises = [];
  107. if (node) {
  108. promises = node.getOptimizedInputEdges().map(e => {
  109. return this.updateOptions(this.variables.find(v => v.name === e.inputNode.name));
  110. });
  111. }
  112. return this.$q.all(promises).then(() => {
  113. if (emitChangeEvents) {
  114. this.$rootScope.$emit('template-variable-value-updated');
  115. this.$rootScope.$broadcast('refresh', { fromVariableValueUpdated: true });
  116. }
  117. });
  118. }
  119. selectOptionsForCurrentValue(variable) {
  120. let i, y, value, option;
  121. const selected: any = [];
  122. for (i = 0; i < variable.options.length; i++) {
  123. option = variable.options[i];
  124. option.selected = false;
  125. if (_.isArray(variable.current.value)) {
  126. for (y = 0; y < variable.current.value.length; y++) {
  127. value = variable.current.value[y];
  128. if (option.value === value) {
  129. option.selected = true;
  130. selected.push(option);
  131. }
  132. }
  133. } else if (option.value === variable.current.value) {
  134. option.selected = true;
  135. selected.push(option);
  136. }
  137. }
  138. return selected;
  139. }
  140. validateVariableSelectionState(variable) {
  141. if (!variable.current) {
  142. variable.current = {};
  143. }
  144. if (_.isArray(variable.current.value)) {
  145. let selected = this.selectOptionsForCurrentValue(variable);
  146. // if none pick first
  147. if (selected.length === 0) {
  148. selected = variable.options[0];
  149. } else {
  150. selected = {
  151. value: _.map(selected, val => {
  152. return val.value;
  153. }),
  154. text: _.map(selected, val => {
  155. return val.text;
  156. }).join(' + '),
  157. };
  158. }
  159. return variable.setValue(selected);
  160. } else {
  161. const currentOption = _.find(variable.options, {
  162. text: variable.current.text,
  163. });
  164. if (currentOption) {
  165. return variable.setValue(currentOption);
  166. } else {
  167. if (!variable.options.length) {
  168. return Promise.resolve();
  169. }
  170. return variable.setValue(variable.options[0]);
  171. }
  172. }
  173. }
  174. setOptionFromUrl(variable, urlValue) {
  175. let promise = this.$q.when();
  176. if (variable.refresh) {
  177. promise = variable.updateOptions();
  178. }
  179. return promise.then(() => {
  180. let option = _.find(variable.options, op => {
  181. return op.text === urlValue || op.value === urlValue;
  182. });
  183. let defaultText = urlValue;
  184. const defaultValue = urlValue;
  185. if (!option && _.isArray(urlValue)) {
  186. defaultText = [];
  187. for (let n = 0; n < urlValue.length; n++) {
  188. const t = _.find(variable.options, op => {
  189. return op.value === urlValue[n];
  190. });
  191. if (t) {
  192. defaultText.push(t.text);
  193. }
  194. }
  195. }
  196. option = option || { text: defaultText, value: defaultValue };
  197. return variable.setValue(option);
  198. });
  199. }
  200. setOptionAsCurrent(variable, option) {
  201. variable.current = _.cloneDeep(option);
  202. if (_.isArray(variable.current.text)) {
  203. variable.current.text = variable.current.text.join(' + ');
  204. }
  205. this.selectOptionsForCurrentValue(variable);
  206. return this.variableUpdated(variable);
  207. }
  208. updateUrlParamsWithCurrentVariables() {
  209. // update url
  210. const params = this.$location.search();
  211. // remove variable params
  212. _.each(params, (value, key) => {
  213. if (key.indexOf('var-') === 0) {
  214. delete params[key];
  215. }
  216. });
  217. // add new values
  218. this.templateSrv.fillVariableValuesForUrl(params);
  219. // update url
  220. this.$location.search(params);
  221. }
  222. setAdhocFilter(options) {
  223. let variable = _.find(this.variables, {
  224. type: 'adhoc',
  225. datasource: options.datasource,
  226. });
  227. if (!variable) {
  228. variable = this.createVariableFromModel({
  229. name: 'Filters',
  230. type: 'adhoc',
  231. datasource: options.datasource,
  232. });
  233. this.addVariable(variable);
  234. }
  235. const filters = variable.filters;
  236. let filter = _.find(filters, { key: options.key, value: options.value });
  237. if (!filter) {
  238. filter = { key: options.key, value: options.value };
  239. filters.push(filter);
  240. }
  241. filter.operator = options.operator;
  242. this.variableUpdated(variable, true);
  243. }
  244. createGraph() {
  245. const g = new Graph();
  246. this.variables.forEach(v => {
  247. g.createNode(v.name);
  248. });
  249. this.variables.forEach(v1 => {
  250. this.variables.forEach(v2 => {
  251. if (v1 === v2) {
  252. return;
  253. }
  254. if (v1.dependsOn(v2)) {
  255. g.link(v1.name, v2.name);
  256. }
  257. });
  258. });
  259. return g;
  260. }
  261. }
  262. coreModule.service('variableSrv', VariableSrv);