graphs.tsx 8.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
import React, {useState, useEffect, useMemo} from 'react';
import useSWR from 'swr';
import styled from 'styled-components';
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';
import {useTranslation, NextI18NextPage} from '~/utils/i18n';
import {rem} from '~/utils/style';
import {fetcher} from '~/utils/fetch';
import NodeInfo, {NodeInfoProps} from '~/components/GraphPage/NodeInfo';
import {Graph, collectDagFacts} from '~/resource/graph';
import {saveSvgAsPng} from 'save-svg-as-png';

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
// eslint-disable-next-line @typescript-eslint/no-empty-interface
243 244 245 246 247 248 249 250 251 252
interface GraphsProps {}
const Graphs: NextI18NextPage<GraphsProps> = () => {
    const {t} = useTranslation(['graphs', 'common']);
    const {data: graph} = useSWR<{data: Graph}>('/graphs/graph', fetcher);
    const {currentNode, downloadImage, fitScreen, scale, setScale} = useDagreD3(graph ? graph.data : undefined);

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

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

            <SubSection>
267
                <Field label={`${t('node-info')}:`}></Field>
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
                <NodeInfo node={currentNode}></NodeInfo>
            </SubSection>
        </section>
    );

    return (
        <>
            <Title>{t('common:graphs')}</Title>

            <Content aside={aside}>
                <GraphSvg>
                    <g></g>
                </GraphSvg>
            </Content>
        </>
    );
};

Graphs.getInitialProps = () => {
    return {
        namespacesRequired: ['graphs', 'common']
    };
};

export default Graphs;