index.js 6.53 KB
Newer Older
1
import React, { Component } from 'react';
niko's avatar
niko committed
2 3
import { Chart, Tooltip, Geom, Coord } from 'bizcharts';
import { DataView } from '@antv/data-set';
afc163's avatar
afc163 committed
4
import { Divider } from 'antd';
偏右's avatar
偏右 committed
5 6
import classNames from 'classnames';
import ReactFitText from 'react-fittext';
7
import Debounce from 'lodash-decorators/debounce';
afc163's avatar
afc163 committed
8
import Bind from 'lodash-decorators/bind';
niko's avatar
niko committed
9 10
import autoHeight from '../autoHeight';

11 12 13
import styles from './index.less';

/* eslint react/no-danger:0 */
niko's avatar
niko committed
14 15
@autoHeight()
export default class Pie extends Component {
16 17
  state = {
    legendData: [],
niko's avatar
niko committed
18
    legendBlock: false,
偏右's avatar
偏右 committed
19
  };
20 21

  componentDidMount() {
Rupeshiya's avatar
Rupeshiya committed
22
    this.getLegendData();
23 24
    this.resize();
    window.addEventListener('resize', this.resize);
25 26 27
  }

  componentWillReceiveProps(nextProps) {
28 29
    const { data } = this.props;
    if (data !== nextProps.data) {
30 31
      // because of charts data create when rendered
      // so there is a trick for get rendered time
32
      const { legendData } = this.state;
33 34
      this.setState(
        {
35
          legendData: [...legendData],
36 37
        },
        () => {
Rupeshiya's avatar
Rupeshiya committed
38
          this.getLegendData();
39 40
        }
      );
nikogu's avatar
nikogu committed
41
    }
42 43
  }

44
  componentWillUnmount() {
45
    window.removeEventListener('resize', this.resize);
afc163's avatar
afc163 committed
46
    this.resize.cancel();
47 48
  }

jim's avatar
jim committed
49
  getG2Instance = chart => {
niko's avatar
niko committed
50 51 52 53
    this.chart = chart;
  };

  // for custom lengend view
Rupeshiya's avatar
Rupeshiya committed
54
  getLegendData = () => {
niko's avatar
niko committed
55 56 57 58
    if (!this.chart) return;
    const geom = this.chart.getAllGeoms()[0]; // θŽ·ε–ζ‰€ζœ‰ηš„ε›Ύε½’
    const items = geom.get('dataArray') || []; // θŽ·ε–ε›Ύε½’ε―ΉεΊ”ηš„

jim's avatar
jim committed
59
    const legendData = items.map(item => {
niko's avatar
niko committed
60 61 62 63 64 65 66 67 68 69 70 71
      /* eslint no-underscore-dangle:0 */
      const origin = item[0]._origin;
      origin.color = item[0].color;
      origin.checked = true;
      return origin;
    });

    this.setState({
      legendData,
    });
  };

jim's avatar
jim committed
72
  handleRoot = n => {
73
    this.root = n;
niko's avatar
niko committed
74
  };
75

76 77 78 79
  handleLegendClick = (item, i) => {
    const newItem = item;
    newItem.checked = !newItem.checked;

afc163's avatar
afc163 committed
80
    const { legendData } = this.state;
81 82
    legendData[i] = newItem;

niko's avatar
niko committed
83 84
    const filteredLegendData = legendData.filter(l => l.checked).map(l => l.x);

85
    if (this.chart) {
niko's avatar
niko committed
86
      this.chart.filter('x', val => filteredLegendData.indexOf(val) > -1);
87 88 89 90 91
    }

    this.setState({
      legendData,
    });
niko's avatar
niko committed
92
  };
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  // for window resize auto responsive legend
  @Bind()
  @Debounce(300)
  resize() {
    const { hasLegend } = this.props;
    if (!hasLegend || !this.root) {
      window.removeEventListener('resize', this.resize);
      return;
    }
    const { legendBlock } = this.state;
    if (this.root.parentNode.clientWidth <= 380) {
      if (!legendBlock) {
        this.setState({
          legendBlock: true,
        });
      }
    } else if (legendBlock) {
      this.setState({
        legendBlock: false,
      });
    }
  }

niko's avatar
niko committed
117
  render() {
118
    const {
niko's avatar
niko committed
119 120 121 122 123 124 125 126 127 128
      valueFormat,
      subTitle,
      total,
      hasLegend = false,
      className,
      style,
      height,
      forceFit = true,
      percent = 0,
      color,
129 130
      inner = 0.75,
      animate = true,
niko's avatar
niko committed
131
      colors,
niko's avatar
niko committed
132
      lineWidth = 1,
nikogu's avatar
nikogu committed
133
    } = this.props;
134

niko's avatar
niko committed
135 136 137 138 139
    const { legendData, legendBlock } = this.state;
    const pieClassName = classNames(styles.pie, className, {
      [styles.hasLegend]: !!hasLegend,
      [styles.legendBlock]: legendBlock,
    });
niko's avatar
niko committed
140

141 142 143 144 145 146
    const { data: d, selected: s, tooltip: t } = this.props;

    let data = d || [];
    let selected = s || true;
    let tooltip = t || true;

niko's avatar
niko committed
147
    const defaultColors = colors;
148 149 150
    // let data = this.props.data || [];
    // let selected = this.props.selected || true;
    // let tooltip = this.props.tooltip || true;
151
    let formatColor;
niko's avatar
niko committed
152 153 154 155 156 157 158 159 160 161 162

    const scale = {
      x: {
        type: 'cat',
        range: [0, 1],
      },
      y: {
        min: 0,
      },
    };

163 164 165
    if (percent) {
      selected = false;
      tooltip = false;
jim's avatar
jim committed
166
      formatColor = value => {
167
        if (value === '占比') {
afc163's avatar
Fix pie  
afc163 committed
168
          return color || 'rgba(24, 144, 255, 0.85)';
169
        } else {
afc163's avatar
Fix pie  
afc163 committed
170
          return '#F0F2F5';
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
        }
      };

      data = [
        {
          x: '占比',
          y: parseFloat(percent),
        },
        {
          x: '反比',
          y: 100 - parseFloat(percent),
        },
      ];
    }

niko's avatar
niko committed
186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    const tooltipFormat = [
      'x*percent',
      (x, p) => ({
        name: x,
        value: `${(p * 100).toFixed(2)}%`,
      }),
    ];

    const padding = [12, 0, 12, 0];

    const dv = new DataView();
    dv.source(data).transform({
      type: 'percent',
      field: 'y',
      dimension: 'x',
      as: 'percent',
偏右's avatar
偏右 committed
202
    });
203 204

    return (
205
      <div ref={this.handleRoot} className={pieClassName} style={style}>
afc163's avatar
afc163 committed
206
        <ReactFitText maxFontSize={25}>
偏右's avatar
偏右 committed
207
          <div className={styles.chart}>
niko's avatar
niko committed
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
            <Chart
              scale={scale}
              height={height}
              forceFit={forceFit}
              data={dv}
              padding={padding}
              animate={animate}
              onGetG2Instance={this.getG2Instance}
            >
              {!!tooltip && <Tooltip showTitle={false} />}
              <Coord type="theta" innerRadius={inner} />
              <Geom
                style={{ lineWidth, stroke: '#fff' }}
                tooltip={tooltip && tooltipFormat}
                type="intervalStack"
                position="percent"
                color={['x', percent ? formatColor : defaultColors]}
                selected={selected}
              />
            </Chart>

            {(subTitle || total) && (
              <div className={styles.total}>
                {subTitle && <h4 className="pie-sub-title">{subTitle}</h4>}
                {/* eslint-disable-next-line */}
niko's avatar
niko committed
233 234 235
                {total && (
                  <div className="pie-stat">{typeof total === 'function' ? total() : total}</div>
                )}
niko's avatar
niko committed
236 237
              </div>
            )}
238
          </div>
偏右's avatar
偏右 committed
239 240
        </ReactFitText>

niko's avatar
niko committed
241 242 243 244 245 246
        {hasLegend && (
          <ul className={styles.legend}>
            {legendData.map((item, i) => (
              <li key={item.x} onClick={() => this.handleLegendClick(item, i)}>
                <span
                  className={styles.dot}
jim's avatar
jim committed
247 248 249
                  style={{
                    backgroundColor: !item.checked ? '#aaa' : item.color,
                  }}
niko's avatar
niko committed
250 251 252
                />
                <span className={styles.legendTitle}>{item.x}</span>
                <Divider type="vertical" />
nikogu's avatar
nikogu committed
253 254 255
                <span className={styles.percent}>
                  {`${(isNaN(item.percent) ? 0 : item.percent * 100).toFixed(2)}%`}
                </span>
niko's avatar
niko committed
256
                <span className={styles.value}>{valueFormat ? valueFormat(item.y) : item.y}</span>
niko's avatar
niko committed
257 258 259 260
              </li>
            ))}
          </ul>
        )}
261 262 263 264
      </div>
    );
  }
}