index.js 2.72 KB
/* eslint-disable no-undef */
import React, { PureComponent } from 'react';

// import G2 from '@antv/g2/build/g2';
import { Chart } from '@antv/g2';
import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import equal from '../equal';

class ColorBlock extends PureComponent {
  componentDidMount() {
    this.renderChart(this.props.data);
    window.addEventListener('resize', this.resize);
  }

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

  componentWillUnmount() {
    window.removeEventListener('resize', this.resize);
    if (this.chart) {
      this.chart.destroy();
    }
    this.resize.cancel();
  }

  @Bind()
  @Debounce(200)
  resize() {
    if (!this.node) {
      return;
    }
    this.renderChart([]);
  }

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

  renderChart(data) {
    if (this.node.offsetWidth === 0) {
      return;
    }
    if (this.chart) {
      this.chart.destroy();
    }

    this.node.innerHTML = '';
    const { day, sMachines, height } = this.props;

    const source = data.map((arr) => {
      return {
        xValue: arr[0],
        yValue: arr[1],
        value: arr[2],
      };
    });

    const chart = new Chart({
      container: this.node,
      autoFit: true,
      height,
    });

    chart.data(source);

    chart.scale('xValue', {
      type: 'cat',
      values: day,
    });
    chart.scale('yValue', {
      type: 'cat',
      values: sMachines,
    });
    chart.scale('value', {
      nice: true,
    });

    chart.axis('xValue', {
      tickLine: null,
      grid: {
        alignTick: false,
        line: {
          style: {
            lineWidth: 1,
            lineDash: null,
            stroke: '#f0f0f0',
          },
        },
      },
    });

    chart.axis('yValue', {
      title: null,
      grid: {
        alignTick: false,
        line: {
          style: {
            lineWidth: 1,
            lineDash: null,
            stroke: '#f0f0f0',
          },
        },
      },
    });

    chart.tooltip({
      showMarkers: false,
    });

    chart
      .polygon()
      .position('xValue*yValue')
      .color('value', '#f6ffed-#389e0d-#135200')
      .label('value', {
        offset: -2,
        style: {
          fill: '#fff',
          shadowBlur: 2,
          shadowColor: 'rgba(0, 0, 0, .45)',
        },
      })
      .style({
        lineWidth: 1,
        stroke: '#fff',
      });

    chart.interaction('element-active');

    chart.render();
    this.chart = chart;
  }

  render() {
    const { height } = this.props;
    return (
      <div style={{ height }}>
        <div ref={this.handleRef} />
      </div>
    );
  }
}

export default ColorBlock;