grafana/public/app/plugins/panel/text2/TextPanel.tsx

94 lines
2.2 KiB
TypeScript
Raw Normal View History

2019-03-06 17:54:19 -06:00
import React, { PureComponent } from 'react';
2019-02-23 23:53:20 -06:00
import Remarkable from 'remarkable';
import { sanitize } from 'app/core/utils/text';
import config from 'app/core/config';
import { debounce } from 'lodash';
// Types
import { TextOptions } from './types';
import { PanelProps } from '@grafana/ui/src/types';
interface Props extends PanelProps<TextOptions> {}
interface State {
html: string;
}
2019-03-06 17:54:19 -06:00
export class TextPanel extends PureComponent<Props, State> {
2019-02-23 23:53:20 -06:00
remarkable: Remarkable;
constructor(props) {
super(props);
this.state = {
2019-03-05 13:14:22 -06:00
html: this.processContent(props.options),
2019-02-23 23:53:20 -06:00
};
}
updateHTML = debounce(() => {
const html = this.processContent(this.props.options);
if (html !== this.state.html) {
this.setState({ html });
}
2019-03-06 17:54:19 -06:00
}, 150);
2019-02-23 23:53:20 -06:00
componentDidUpdate(prevProps: Props) {
// Since any change could be referenced in a template variable,
2019-03-06 17:54:19 -06:00
// This needs to process everytime (with debounce)
2019-02-23 23:53:20 -06:00
this.updateHTML();
}
prepareHTML(html: string): string {
2019-03-05 13:14:22 -06:00
const { replaceVariables } = this.props;
2019-02-23 23:53:20 -06:00
html = config.disableSanitizeHtml ? html : sanitize(html);
try {
2019-03-05 13:14:22 -06:00
return replaceVariables(html);
2019-02-23 23:53:20 -06:00
} catch (e) {
// TODO -- put the error in the header window
console.log('Text panel error: ', e);
return html;
}
}
prepareText(content: string): string {
return this.prepareHTML(
content
.replace(/&/g, '&amp;')
.replace(/>/g, '&gt;')
.replace(/</g, '&lt;')
.replace(/\n/g, '<br/>')
);
}
prepareMarkdown(content: string): string {
if (!this.remarkable) {
this.remarkable = new Remarkable();
}
return this.prepareHTML(this.remarkable.render(content));
}
processContent(options: TextOptions): string {
const { mode, content } = options;
if (!content) {
return '';
}
if (mode === 'markdown') {
return this.prepareMarkdown(content);
}
if (mode === 'html') {
return this.prepareHTML(content);
}
return this.prepareText(content);
}
render() {
const { html } = this.state;
return <div className="markdown-html panel-text-content" dangerouslySetInnerHTML={{ __html: html }} />;
}
}