add_graphite_func.js 3.0 KB

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