StackChart.tsx 18.4 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

P
Peter Pan 已提交
17 18
import * as chart from '~/utils/chart';

19
import type {EChartOption, ECharts, EChartsConvertFinder} from 'echarts';
20
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
P
Peter Pan 已提交
21 22
import {WithStyled, primaryColor, transitionProps} from '~/utils/style';
import useECharts, {Options, Wrapper, useChartTheme} from '~/hooks/useECharts';
P
Peter Pan 已提交
23 24 25

import GridLoader from 'react-spinners/GridLoader';
import defaultsDeep from 'lodash/defaultsDeep';
26 27 28 29 30 31
import styled from 'styled-components';
import useThrottleFn from '~/hooks/useThrottleFn';

const Tooltip = styled.div`
    position: absolute;
    z-index: 1;
P
Peter Pan 已提交
32 33
    background-color: var(--tooltip-background-color);
    color: var(--tooltip-text-color);
34 35 36
    border-radius: 4px;
    padding: 5px;
    display: none;
P
Peter Pan 已提交
37
    ${transitionProps(['color', 'background-color'])}
38
`;
P
Peter Pan 已提交
39 40 41 42 43 44 45 46 47 48 49

type renderItem = NonNullable<EChartOption.SeriesCustom['renderItem']>;
type renderItemArguments = NonNullable<renderItem['arguments']>;
type RenderItem = (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    params: any,
    api: Required<NonNullable<renderItemArguments['api']>>
) => NonNullable<renderItem['return']>;
type GetValue = (i: number) => number;
type GetCoord = (p: [number, number]) => [number, number];

50
export type StackChartProps = {
P
Peter Pan 已提交
51 52
    options?: EChartOption;
    title?: string;
53
    data?: Partial<Omit<NonNullable<EChartOption<EChartOption.SeriesCustom>['series']>[number], 'data'>> & {
P
Peter Pan 已提交
54 55 56 57
        minZ: number;
        maxZ: number;
        minX: number;
        maxX: number;
58 59 60
        minY: number;
        maxY: number;
        data: number[][];
P
Peter Pan 已提交
61 62 63
    };
    loading?: boolean;
    zoom?: boolean;
64
    onInit?: Options['onInit'];
P
Peter Pan 已提交
65 66 67 68 69 70 71
};

export type StackChartRef = {
    saveAsImage(): void;
};

const StackChart = React.forwardRef<StackChartRef, StackChartProps & WithStyled>(
72 73
    ({options, data, title, loading, zoom, className, onInit}, ref) => {
        const {minZ, maxZ, minY, maxY, minX, maxX, ...seriesData} = data ?? {
P
Peter Pan 已提交
74 75
            minZ: 0,
            maxZ: 0,
76 77
            minY: 0,
            maxY: 0,
P
Peter Pan 已提交
78 79 80 81
            minX: 0,
            maxX: 0,
            data: null
        };
82
        const rawData = useMemo(() => seriesData.data ?? [], [seriesData.data]);
83

84
        const negativeY = useMemo(() => (minY === 0 && maxY === 0 ? -0.4 : minY - (maxY - minY) * 0.4), [minY, maxY]);
P
Peter Pan 已提交
85 86

        const getPoint = useCallback(
87
            (x: number, y: number, z: number, getCoord: GetCoord) => {
P
Peter Pan 已提交
88
                const pt = getCoord([x, y]);
89 90 91 92
                // bug of echarts
                if (!pt) {
                    return [0, 0];
                }
P
Peter Pan 已提交
93
                // linear map in z axis
94
                pt[1] -= ((z - minZ) / (maxZ - minZ)) * (getCoord([0, minY])[1] - getCoord([0, negativeY])[1]);
P
Peter Pan 已提交
95 96
                return pt;
            },
97
            [minZ, maxZ, minY, negativeY]
P
Peter Pan 已提交
98 99 100
        );

        const makePolyPoints = useCallback(
101
            (dataIndex: number, getValue: GetValue, getCoord: GetCoord) => {
P
Peter Pan 已提交
102 103 104 105 106 107
                const points = [];
                let i = 0;
                while (rawData[dataIndex] && i < rawData[dataIndex].length) {
                    const x = getValue(i++);
                    const y = getValue(i++);
                    const z = getValue(i++);
108 109 110 111 112 113 114
                    if (z !== 1 && i === 3) {
                        points.push(getPoint(x, y, 1, getCoord));
                    }
                    points.push(getPoint(x, y, z, getCoord));
                    if (z !== 1 && i === rawData[dataIndex].length) {
                        points.push(getPoint(x, y, 1, getCoord));
                    }
P
Peter Pan 已提交
115 116 117 118 119 120
                }
                return points;
            },
            [getPoint, rawData]
        );

121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
        const renderItem = useCallback<RenderItem>(
            (params, api) => {
                const points = makePolyPoints(params.dataIndex as number, api.value as GetValue, api.coord as GetCoord);
                return {
                    type: 'polygon',
                    silent: true,
                    z: api.value(1),
                    shape: {
                        points
                    },
                    style: api.style({
                        stroke: chart.xAxis.axisLine.lineStyle.color,
                        lineWidth: 1
                    })
                };
            },
            [makePolyPoints]
        );

140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
        const [highlight, setHighlight] = useState<number | null>(null);
        const [dots, setDots] = useState<[number, number, number][]>([]);
        const tooltipRef = useRef<HTMLDivElement | null>(null);
        const [tooltip, setTooltip] = useState('');
        const highLightRef = useRef(highlight);
        const dotsRef = useRef(dots);
        useEffect(() => {
            highLightRef.current = highlight;
        }, [highlight]);
        useEffect(() => {
            dotsRef.current = dots;
        }, [dots]);

        const pointerLabelFormatter = options?.axisPointer?.label?.formatter;

        // formatter change will cause echarts rerender axis pointer label
        // so we need to use 2 refs instead of dots and highlight to get rid of dependencies of these two variables
        const axisPointerLabelFormatter = useCallback(
            params => {
                if (!pointerLabelFormatter || highLightRef.current == null) {
                    return '';
                }
                if ('string' === typeof pointerLabelFormatter) {
                    return pointerLabelFormatter;
                }
                return pointerLabelFormatter(params, dotsRef.current[highLightRef.current]);
            },
            [pointerLabelFormatter]
        );

P
Peter Pan 已提交
170 171
        const theme = useChartTheme();

172 173 174 175 176 177 178 179 180 181 182 183 184
        const chartOptions = useMemo<EChartOption>(() => {
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            const {color, colorAlt, toolbox, series, ...defaults} = chart;

            return defaultsDeep(
                {
                    title: {
                        text: title ?? ''
                    },
                    visualMap: {
                        min: minY,
                        max: maxY
                    },
185 186 187 188 189
                    axisPointer: {
                        label: {
                            formatter: axisPointerLabelFormatter
                        }
                    },
190 191
                    xAxis: {
                        min: minX,
192 193 194 195
                        max: maxX,
                        axisPointer: {
                            type: 'none'
                        }
196 197 198 199 200 201 202 203 204 205 206
                    },
                    yAxis: {
                        inverse: true,
                        position: 'right',
                        min: negativeY,
                        max: maxY,
                        axisLine: {
                            onZero: false
                        },
                        axisLabel: {
                            formatter: (value: number) => (value < minY ? '' : value + '')
207 208 209
                        },
                        axisPointer: {
                            type: 'none'
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
                        }
                    },
                    grid: {
                        left: defaults.grid.right,
                        right: defaults.grid.left
                    },
                    tooltip: {
                        trigger: 'none',
                        showContent: false,
                        axisPointer: {
                            axis: 'y',
                            snap: false
                        }
                    },
                    series: [
                        {
                            ...series,
                            type: 'custom',
                            silent: true,
                            data: rawData,
                            renderItem
                        }
                    ]
                },
                options,
P
Peter Pan 已提交
235
                theme,
236 237
                defaults
            );
P
Peter Pan 已提交
238
        }, [options, title, theme, rawData, minX, maxX, minY, maxY, negativeY, renderItem, axisPointerLabelFormatter]);
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278

        const mouseout = useCallback(() => {
            setHighlight(null);
            setDots([]);
            if (chartOptions.tooltip?.formatter) {
                setTooltip('');
                if (tooltipRef.current) {
                    tooltipRef.current.style.display = 'none';
                }
            }
        }, [chartOptions.tooltip]);

        const mousemove = useCallback(
            (echarts: ECharts, e: {offsetX: number; offsetY: number}) => {
                try {
                    if (!echarts || !e) {
                        return;
                    }

                    const {offsetX, offsetY} = e;
                    if (offsetY < negativeY + ((chartOptions.grid as EChartOption.Grid).top as number) ?? 0) {
                        mouseout();
                        return;
                    }
                    const [x, y] = echarts.convertFromPixel('grid' as EChartsConvertFinder, [offsetX, offsetY]) as [
                        number,
                        number
                    ];
                    const data = (echarts.getOption().series?.[0].data as number[][]) ?? [];

                    // find right on top step
                    const steps = data.map(row => row[1]).sort((a, b) => a - b);
                    let i = 0;
                    let step: number | null = null;
                    while (i < steps.length) {
                        if (y <= steps[i++]) {
                            step = steps[i - 1];
                            break;
                        }
                    }
279 280
                    const highlight = step == null ? null : data.findIndex(row => row[1] === step);
                    setHighlight(highlight);
281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306

                    // find nearest x axis point
                    let dots: [number, number, number][] = [];
                    if (step == null) {
                        setDots(dots);
                    } else {
                        dots = data.map(row => {
                            const pt: [number, number, number] = [row[0], row[1], row[2]];
                            let d = Number.POSITIVE_INFINITY;
                            for (let j = 0; j < row.length; j += 3) {
                                const d1 = Math.abs(row[j] - x);
                                if (d1 < d) {
                                    d = d1;
                                    pt[0] = row[j];
                                    pt[2] = row[j + 2];
                                }
                            }
                            return pt;
                        });
                        setDots(dots);
                    }

                    // set tooltip
                    if (chartOptions.tooltip?.formatter) {
                        setTooltip(
                            // eslint-disable-next-line @typescript-eslint/no-explicit-any
307
                            highlight == null ? '' : (chartOptions.tooltip?.formatter as any)?.(dots[highlight])
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
                        );
                        if (tooltipRef.current) {
                            if (step == null) {
                                tooltipRef.current.style.display = 'none';
                            } else {
                                tooltipRef.current.style.left = `${offsetX + 10}px`;
                                tooltipRef.current.style.top = `${offsetY + 10}px`;
                                tooltipRef.current.style.display = 'block';
                            }
                        }
                    }
                } catch {
                    mouseout();
                }
            },
            [mouseout, negativeY, chartOptions.grid, chartOptions.tooltip]
        );

        const throttled = useThrottleFn(mousemove, {wait: 200});

        const init = useCallback<NonNullable<Options['onInit']>>(
            echarts => {
                try {
                    // eslint-disable-next-line @typescript-eslint/no-explicit-any
                    const zr = (echarts as any).getZr();
                    if (zr) {
                        zr.on('mousemove', (e: {offsetX: number; offsetY: number}) => throttled.run(echarts, e));

                        zr.on('mouseout', () => {
                            throttled.cancel();
                            mouseout();
                        });
                    }
                } catch {
                    throttled.cancel();
                }
                onInit?.(echarts);
            },
            [onInit, throttled, mouseout]
        );

        const {ref: echartRef, echart, wrapper, saveAsImage} = useECharts<HTMLDivElement>({
            loading: !!loading,
            zoom,
            autoFit: true,
            onInit: init
        });

        useImperativeHandle(ref, () => ({
            saveAsImage: () => {
                saveAsImage(title);
            }
        }));

P
Peter Pan 已提交
362
        useEffect(() => {
363
            echart?.setOption(chartOptions, {notMerge: true});
364
        }, [echart, chartOptions]);
P
Peter Pan 已提交
365

366 367 368 369 370 371 372 373 374 375 376 377 378
        useEffect(() => {
            if (echart) {
                try {
                    if (highlight == null) {
                        echart.setOption({
                            graphic: {
                                elements: [
                                    {
                                        id: 'highlight',
                                        type: 'polyline',
                                        $action: 'remove'
                                    }
                                ]
P
Peter Pan 已提交
379
                            }
380 381 382 383 384 385 386 387 388 389 390 391 392
                        });
                    } else {
                        const data = (echart.getOption().series?.[0].data as number[][]) ?? [];
                        const getCoord: GetCoord = pt =>
                            echart.convertToPixel('grid' as EChartsConvertFinder, pt) as [number, number];
                        const getValue: GetValue = i => data[highlight][i];
                        echart.setOption({
                            graphic: {
                                elements: [
                                    {
                                        id: 'highlight',
                                        type: 'polyline',
                                        $action: 'replace',
P
Peter Pan 已提交
393
                                        silent: true,
394 395 396
                                        cursor: 'default',
                                        zlevel: 1,
                                        z: 1,
P
Peter Pan 已提交
397
                                        shape: {
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
                                            points: makePolyPoints(highlight, getValue, getCoord)
                                        }
                                    }
                                ]
                            }
                        });
                    }
                } catch {
                    // ignore
                }
            }
        }, [highlight, echart, makePolyPoints]);

        useEffect(() => {
            if (echart) {
                try {
                    if (!dots.length) {
                        echart.setOption({
                            graphic: {
                                // eslint-disable-next-line @typescript-eslint/no-explicit-any
                                elements: ((echart.getOption()?.graphic as any[])?.[0]?.elements as any[])
                                    ?.filter(element => (element.id as string).startsWith('dot'))
                                    .map(element => ({
                                        id: element.id,
                                        type: 'circle',
                                        $action: 'remove'
                                    }))
                            }
                        });
                    } else {
                        const getCoord: GetCoord = pt =>
                            echart.convertToPixel('grid' as EChartsConvertFinder, pt) as [number, number];
                        echart.setOption({
                            graphic: {
                                elements: dots.map((dot, i) => {
                                    const pt = getPoint(dot[0], dot[1], dot[2], getCoord);
                                    return {
                                        type: 'circle',
                                        id: `dot${i}`,
                                        $action: 'replace',
                                        cursor: 'default',
                                        zlevel: 1,
                                        z: 2,
                                        shape: {
                                            cx: pt[0],
                                            cy: pt[1],
                                            r: 3
P
Peter Pan 已提交
445
                                        },
446 447 448 449 450
                                        style: {
                                            fill: '#fff',
                                            stroke: chartOptions.color?.[0],
                                            lineWidth: 2
                                        }
P
Peter Pan 已提交
451
                                    };
452
                                })
P
Peter Pan 已提交
453
                            }
454 455 456 457 458
                        });
                    }
                } catch {
                    // ignore
                }
P
Peter Pan 已提交
459
            }
460
        }, [dots, echart, chartOptions.color, getPoint]);
P
Peter Pan 已提交
461 462 463 464 465 466 467 468 469

        return (
            <Wrapper ref={wrapper} className={className}>
                {!echart && (
                    <div className="loading">
                        <GridLoader color={primaryColor} size="10px" />
                    </div>
                )}
                <div className="echarts" ref={echartRef}></div>
470
                <Tooltip className="tooltip" ref={tooltipRef} dangerouslySetInnerHTML={{__html: tooltip}} />
P
Peter Pan 已提交
471 472 473 474 475 476
            </Wrapper>
        );
    }
);

export default StackChart;