graphs.tsx 8.6 KB
Newer Older
1 2 3
import React, {useState, useEffect, useMemo} from 'react';
import useSWR from 'swr';
import styled from 'styled-components';
P
Peter Pan 已提交
4 5
import {saveSvgAsPng} from 'save-svg-as-png';
import {rem} from '~/utils/style';
6 7 8 9 10
import RawButton from '~/components/Button';
import RawRangeSlider from '~/components/RangeSlider';
import Content from '~/components/Content';
import Title from '~/components/Title';
import Field from '~/components/Field';
11
import {useTranslation, NextI18NextPage} from '~/utils/i18n';
12
import NodeInfo, {NodeInfoProps} from '~/components/GraphPage/NodeInfo';
P
Peter Pan 已提交
13
import Preloader from '~/components/Preloader';
14 15
import {Graph, collectDagFacts} from '~/resource/graph';

16
// eslint-disable-next-line @typescript-eslint/no-empty-function
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
const dumbFn = () => {};

const SubSection = styled.div`
    margin-bottom: ${rem(30)};
`;
const Button = styled(RawButton)`
    width: 100%;
    text-transform: uppercase;

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

const RangeSlider = styled(RawRangeSlider)`
    width: 100%;
`;
const GraphSvg = styled('svg')`
    width: 100%;

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

    .node {
        cursor: pointer;
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78

        .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;
            }
        }
79 80 81 82 83 84 85 86 87 88 89 90 91 92
    }

    .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({
93 94 95
        detail: false,
        input: false,
        output: false
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 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 147 148 149 150 151 152
    });
    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
    };
};

const useDagreD3 = (graph: Graph | undefined) => {
    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;
            }

            const g = new dagre.graphlib.Graph();
            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();
153
            const svg = d3.select<HTMLElement, any>('svg'); // eslint-disable-line @typescript-eslint/no-explicit-any
154 155 156 157 158 159 160
            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));

161 162
            const zoom = d3
                .zoom<HTMLElement, any>() // eslint-disable-line @typescript-eslint/no-explicit-any
163 164 165 166 167 168 169 170 171
                .scaleExtent([MIN_SCALE, MAX_SCALE])
                .on('zoom', function() {
                    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);

172
            let prevDom: HTMLElement | undefined;
173 174 175
            // install event listeners
            svg.selectAll('g.node').on('click', v => {
                const uid = v as string;
176 177 178 179 180 181 182 183
                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) {
184 185 186 187
                    setCurrentNode({type: 'unknown', guessType: type, msg: uid});
                    return;
                }

188
                setCurrentNode({...node, type});
189 190 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 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
            });

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

242
const Graphs: NextI18NextPage = () => {
243
    const {t} = useTranslation(['graphs', 'common']);
P
Peter Pan 已提交
244
    const {data: graph} = useSWR<{data: Graph}>('/graphs/graph');
245 246 247 248 249 250
    const {currentNode, downloadImage, fitScreen, scale, setScale} = useDagreD3(graph ? graph.data : undefined);

    const aside = (
        <section>
            <SubSection>
                <Button icon="download" onClick={downloadImage}>
251
                    {t('download-image')}
252 253
                </Button>
                <Button icon="revert" onClick={fitScreen}>
254
                    {t('restore-image')}
255 256 257 258
                </Button>
            </SubSection>

            <SubSection>
259
                <Field label={`${t('scale')}:`}>
260 261 262 263 264
                    <RangeSlider min={MIN_SCALE} max={MAX_SCALE} step={0.1} value={scale} onChange={setScale} />
                </Field>
            </SubSection>

            <SubSection>
265
                <Field label={`${t('node-info')}:`}></Field>
266 267 268 269 270 271 272
                <NodeInfo node={currentNode}></NodeInfo>
            </SubSection>
        </section>
    );

    return (
        <>
P
Peter Pan 已提交
273
            <Preloader url="/graphs/graph" />
274 275
            <Title>{t('common:graphs')}</Title>

P
Peter Pan 已提交
276
            <Content aside={aside} loading={!graph}>
277 278 279 280 281 282 283 284
                <GraphSvg>
                    <g></g>
                </GraphSvg>
            </Content>
        </>
    );
};

285 286 287 288
Graphs.getInitialProps = () => ({
    namespacesRequired: ['graphs', 'common']
});

289
export default Graphs;