module.ts 2.5 KB

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