addGraphiteFunc.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. define([
  2. 'angular',
  3. 'app',
  4. 'lodash',
  5. 'jquery',
  6. './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="tight-form-input input-medium tight-form-input"' +
  15. ' spellcheck="false" style="display:none"></input>';
  16. var buttonTemplate = '<a class="tight-form-item tight-form-func dropdown-toggle"' +
  17. ' tabindex="1" gf-dropdown="functionMenu" data-toggle="dropdown"' +
  18. ' data-placement="top"><i class="fa fa-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. if (!funcDef) {
  36. // try find close match
  37. value = value.toLowerCase();
  38. funcDef = _.find(allFunctions, function(funcName) {
  39. return funcName.toLowerCase().indexOf(value) === 0;
  40. });
  41. if (!funcDef) { return; }
  42. }
  43. $scope.$apply(function() {
  44. $scope.addFunction(funcDef);
  45. });
  46. $input.trigger('blur');
  47. return '';
  48. }
  49. });
  50. $button.click(function() {
  51. $button.hide();
  52. $input.show();
  53. $input.focus();
  54. });
  55. $input.keyup(function() {
  56. elem.toggleClass('open', $input.val() === '');
  57. });
  58. $input.blur(function() {
  59. // clicking the function dropdown menu wont
  60. // work if you remove class at once
  61. setTimeout(function() {
  62. $input.val('');
  63. $input.hide();
  64. $button.show();
  65. elem.removeClass('open');
  66. }, 200);
  67. });
  68. $compile(elem.contents())($scope);
  69. }
  70. };
  71. });
  72. function getAllFunctionNames(categories) {
  73. return _.reduce(categories, function(list, category) {
  74. _.each(category, function(func) {
  75. list.push(func.name);
  76. });
  77. return list;
  78. }, []);
  79. }
  80. function createFunctionDropDownMenu(categories) {
  81. return _.map(categories, function(list, category) {
  82. return {
  83. text: category,
  84. submenu: _.map(list, function(value) {
  85. return {
  86. text: value.name,
  87. click: "addFunction('" + value.name + "')",
  88. };
  89. })
  90. };
  91. });
  92. }
  93. });