index.js 6.64 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 */
afc163's avatar
afc163 committed
14
export default
niko's avatar
niko committed
15
@autoHeight()
afc163's avatar
afc163 committed
16
class Pie extends Component {
17 18
  state = {
    legendData: [],
niko's avatar
niko committed
19
    legendBlock: false,
偏右's avatar
偏右 committed
20
  };
21 22

  componentDidMount() {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
23 24 25
    window.addEventListener(
      'resize',
      () => {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
26
        this.requestRef = requestAnimationFrame(() => this.resize());
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
27 28 29
      },
      { passive: true }
    );
30 31
  }

jim's avatar
jim committed
32
  componentDidUpdate(preProps) {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
33 34
    const { data } = this.props;
    if (data !== preProps.data) {
35 36
      // because of charts data create when rendered
      // so there is a trick for get rendered time
jim's avatar
jim committed
37
      this.getLegendData();
nikogu's avatar
nikogu committed
38
    }
39
  }
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
40

41
  componentWillUnmount() {
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
42
    window.cancelAnimationFrame(this.requestRef);
43
    window.removeEventListener('resize', this.resize);
afc163's avatar
afc163 committed
44
    this.resize.cancel();
45 46
  }

jim's avatar
jim committed
47
  getG2Instance = chart => {
niko's avatar
niko committed
48
    this.chart = chart;
jim's avatar
jim committed
49 50 51 52
    requestAnimationFrame(() => {
      this.getLegendData();
      this.resize();
    });
niko's avatar
niko committed
53 54 55
  };

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

jim's avatar
jim committed
62
    const legendData = items.map(item => {
niko's avatar
niko committed
63 64 65 66 67 68 69 70 71 72 73 74
      /* 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
75
  handleRoot = n => {
76
    this.root = n;
niko's avatar
niko committed
77
  };
78

79 80 81 82
  handleLegendClick = (item, i) => {
    const newItem = item;
    newItem.checked = !newItem.checked;

afc163's avatar
afc163 committed
83
    const { legendData } = this.state;
84 85
    legendData[i] = newItem;

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

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

    this.setState({
      legendData,
    });
niko's avatar
niko committed
95
  };
96

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

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

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

yoyo837's avatar
yoyo837 committed
144 145 146 147 148
    const {
      data: propsData,
      selected: propsSelected = true,
      tooltip: propsTooltip = true,
    } = this.props;
149

yoyo837's avatar
yoyo837 committed
150
    let data = propsData || [];
yoyo837's avatar
yoyo837 committed
151 152
    let selected = propsSelected;
    let tooltip = propsTooltip;
153

niko's avatar
niko committed
154
    const defaultColors = colors;
ι™ˆεΈ…'s avatar
ι™ˆεΈ… committed
155 156 157
    data = data || [];
    selected = selected || true;
    tooltip = tooltip || true;
158
    let formatColor;
niko's avatar
niko committed
159 160 161 162 163 164 165 166 167 168 169

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

170
    if (percent || percent === 0) {
171 172
      selected = false;
      tooltip = false;
jim's avatar
jim committed
173
      formatColor = value => {
174
        if (value === '占比') {
afc163's avatar
Fix pie  
afc163 committed
175
          return color || 'rgba(24, 144, 255, 0.85)';
176
        }
177
        return '#F0F2F5';
178 179 180 181 182 183 184 185 186 187 188 189 190 191
      };

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

niko's avatar
niko committed
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207
    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
208
    });
209 210

    return (
211
      <div ref={this.handleRoot} className={pieClassName} style={style}>
afc163's avatar
afc163 committed
212
        <ReactFitText maxFontSize={25}>
偏右's avatar
偏右 committed
213
          <div className={styles.chart}>
niko's avatar
niko committed
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
            <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"
230
                color={['x', percent || percent === 0 ? formatColor : defaultColors]}
niko's avatar
niko committed
231 232 233 234 235 236 237 238
                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
239 240 241
                {total && (
                  <div className="pie-stat">{typeof total === 'function' ? total() : total}</div>
                )}
niko's avatar
niko committed
242 243
              </div>
            )}
244
          </div>
偏右's avatar
偏右 committed
245 246
        </ReactFitText>

niko's avatar
niko committed
247 248 249 250 251 252
        {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
253 254 255
                  style={{
                    backgroundColor: !item.checked ? '#aaa' : item.color,
                  }}
niko's avatar
niko committed
256 257 258
                />
                <span className={styles.legendTitle}>{item.x}</span>
                <Divider type="vertical" />
nikogu's avatar
nikogu committed
259
                <span className={styles.percent}>
260
                  {`${(Number.isNaN(item.percent) ? 0 : item.percent * 100).toFixed(2)}%`}
nikogu's avatar
nikogu committed
261
                </span>
niko's avatar
niko committed
262
                <span className={styles.value}>{valueFormat ? valueFormat(item.y) : item.y}</span>
niko's avatar
niko committed
263 264 265 266
              </li>
            ))}
          </ul>
        )}
267 268 269 270
      </div>
    );
  }
}