module.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import _ from 'lodash';
  2. import { PanelCtrl } from 'app/plugins/sdk';
  3. import { sanitize, escapeHtml } from 'app/core/utils/text';
  4. import config from 'app/core/config';
  5. import { auto, ISCEService } from 'angular';
  6. import { TemplateSrv } from 'app/features/templating/template_srv';
  7. import { renderMarkdown } from '@grafana/data';
  8. const defaultContent = `
  9. # Title
  10. For markdown syntax help: [commonmark.org/help](https://commonmark.org/help/)
  11. `;
  12. export class TextPanelCtrl extends PanelCtrl {
  13. static templateUrl = `public/app/plugins/panel/text/module.html`;
  14. static scrollable = true;
  15. content: string;
  16. // Set and populate defaults
  17. panelDefaults = {
  18. mode: 'markdown', // 'html', 'markdown', 'text'
  19. content: defaultContent,
  20. };
  21. /** @ngInject */
  22. constructor(
  23. $scope: any,
  24. $injector: auto.IInjectorService,
  25. private templateSrv: TemplateSrv,
  26. private $sce: ISCEService
  27. ) {
  28. super($scope, $injector);
  29. _.defaults(this.panel, this.panelDefaults);
  30. this.events.on('init-edit-mode', this.onInitEditMode.bind(this));
  31. this.events.on('refresh', this.onRefresh.bind(this));
  32. this.events.on('render', this.onRender.bind(this));
  33. const renderWhenChanged = (scope: any) => {
  34. const { panel } = scope.ctrl;
  35. return [panel.content, panel.mode].join();
  36. };
  37. $scope.$watch(
  38. renderWhenChanged,
  39. _.throttle(() => {
  40. this.render();
  41. }, 100)
  42. );
  43. }
  44. onInitEditMode() {
  45. this.addEditorTab('Options', 'public/app/plugins/panel/text/editor.html');
  46. if (this.panel.mode === 'text') {
  47. this.panel.mode = 'markdown';
  48. }
  49. }
  50. onRefresh() {
  51. this.render();
  52. }
  53. onRender() {
  54. if (this.panel.mode === 'markdown') {
  55. this.renderMarkdown(this.panel.content);
  56. } else if (this.panel.mode === 'html') {
  57. this.updateContent(this.panel.content);
  58. }
  59. this.renderingCompleted();
  60. }
  61. renderText(content: string) {
  62. const safeContent = escapeHtml(content).replace(/\n/g, '<br/>');
  63. this.updateContent(safeContent);
  64. }
  65. renderMarkdown(content: string) {
  66. this.$scope.$applyAsync(() => {
  67. this.updateContent(renderMarkdown(content));
  68. });
  69. }
  70. updateContent(html: string) {
  71. html = config.disableSanitizeHtml ? html : sanitize(html);
  72. try {
  73. this.content = this.$sce.trustAsHtml(this.templateSrv.replace(html, this.panel.scopedVars));
  74. } catch (e) {
  75. console.log('Text panel error: ', e);
  76. this.content = this.$sce.trustAsHtml(html);
  77. }
  78. }
  79. }
  80. export { TextPanelCtrl as PanelCtrl };