plugin_directive_loader.ts 2.7 KB

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