graphs.tsx 9.3 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 21 22 23 24 25 26 27 28 29 30 31 32
const dumbFn = () => {};

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

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

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

41 42 43
const RangeSlider = styled(RawRangeSlider)`
    width: 100%;
`;
44

45 46 47 48 49 50 51 52 53 54
const GraphSvg = styled('svg')`
    width: 100%;

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

    .node {
        cursor: pointer;
55 56 57 58 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

        .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;
            }
        }
90 91 92 93 94 95 96 97 98 99 100 101 102 103
    }

    .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({
104 105 106
        detail: false,
        input: false,
        output: false
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
    });
    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
    };
};

143
const useDagreD3 = (graph?: Graph) => {
144 145 146 147 148 149 150 151 152 153 154 155 156
    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;
            }

157
            const g = new dagre.graphlib.Graph<{type: NodeType; elem: HTMLElement}>();
158 159 160 161 162 163
            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();
164
            const svg = d3.select<HTMLElement, any>('svg'); // eslint-disable-line @typescript-eslint/no-explicit-any
165 166 167 168 169 170 171
            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));

172 173
            const zoom = d3
                .zoom<HTMLElement, any>() // eslint-disable-line @typescript-eslint/no-explicit-any
174
                .scaleExtent([MIN_SCALE, MAX_SCALE])
175
                .on('zoom', function () {
176 177 178 179 180 181 182
                    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);

183
            let prevDom: HTMLElement | undefined;
184 185 186
            // install event listeners
            svg.selectAll('g.node').on('click', v => {
                const uid = v as string;
187 188 189 190 191 192 193 194
                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) {
195 196 197 198
                    setCurrentNode({type: 'unknown', guessType: type, msg: uid});
                    return;
                }

199
                setCurrentNode({...node, type} as TypedNode);
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 242 243 244 245 246 247 248 249 250 251 252
            });

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

253
const Graphs: NextI18NextPage = () => {
254
    const {t} = useTranslation(['graphs', 'common']);
255 256 257
    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);
258 259 260 261 262

    const aside = (
        <section>
            <SubSection>
                <Button icon="download" onClick={downloadImage}>
263
                    {t('download-image')}
264 265
                </Button>
                <Button icon="revert" onClick={fitScreen}>
266
                    {t('restore-image')}
267 268 269 270
                </Button>
            </SubSection>

            <SubSection>
271
                <Field label={`${t('scale')}:`}>
272 273 274 275 276
                    <RangeSlider min={MIN_SCALE} max={MAX_SCALE} step={0.1} value={scale} onChange={setScale} />
                </Field>
            </SubSection>

            <SubSection>
277 278
                <Field label={`${t('node-info')}:`} />
                <NodeInfo node={currentNode} />
279 280 281 282
            </SubSection>
        </section>
    );

283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
    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]);

300 301
    return (
        <>
P
Peter Pan 已提交
302
            <Preloader url="/graphs/graph" />
303 304
            <Title>{t('common:graphs')}</Title>

305 306
            <Content aside={aside} loading={loading}>
                {ContentInner}
307 308 309 310 311
            </Content>
        </>
    );
};

312 313 314 315
Graphs.getInitialProps = () => ({
    namespacesRequired: ['graphs', 'common']
});

316
export default Graphs;