module.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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 [
  30. panel.content,
  31. panel.mode
  32. ].join();
  33. };
  34. $scope.$watch(
  35. renderWhenChanged,
  36. _.throttle(() => {
  37. this.render();
  38. }, 100)
  39. );
  40. }
  41. onInitEditMode() {
  42. this.addEditorTab('Options', 'public/app/plugins/panel/text/editor.html');
  43. if (this.panel.mode === 'text') {
  44. this.panel.mode = 'markdown';
  45. }
  46. }
  47. onRefresh() {
  48. this.render();
  49. }
  50. onRender() {
  51. if (this.panel.mode === 'markdown') {
  52. this.renderMarkdown(this.panel.content);
  53. } else if (this.panel.mode === 'html') {
  54. this.updateContent(this.panel.content);
  55. }
  56. this.renderingCompleted();
  57. }
  58. renderText(content: string) {
  59. content = content
  60. .replace(/&/g, '&')
  61. .replace(/>/g, '>')
  62. .replace(/</g, '&lt;')
  63. .replace(/\n/g, '<br/>');
  64. this.updateContent(content);
  65. }
  66. renderMarkdown(content: string) {
  67. if (!this.remarkable) {
  68. this.remarkable = new Remarkable();
  69. }
  70. this.$scope.$applyAsync(() => {
  71. this.updateContent(this.remarkable.render(content));
  72. });
  73. }
  74. updateContent(html: string) {
  75. html = config.disableSanitizeHtml ? html : sanitize(html);
  76. try {
  77. this.content = this.$sce.trustAsHtml(this.templateSrv.replace(html, this.panel.scopedVars));
  78. } catch (e) {
  79. console.log('Text panel error: ', e);
  80. this.content = this.$sce.trustAsHtml(html);
  81. }
  82. }
  83. }
  84. export { TextPanelCtrl as PanelCtrl };