graphs.tsx 9.5 KB
Newer Older
1
import {Graph, NodeType, TypedNode, collectDagFacts} from '~/resource/graphs';
2 3 4 5
import {NextI18NextPage, useTranslation} from '~/utils/i18n';
import NodeInfo, {NodeInfoProps} from '~/components/GraphsPage/NodeInfo';
import React, {useEffect, useMemo, useState} from 'react';

6 7
import Content from '~/components/Content';
import Field from '~/components/Field';
P
Peter Pan 已提交
8
import Preloader from '~/components/Preloader';
9 10 11 12 13 14 15 16
import RawButton from '~/components/Button';
import RawRangeSlider from '~/components/RangeSlider';
import Title from '~/components/Title';
import isEmpty from 'lodash/isEmpty';
import {rem} from '~/utils/style';
import {saveSvgAsPng} from 'save-svg-as-png';
import styled from 'styled-components';
import useRequest from '~/hooks/useRequest';
17

18
// eslint-disable-next-line @typescript-eslint/no-empty-function
19 20
const dumbFn = () => {};

21 22 23 24
const AsideSection = styled.section`
    padding: ${rem(20)};
`;

25 26 27 28 29 30 31 32 33 34 35 36
const SubSection = styled.div`
    margin-bottom: ${rem(30)};
`;
const Button = styled(RawButton)`
    width: 100%;
    text-transform: uppercase;

    & + & {
        margin-top: ${rem(20)};
    }
`;

37 38 39 40 41 42 43 44
const Empty = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: ${rem(20)};
    height: ${rem(150)};
`;

45 46 47
const RangeSlider = styled(RawRangeSlider)`
    width: 100%;
`;
48

49 50 51 52 53 54 55 56 57 58
const GraphSvg = styled('svg')`
    width: 100%;

    cursor: grab;
    &.grabbing {
        cursor: grabbing;
    }

    .node {
        cursor: pointer;
59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

        .label-container {
            stroke-width: 3px;
            stroke: #e6e6e6;
            &.rect {
                rx: 10;
                ry: 10;
            }
        }

        &.operator {
            .label-container {
                fill: #cdd9da;
            }
        }

        &.output {
            .label-container {
                stroke-dasharray: 5, 5;
                stroke: #e6e6e6;
                fill: #cad2d0;
            }
        }

        &.input {
            .label-container {
                fill: #d5d3d8;
            }
        }

        &.active {
            .label-container {
                stroke: #25c9ff;
            }
        }
94 95 96 97 98 99 100 101 102 103 104 105 106 107
    }

    .edgePath path.path {
        stroke: #333;
        stroke-width: 1.5px;
    }
`;

const loadDagLibs = [import('d3'), import('dagre-d3')] as const;
const MIN_SCALE = 0.1;
const MAX_SCALE = 4;

const useDag = (graph?: Graph) => {
    const [displaySwitch, setDisplaySwitch] = useState({
108 109 110
        detail: false,
        input: false,
        output: false
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
    });
    const facts = useMemo(() => collectDagFacts(graph), [graph]);

    const dagInfo = useMemo(() => {
        const {inputLayer, outputLayer, briefLayer, detailLayer, findNode} = facts;

        const availableLayers = displaySwitch.detail ? [detailLayer] : [briefLayer];
        if (displaySwitch.input) {
            availableLayers.push(inputLayer);
        }
        if (displaySwitch.output) {
            availableLayers.push(outputLayer);
        }

        return {
            ...availableLayers.reduce(
                (memo, {nodes, edges}) => ({
                    nodes: memo.nodes.concat(nodes),
                    edges: memo.edges.concat(edges)
                }),
                {
                    nodes: [],
                    edges: []
                }
            ),
            findNode
        };
    }, [facts, displaySwitch]);

    return {
        dagInfo,
        displaySwitch,
        setDisplaySwitch
    };
};

147
const useDagreD3 = (graph?: Graph) => {
148 149 150 151 152 153 154 155 156 157 158 159 160
    const [currentNode, setCurrentNode] = useState<NodeInfoProps['node']>(undefined);
    const {dagInfo, displaySwitch, setDisplaySwitch} = useDag(graph);
    const [downloadImage, setDownloadImageFn] = useState<() => void>(() => dumbFn);
    const [fitScreen, setFitScreenFn] = useState<() => void>(() => dumbFn);
    const [scale, setScaleValue] = useState(1);
    const [setScale, setScaleFn] = useState<(n: number) => void>(() => dumbFn);

    useEffect(() => {
        Promise.all(loadDagLibs).then(([d3, {default: dagre}]) => {
            if (!dagInfo.nodes.length || !dagInfo.edges.length) {
                return;
            }

161
            const g = new dagre.graphlib.Graph<{type: NodeType; elem: HTMLElement}>();
162 163 164 165 166 167
            g.setGraph({}).setDefaultEdgeLabel(() => ({}));

            dagInfo.nodes.forEach(n => g.setNode(n.key, n));
            dagInfo.edges.forEach(e => g.setEdge(e[0], e[1]));

            const render = new dagre.render();
168
            const svg = d3.select<HTMLElement, any>('svg'); // eslint-disable-line @typescript-eslint/no-explicit-any
169 170 171 172 173 174 175
            const inner = svg.select('svg g');
            render(inner, g);

            const {width, height} = g.graph();
            const scaleFactor = 1;
            svg.attr('height', Math.max(640, window.innerHeight + 40));

176 177
            const zoom = d3
                .zoom<HTMLElement, any>() // eslint-disable-line @typescript-eslint/no-explicit-any
178
                .scaleExtent([MIN_SCALE, MAX_SCALE])
179
                .on('zoom', function () {
180 181 182 183 184 185 186
                    setScaleValue(d3.event.transform.k / scaleFactor);
                    inner.attr('transform', d3.event.transform);
                })
                .on('start', () => svg.classed('grabbing', true))
                .on('end', () => svg.classed('grabbing', false));
            svg.call(zoom);

187
            let prevDom: HTMLElement | undefined;
188 189 190
            // install event listeners
            svg.selectAll('g.node').on('click', v => {
                const uid = v as string;
191 192 193 194 195 196 197 198
                const {type, elem: dom} = g.node(uid);
                if (prevDom) {
                    prevDom.classList.remove('active');
                }
                dom.classList.add('active');
                prevDom = dom;
                const node = dagInfo.findNode(type, uid);
                if (!node) {
199 200 201 202
                    setCurrentNode({type: 'unknown', guessType: type, msg: uid});
                    return;
                }

203
                setCurrentNode({...node, type} as TypedNode);
204 205 206 207 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 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
            });

            const fitScreen = () => {
                if (!svg) {
                    return;
                }

                const parent = svg.node()?.parentElement;
                if (!parent) {
                    return;
                }

                const {width: parentWidth} = parent.getBoundingClientRect();
                svg.call(
                    zoom.transform,
                    d3.zoomIdentity.translate((parentWidth - (width ?? 0) * scaleFactor) / 2, 20).scale(scaleFactor)
                );
            };
            fitScreen();

            setFitScreenFn(() => fitScreen);

            setDownloadImageFn(() => {
                let processing = false;
                return async () => {
                    if (processing) {
                        return;
                    }

                    processing = true;
                    fitScreen();
                    const svgNode = svg.node();
                    if (!svgNode) {
                        return;
                    }
                    const originalHeight = +svg.attr('height');
                    svg.attr('height', (height ?? 0) + 40);
                    await saveSvgAsPng(svgNode, 'graph.png');
                    svg.attr('height', originalHeight);
                    processing = false;
                };
            });

            setScaleFn(() => (n: number) => {
                zoom.scaleTo(svg, scaleFactor * n);
                setScaleValue(n);
            });
        });
    }, [dagInfo]);

    return {currentNode, displaySwitch, setDisplaySwitch, downloadImage, fitScreen, scale, setScale};
};

257
const Graphs: NextI18NextPage = () => {
258
    const {t} = useTranslation(['graphs', 'common']);
259 260 261
    const {data, error, loading} = useRequest<{data: Graph}>('/graphs/graph');
    const graph = useMemo(() => (loading || isEmpty(data?.data) ? undefined : data?.data), [loading, data]);
    const {currentNode, downloadImage, fitScreen, scale, setScale} = useDagreD3(graph);
262 263

    const aside = (
264
        <AsideSection>
265
            <SubSection>
266
                <Button rounded type="primary" icon="download" onClick={downloadImage}>
P
Peter Pan 已提交
267
                    {t('graphs:download-image')}
268
                </Button>
269
                <Button rounded type="primary" icon="revert" onClick={fitScreen}>
P
Peter Pan 已提交
270
                    {t('graphs:restore-image')}
271 272 273 274
                </Button>
            </SubSection>

            <SubSection>
P
Peter Pan 已提交
275
                <Field label={`${t('graphs:scale')}:`}>
276 277 278 279 280
                    <RangeSlider min={MIN_SCALE} max={MAX_SCALE} step={0.1} value={scale} onChange={setScale} />
                </Field>
            </SubSection>

            <SubSection>
P
Peter Pan 已提交
281
                <Field label={`${t('graphs:node-info')}:`} />
282
                <NodeInfo node={currentNode} />
283
            </SubSection>
284
        </AsideSection>
285 286
    );

287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
    const ContentInner = useMemo(() => {
        if (loading) {
            return null;
        }
        if (error) {
            return <Empty>{t('common:error')}</Empty>;
        }
        if (!graph) {
            return <Empty>{t('common:empty')}</Empty>;
        }
        return (
            <GraphSvg>
                <g></g>
            </GraphSvg>
        );
    }, [loading, error, graph, t]);

304 305
    return (
        <>
P
Peter Pan 已提交
306
            <Preloader url="/graphs/graph" />
307 308
            <Title>{t('common:graphs')}</Title>

309 310
            <Content aside={aside} loading={loading}>
                {ContentInner}
311 312 313 314 315
            </Content>
        </>
    );
};

316 317 318 319
Graphs.getInitialProps = () => ({
    namespacesRequired: ['graphs', 'common']
});

320
export default Graphs;