All files / javascripts/SqlLab/components HighlightedSql.jsx

0% Statements 0/28
0% Branches 0/14
0% Functions 0/2
0% Lines 0/28
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89                                                                                                                                                                                 
import React from 'react';
import PropTypes from 'prop-types';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { github } from 'react-syntax-highlighter/dist/styles';
import ModalTrigger from '../../components/ModalTrigger';
 
const defaultProps = {
  maxWidth: 50,
  maxLines: 5,
  shrink: false,
};
 
const propTypes = {
  sql: PropTypes.string.isRequired,
  rawSql: PropTypes.string,
  maxWidth: PropTypes.number,
  maxLines: PropTypes.number,
  shrink: PropTypes.bool,
};
 
class HighlightedSql extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modalBody: null,
    };
  }
  shrinkSql() {
    const sql = this.props.sql || '';
    let lines = sql.split('\n');
    if (lines.length >= this.props.maxLines) {
      lines = lines.slice(0, this.props.maxLines);
      lines.push('{...}');
    }
    return lines.map((line) => {
      if (line.length > this.props.maxWidth) {
        return line.slice(0, this.props.maxWidth) + '{...}';
      }
      return line;
    })
    .join('\n');
  }
  triggerNode() {
    const shownSql = this.props.shrink ? this.shrinkSql(this.props.sql) : this.props.sql;
    return (
      <SyntaxHighlighter language="sql" style={github}>
        {shownSql}
      </SyntaxHighlighter>);
  }
  generateModal() {
    let rawSql;
    if (this.props.rawSql && this.props.rawSql !== this.props.sql) {
      rawSql = (
        <div>
          <h4>Raw SQL</h4>
          <SyntaxHighlighter language="sql" style={github}>
            {this.props.rawSql}
          </SyntaxHighlighter>
        </div>
      );
    }
    this.setState({
      modalBody: (
        <div>
          <h4>Source SQL</h4>
          <SyntaxHighlighter language="sql" style={github}>
            {this.props.sql}
          </SyntaxHighlighter>
          {rawSql}
        </div>
      ),
    });
  }
  render() {
    return (
      <ModalTrigger
        modalTitle="SQL"
        triggerNode={this.triggerNode()}
        modalBody={this.state.modalBody}
        beforeOpen={this.generateModal.bind(this)}
      />
    );
  }
}
HighlightedSql.propTypes = propTypes;
HighlightedSql.defaultProps = defaultProps;
 
export default HighlightedSql;