TableInputCSV.tsx 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import React from 'react';
  2. import debounce from 'lodash/debounce';
  3. import { DataFrame } from '../../types/data';
  4. import { CSVConfig, readCSV } from '../../utils/csv';
  5. interface Props {
  6. config?: CSVConfig;
  7. text: string;
  8. width: string | number;
  9. height: string | number;
  10. onSeriesParsed: (data: DataFrame[], text: string) => void;
  11. }
  12. interface State {
  13. text: string;
  14. data: DataFrame[];
  15. }
  16. /**
  17. * Expects the container div to have size set and will fill it 100%
  18. */
  19. export class TableInputCSV extends React.PureComponent<Props, State> {
  20. constructor(props: Props) {
  21. super(props);
  22. const { text, config } = props;
  23. this.state = {
  24. text,
  25. data: readCSV(text, { config }),
  26. };
  27. }
  28. readCSV = debounce(() => {
  29. const { config } = this.props;
  30. const { text } = this.state;
  31. this.setState({ data: readCSV(text, { config }) });
  32. }, 150);
  33. componentDidUpdate(prevProps: Props, prevState: State) {
  34. const { text } = this.state;
  35. if (text !== prevState.text || this.props.config !== prevProps.config) {
  36. this.readCSV();
  37. }
  38. // If the props text has changed, replace our local version
  39. if (this.props.text !== prevProps.text && this.props.text !== text) {
  40. this.setState({ text: this.props.text });
  41. }
  42. if (this.state.data !== prevState.data) {
  43. this.props.onSeriesParsed(this.state.data, this.state.text);
  44. }
  45. }
  46. onTextChange = (event: any) => {
  47. this.setState({ text: event.target.value });
  48. };
  49. render() {
  50. const { width, height } = this.props;
  51. const { data } = this.state;
  52. return (
  53. <div className="gf-table-input-csv">
  54. <textarea
  55. style={{ width, height }}
  56. placeholder="Enter CSV here..."
  57. value={this.state.text}
  58. onChange={this.onTextChange}
  59. className="gf-form-input"
  60. />
  61. {data && (
  62. <footer>
  63. {data.map((series, index) => {
  64. return (
  65. <span key={index}>
  66. Rows:{series.rows.length}, Columns:{series.fields.length} &nbsp;
  67. <i className="fa fa-check-circle" />
  68. </span>
  69. );
  70. })}
  71. </footer>
  72. )}
  73. </div>
  74. );
  75. }
  76. }
  77. export default TableInputCSV;