import React, { PropTypes } from 'react';
import ModalTrigger from './../../components/ModalTrigger';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { github } from 'react-syntax-highlighter/dist/styles';
const $ = window.$ = require('jquery');
const propTypes = {
animation: PropTypes.bool,
queryResponse: PropTypes.object,
chartStatus: PropTypes.string,
queryEndpoint: PropTypes.string.isRequired,
};
const defaultProps = {
animation: true,
};
export default class DisplayQueryButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
language: null,
query: null,
isLoading: false,
error: null,
};
this.beforeOpen = this.beforeOpen.bind(this);
this.fetchQuery = this.fetchQuery.bind(this);
}
fetchQuery() {
this.setState({ isLoading: true });
$.ajax({
type: 'GET',
url: this.props.queryEndpoint,
success: data => {
this.setState({
language: data.language,
query: data.query,
isLoading: false,
});
},
error: data => {
this.setState({
error: data.error,
isLoading: false,
});
},
});
}
setStateFromQueryResponse() {
const qr = this.props.queryResponse;
this.setState({
language: qr.language,
query: qr.query,
isLoading: false,
});
}
beforeOpen() {
Iif (this.props.chartStatus === 'loading' || this.props.chartStatus === null) {
this.fetchQuery();
} else {
this.setStateFromQueryResponse();
}
}
renderModalBody() {
Iif (this.state.isLoading) {
return (<img
className="loading"
alt="Loading..."
src="/static/assets/images/loading.gif"
/>);
} else Iif (this.state.error) {
return <pre>{this.state.error}</pre>;
}
return (
<SyntaxHighlighter language={this.state.language} style={github}>
{this.state.query}
</SyntaxHighlighter>);
}
render() {
return (
<ModalTrigger
animation={this.props.animation}
isButton
triggerNode={<span>Query</span>}
modalTitle="Query"
bsSize="large"
beforeOpen={this.beforeOpen}
modalBody={this.renderModalBody()}
/>
);
}
}
DisplayQueryButton.propTypes = propTypes;
DisplayQueryButton.defaultProps = defaultProps;
|