addGraphiteFunc.js 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. define([
  2. 'angular',
  3. 'app',
  4. 'lodash',
  5. 'jquery',
  6. '../services/graphite/gfunc',
  7. ],
  8. function (angular, app, _, $, gfunc) {
  9. 'use strict';
  10. angular
  11. .module('grafana.directives')
  12. .directive('graphiteAddFunc', function($compile) {
  13. var inputTemplate = '<input type="text"'+
  14. ' class="grafana-target-segment-input input-medium grafana-target-segment-input"' +
  15. ' spellcheck="false" style="display:none"></input>';
  16. var buttonTemplate = '<a class="grafana-target-segment grafana-target-function dropdown-toggle"' +
  17. ' tabindex="1" gf-dropdown="functionMenu" data-toggle="dropdown"' +
  18. ' data-placement="top"><i class="icon-plus"></i></a>';
  19. return {
  20. link: function($scope, elem) {
  21. var categories = gfunc.getCategories();
  22. var allFunctions = getAllFunctionNames(categories);
  23. $scope.functionMenu = createFunctionDropDownMenu(categories);
  24. var $input = $(inputTemplate);
  25. var $button = $(buttonTemplate);
  26. $input.appendTo(elem);
  27. $button.appendTo(elem);
  28. $input.attr('data-provide', 'typeahead');
  29. $input.typeahead({
  30. source: allFunctions,
  31. minLength: 1,
  32. items: 10,
  33. updater: function (value) {
  34. var funcDef = gfunc.getFuncDef(value);
  35. $scope.$apply(function() {
  36. $scope.addFunction(funcDef);
  37. });
  38. $input.trigger('blur');
  39. return '';
  40. }
  41. });
  42. $button.click(function() {
  43. $button.hide();
  44. $input.show();
  45. $input.focus();
  46. });
  47. $input.keyup(function() {
  48. elem.toggleClass('open', $input.val() === '');
  49. });
  50. $input.blur(function() {
  51. $input.hide();
  52. $input.val('');
  53. $button.show();
  54. $button.focus();
  55. // clicking the function dropdown menu wont
  56. // work if you remove class at once
  57. setTimeout(function() {
  58. elem.removeClass('open');
  59. }, 200);
  60. });
  61. $compile(elem.contents())($scope);
  62. }
  63. };
  64. });
  65. function getAllFunctionNames(categories) {
  66. return _.reduce(categories, function(list, category) {
  67. _.each(category, function(func) {
  68. list.push(func.name);
  69. });
  70. return list;
  71. }, []);
  72. }
  73. function createFunctionDropDownMenu(categories) {
  74. return _.map(categories, function(list, category) {
  75. return {
  76. text: category,
  77. submenu: _.map(list, function(value) {
  78. return {
  79. text: value.name,
  80. click: "addFunction('" + value.name + "')",
  81. };
  82. })
  83. };
  84. });
  85. }
  86. });