StackChart.tsx 17.5 KB
Newer Older
P
Peter Pan 已提交
1 2
import * as chart from '~/utils/chart';

3
import type {EChartOption, ECharts, EChartsConvertFinder} from 'echarts';
4
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
P
Peter Pan 已提交
5
import {WithStyled, primaryColor} from '~/utils/style';
6
import useECharts, {Options, Wrapper} from '~/hooks/useECharts';
P
Peter Pan 已提交
7 8 9

import GridLoader from 'react-spinners/GridLoader';
import defaultsDeep from 'lodash/defaultsDeep';
10 11 12 13 14 15 16 17 18 19 20 21
import styled from 'styled-components';
import useThrottleFn from '~/hooks/useThrottleFn';

const Tooltip = styled.div`
    position: absolute;
    z-index: 1;
    background-color: rgba(0, 0, 0, 0.75);
    color: #fff;
    border-radius: 4px;
    padding: 5px;
    display: none;
`;
P
Peter Pan 已提交
22 23 24 25 26 27 28 29 30 31 32

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

33
export type StackChartProps = {
P
Peter Pan 已提交
34 35
    options?: EChartOption;
    title?: string;
36
    data?: Partial<Omit<NonNullable<EChartOption<EChartOption.SeriesCustom>['series']>[number], 'data'>> & {
P
Peter Pan 已提交
37 38 39 40
        minZ: number;
        maxZ: number;
        minX: number;
        maxX: number;
41 42 43
        minY: number;
        maxY: number;
        data: number[][];
P
Peter Pan 已提交
44 45 46
    };
    loading?: boolean;
    zoom?: boolean;
47
    onInit?: Options['onInit'];
P
Peter Pan 已提交
48 49 50 51 52 53 54
};

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

const StackChart = React.forwardRef<StackChartRef, StackChartProps & WithStyled>(
55 56
    ({options, data, title, loading, zoom, className, onInit}, ref) => {
        const {minZ, maxZ, minY, maxY, minX, maxX, ...seriesData} = data ?? {
P
Peter Pan 已提交
57 58
            minZ: 0,
            maxZ: 0,
59 60
            minY: 0,
            maxY: 0,
P
Peter Pan 已提交
61 62 63 64
            minX: 0,
            maxX: 0,
            data: null
        };
65
        const rawData = useMemo(() => seriesData.data ?? [], [seriesData.data]);
66 67

        const negativeY = useMemo(() => minY - (maxY - minY) * 0.4, [minY, maxY]);
P
Peter Pan 已提交
68 69

        const getPoint = useCallback(
70
            (x: number, y: number, z: number, getCoord: GetCoord) => {
P
Peter Pan 已提交
71
                const pt = getCoord([x, y]);
72 73 74 75
                // bug of echarts
                if (!pt) {
                    return [0, 0];
                }
P
Peter Pan 已提交
76
                // linear map in z axis
77
                pt[1] -= ((z - minZ) / (maxZ - minZ)) * (getCoord([0, minY])[1] - getCoord([0, negativeY])[1]);
P
Peter Pan 已提交
78 79
                return pt;
            },
80
            [minZ, maxZ, minY, negativeY]
P
Peter Pan 已提交
81 82 83
        );

        const makePolyPoints = useCallback(
84
            (dataIndex: number, getValue: GetValue, getCoord: GetCoord) => {
P
Peter Pan 已提交
85 86 87 88 89 90
                const points = [];
                let i = 0;
                while (rawData[dataIndex] && i < rawData[dataIndex].length) {
                    const x = getValue(i++);
                    const y = getValue(i++);
                    const z = getValue(i++);
91 92 93 94 95 96 97
                    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 已提交
98 99 100 101 102 103
                }
                return points;
            },
            [getPoint, rawData]
        );

104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
        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]
        );

123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
        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]
        );

153 154 155 156 157 158 159 160 161 162 163 164 165
        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
                    },
166 167 168 169 170
                    axisPointer: {
                        label: {
                            formatter: axisPointerLabelFormatter
                        }
                    },
171 172
                    xAxis: {
                        min: minX,
173 174 175 176
                        max: maxX,
                        axisPointer: {
                            type: 'none'
                        }
177 178 179 180 181 182 183 184 185 186 187
                    },
                    yAxis: {
                        inverse: true,
                        position: 'right',
                        min: negativeY,
                        max: maxY,
                        axisLine: {
                            onZero: false
                        },
                        axisLabel: {
                            formatter: (value: number) => (value < minY ? '' : value + '')
188 189 190
                        },
                        axisPointer: {
                            type: 'none'
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
                        }
                    },
                    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,
                defaults
            );
218
        }, [options, title, rawData, minX, maxX, minY, maxY, negativeY, renderItem, axisPointerLabelFormatter]);
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258

        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;
                        }
                    }
259 260
                    const highlight = step == null ? null : data.findIndex(row => row[1] === step);
                    setHighlight(highlight);
261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286

                    // 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
287
                            highlight == null ? '' : (chartOptions.tooltip?.formatter as any)?.(dots[highlight])
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 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
                        );
                        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 已提交
342
        useEffect(() => {
343
            echart?.setOption(chartOptions, {notMerge: true});
344
        }, [echart, chartOptions]);
P
Peter Pan 已提交
345

346 347 348 349 350 351 352 353 354 355 356 357 358
        useEffect(() => {
            if (echart) {
                try {
                    if (highlight == null) {
                        echart.setOption({
                            graphic: {
                                elements: [
                                    {
                                        id: 'highlight',
                                        type: 'polyline',
                                        $action: 'remove'
                                    }
                                ]
P
Peter Pan 已提交
359
                            }
360 361 362 363 364 365 366 367 368 369 370 371 372
                        });
                    } 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 已提交
373
                                        silent: true,
374 375 376
                                        cursor: 'default',
                                        zlevel: 1,
                                        z: 1,
P
Peter Pan 已提交
377
                                        shape: {
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 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
                                            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 已提交
425
                                        },
426 427 428 429 430
                                        style: {
                                            fill: '#fff',
                                            stroke: chartOptions.color?.[0],
                                            lineWidth: 2
                                        }
P
Peter Pan 已提交
431
                                    };
432
                                })
P
Peter Pan 已提交
433
                            }
434 435 436 437 438
                        });
                    }
                } catch {
                    // ignore
                }
P
Peter Pan 已提交
439
            }
440
        }, [dots, echart, chartOptions.color, getPoint]);
P
Peter Pan 已提交
441 442 443 444 445 446 447 448 449

        return (
            <Wrapper ref={wrapper} className={className}>
                {!echart && (
                    <div className="loading">
                        <GridLoader color={primaryColor} size="10px" />
                    </div>
                )}
                <div className="echarts" ref={echartRef}></div>
450
                <Tooltip className="tooltip" ref={tooltipRef} dangerouslySetInnerHTML={{__html: tooltip}} />
P
Peter Pan 已提交
451 452 453 454 455 456
            </Wrapper>
        );
    }
);

export default StackChart;