plugin_component.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. ///<reference path="../../headers/common.d.ts" />
  2. import angular from 'angular';
  3. import _ from 'lodash';
  4. import coreModule from '../core_module';
  5. function pluginDirectiveLoader($compile, datasourceSrv) {
  6. function getPluginComponentDirective(options) {
  7. return function() {
  8. return {
  9. templateUrl: options.Component.templateUrl,
  10. restrict: 'E',
  11. controller: options.Component,
  12. controllerAs: 'ctrl',
  13. bindToController: true,
  14. scope: options.bindings,
  15. link: (scope, elem, attrs, ctrl) => {
  16. if (ctrl.link) {
  17. ctrl.link(scope, elem, attrs, ctrl);
  18. }
  19. }
  20. };
  21. };
  22. }
  23. function getModule(scope, attrs) {
  24. switch (attrs.type) {
  25. case "metrics-query-editor":
  26. let datasource = scope.target.datasource || scope.ctrl.panel.datasource;
  27. return datasourceSrv.get(datasource).then(ds => {
  28. scope.datasource = ds;
  29. return System.import(ds.meta.module).then(dsModule => {
  30. return {
  31. name: 'metrics-query-editor-' + ds.meta.id,
  32. bindings: {target: "=", panelCtrl: "=", datasource: "="},
  33. attrs: {"target": "target", "panel-ctrl": "ctrl", datasource: "datasource"},
  34. Component: dsModule.QueryCtrl
  35. };
  36. });
  37. });
  38. case 'datasource-config-view':
  39. return System.import(scope.datasourceMeta.module).then(function(dsModule) {
  40. return {
  41. name: 'ds-config-' + scope.datasourceMeta.id,
  42. bindings: {meta: "=", current: "="},
  43. attrs: {meta: "datasourceMeta", current: "current"},
  44. Component: dsModule.ConfigView,
  45. };
  46. });
  47. }
  48. }
  49. function appendAndCompile(scope, elem, componentInfo) {
  50. var child = angular.element(document.createElement(componentInfo.name));
  51. _.each(componentInfo.attrs, (value, key) => {
  52. child.attr(key, value);
  53. });
  54. $compile(child)(scope);
  55. elem.empty();
  56. elem.append(child);
  57. }
  58. function registerPluginComponent(scope, elem, attrs, componentInfo) {
  59. if (!componentInfo.Component.registered) {
  60. var directiveName = attrs.$normalize(componentInfo.name);
  61. var directiveFn = getPluginComponentDirective(componentInfo);
  62. coreModule.directive(directiveName, directiveFn);
  63. componentInfo.Component.registered = true;
  64. }
  65. appendAndCompile(scope, elem, componentInfo);
  66. }
  67. return {
  68. restrict: 'E',
  69. link: function(scope, elem, attrs) {
  70. getModule(scope, attrs).then(function (componentInfo) {
  71. registerPluginComponent(scope, elem, attrs, componentInfo);
  72. });
  73. }
  74. };
  75. }
  76. coreModule.directive('pluginComponent', pluginDirectiveLoader);