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
// cSpell:words coord zlevel

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

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

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

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

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];

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

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

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

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

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

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

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
        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]
        );

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 170 171
        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 已提交
172 173
        const theme = useChartTheme();

174 175 176 177 178 179 180 181 182 183 184 185 186
        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
                    },
187 188 189 190 191
                    axisPointer: {
                        label: {
                            formatter: axisPointerLabelFormatter
                        }
                    },
192 193
                    xAxis: {
                        min: minX,
194 195 196 197
                        max: maxX,
                        axisPointer: {
                            type: 'none'
                        }
198 199 200 201 202 203 204 205 206 207 208
                    },
                    yAxis: {
                        inverse: true,
                        position: 'right',
                        min: negativeY,
                        max: maxY,
                        axisLine: {
                            onZero: false
                        },
                        axisLabel: {
                            formatter: (value: number) => (value < minY ? '' : value + '')
209 210 211
                        },
                        axisPointer: {
                            type: 'none'
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
                        }
                    },
                    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 已提交
237
                theme,
238 239
                defaults
            );
P
Peter Pan 已提交
240
        }, [options, title, theme, rawData, minX, maxX, minY, maxY, negativeY, renderItem, axisPointerLabelFormatter]);
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 279 280

        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;
                        }
                    }
281 282
                    const highlight = step == null ? null : data.findIndex(row => row[1] === step);
                    setHighlight(highlight);
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308

                    // 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
309
                            highlight == null ? '' : (chartOptions.tooltip?.formatter as any)?.(dots[highlight])
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 362 363
                        );
                        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 已提交
364
        useEffect(() => {
365
            echart?.setOption(chartOptions, {notMerge: true});
366
        }, [echart, chartOptions]);
P
Peter Pan 已提交
367

368 369 370 371 372 373 374 375 376 377 378 379 380
        useEffect(() => {
            if (echart) {
                try {
                    if (highlight == null) {
                        echart.setOption({
                            graphic: {
                                elements: [
                                    {
                                        id: 'highlight',
                                        type: 'polyline',
                                        $action: 'remove'
                                    }
                                ]
P
Peter Pan 已提交
381
                            }
382 383 384 385 386 387 388 389 390 391 392 393 394
                        });
                    } 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 已提交
395
                                        silent: true,
396 397 398
                                        cursor: 'default',
                                        zlevel: 1,
                                        z: 1,
P
Peter Pan 已提交
399
                                        shape: {
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 445 446
                                            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 已提交
447
                                        },
448 449 450 451 452
                                        style: {
                                            fill: '#fff',
                                            stroke: chartOptions.color?.[0],
                                            lineWidth: 2
                                        }
P
Peter Pan 已提交
453
                                    };
454
                                })
P
Peter Pan 已提交
455
                            }
456 457 458 459 460
                        });
                    }
                } catch {
                    // ignore
                }
P
Peter Pan 已提交
461
            }
462
        }, [dots, echart, chartOptions.color, getPoint]);
P
Peter Pan 已提交
463 464 465 466 467 468 469 470 471

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

export default StackChart;