index.js 2.21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
import React, { Component } from 'react';
import G2 from 'g2';
import Slider from 'g2-plugin-slider';
import styles from './index.less';

class TimelineChart extends Component {
  componentDidMount() {
    this.renderChart(this.props.data);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.data !== this.props.data) {
      this.renderChart(nextProps.data);
    }
  }

nikogu's avatar
nikogu committed
17 18 19 20 21 22 23 24 25
  componentWillUnmount() {
    if (this.chart) {
      this.chart.destroy();
    }
    if (this.slider) {
      this.slider.destroy();
    }
  }

26 27 28 29 30 31 32
  sliderId = `timeline-chart-slider-${Math.random() * 1000}`

  handleRef = (n) => {
    this.node = n;
  }

  renderChart(data) {
niko's avatar
niko committed
33
    const { height = 400, margin = [60, 20, 40, 40], titleMap } = this.props;
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

    if (!data || (data && data.length < 1)) {
      return;
    }

    // clean
    if (this.sliderId) {
      document.getElementById(this.sliderId).innerHTML = '';
    }
    this.node.innerHTML = '';

    const chart = new G2.Chart({
      container: this.node,
      forceFit: true,
      height,
      plotCfg: {
        margin,
      },
    });

    chart.axis('x', {
      title: false,
    });
    chart.axis('y1', {
      title: false,
    });
    chart.axis('y2', false);

    chart.legend({
      mode: false,
      position: 'top',
    });

    chart.source(data, {
      x: {
        type: 'timeCat',
        tickCount: 16,
        mask: 'HH:MM',
        range: [0, 1],
      },
      y1: {
        alias: titleMap.y1,
        min: 0,
      },
      y2: {
        alias: titleMap.y2,
        min: 0,
      },
    });

niko's avatar
niko committed
84 85
    chart.line().position('x*y1').color('#1890FF');
    chart.line().position('x*y2').color('#2FC25B');
86

nikogu's avatar
nikogu committed
87 88
    this.chart = chart;

89 90 91 92 93 94 95 96 97
    /* eslint new-cap:0 */
    const slider = new Slider({
      domId: this.sliderId,
      height: 26,
      xDim: 'x',
      yDim: 'y1',
      charts: [chart],
    });
    slider.render();
nikogu's avatar
nikogu committed
98 99

    this.slider = slider;
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
  }

  render() {
    const { height, title } = this.props;

    return (
      <div className={styles.timelineChart} style={{ height }}>
        <div>
          { title && <h4>{title}</h4>}
          <div ref={this.handleRef} />
          <div id={this.sliderId} />
        </div>
      </div>
    );
  }
}

export default TimelineChart;