Graph.tsx 8.5 KB
Newer Older
P
Peter Pan 已提交
1 2
import {Documentation, Properties, SearchItem, SearchResult} from '~/resource/graphs/types';
import React, {useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState} from 'react';
3
import {backgroundColor, borderColor, contentHeight, position, primaryColor, rem, size} from '~/utils/style';
P
Peter Pan 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38

import ChartToolbox from '~/components/ChartToolbox';
import HashLoader from 'react-spinners/HashLoader';
import styled from 'styled-components';
import {useTranslation} from '~/utils/i18n';

const toolboxHeight = rem(40);

const Wrapper = styled.div`
    position: relative;
    height: ${contentHeight};
    background-color: ${backgroundColor};
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
`;

const RenderContent = styled.div<{show: boolean}>`
    position: absolute;
    top: 0;
    left: 0;
    ${size('100%', '100%')}
    opacity: ${props => (props.show ? 1 : 0)};
    z-index: ${props => (props.show ? 0 : -1)};
    pointer-events: ${props => (props.show ? 'auto' : 'none')};
`;

const Toolbox = styled(ChartToolbox)`
    height: ${toolboxHeight};
    border-bottom: 1px solid ${borderColor};
    padding: 0 ${rem(20)};
`;

const Content = styled.div`
39
    position: relative;
P
Peter Pan 已提交
40 41 42 43 44 45
    height: calc(100% - ${toolboxHeight});

    > iframe {
        ${size('100%', '100%')}
        border: none;
    }
46 47 48 49 50 51 52 53 54 55 56 57 58 59

    > .powered-by {
        display: block;
        ${position('absolute', null, null, rem(20), rem(30))}
        color: #ddd;
        font-size: ${rem(14)};
        user-select: none;

        img {
            height: 1em;
            opacity: 0.5;
            vertical-align: middle;
        }
    }
P
Peter Pan 已提交
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 94 95 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 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 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
`;

const Loading = styled.div`
    ${size('100%', '100%')}
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overscroll-behavior: none;
    cursor: progress;
    font-size: ${rem(16)};
    line-height: ${rem(60)};
`;

export type GraphRef = {
    export(type: 'svg' | 'png'): void;
    search(value: string): void;
    select(item: SearchItem): void;
    showModelProperties(): void;
    showNodeDocumentation: (data: Properties) => void;
};

type GraphProps = {
    files: FileList | null;
    uploader: JSX.Element;
    showAttributes: boolean;
    showInitializers: boolean;
    showNames: boolean;
    onRendered?: () => unknown;
    onSearch?: (data: SearchResult) => unknown;
    onShowModelProperties?: (data: Properties) => unknown;
    onShowNodeProperties?: (data: Properties) => unknown;
    onShowNodeDocumentation?: (data: Documentation) => unknown;
};

const Graph = React.forwardRef<GraphRef, GraphProps>(
    (
        {
            files,
            uploader,
            showAttributes,
            showInitializers,
            showNames,
            onRendered,
            onSearch,
            onShowModelProperties,
            onShowNodeProperties,
            onShowNodeDocumentation
        },
        ref
    ) => {
        const {t} = useTranslation('graphs');

        const [ready, setReady] = useState(false);
        const [loading, setLoading] = useState(false);
        const [rendered, setRendered] = useState(false);

        const iframe = useRef<HTMLIFrameElement>(null);
        const handler = useCallback(
            (event: MessageEvent) => {
                if (event.data) {
                    const {type, data} = event.data;
                    switch (type) {
                        case 'status':
                            switch (data) {
                                case 'ready':
                                    return setReady(true);
                                case 'loading':
                                    return setLoading(true);
                                case 'rendered':
                                    setLoading(false);
                                    setRendered(true);
                                    onRendered?.();
                                    return;
                            }
                            return;
                        case 'search':
                            return onSearch?.(data);
                        case 'show-model-properties':
                            return onShowModelProperties?.(data);
                        case 'show-node-properties':
                            return onShowNodeProperties?.(data);
                        case 'show-node-documentation':
                            return onShowNodeDocumentation?.(data);
                    }
                }
            },
            [onRendered, onSearch, onShowModelProperties, onShowNodeProperties, onShowNodeDocumentation]
        );
        useEffect(() => {
            if (process.browser) {
                window.addEventListener('message', handler);
                return () => window.removeEventListener('message', handler);
            }
        }, [handler]);

        const dispatch = useCallback((type: string, data?: unknown) => {
            if (process.browser) {
                iframe.current?.contentWindow?.postMessage(
                    {
                        type,
                        data
                    },
                    `${window.location.protocol}//${window.location.host}`
                );
            }
        }, []);

        useEffect(() => dispatch('change-files', files), [dispatch, files]);
        useEffect(() => dispatch('toggle-attributes', showAttributes), [dispatch, showAttributes]);
        useEffect(() => dispatch('toggle-initializers', showInitializers), [dispatch, showInitializers]);
        useEffect(() => dispatch('toggle-names', showNames), [dispatch, showNames]);

        useImperativeHandle(ref, () => ({
            export(type) {
                dispatch('export', type);
            },
            search(value) {
                dispatch('search', value);
            },
            select(item) {
                dispatch('select', item);
            },
            showModelProperties() {
                dispatch('show-model-properties');
            },
            showNodeDocumentation(data) {
                dispatch('show-node-documentation', data);
            }
        }));

        const content = useMemo(() => {
            if (!ready || loading) {
                return (
                    <Loading>
                        <HashLoader size="60px" color={primaryColor} />
                    </Loading>
                );
            }
            if (ready && !rendered) {
                return uploader;
            }
            return null;
        }, [ready, loading, rendered, uploader]);

        return (
            <Wrapper>
                {content}
                <RenderContent show={!loading && rendered}>
                    <Toolbox
                        items={[
                            {
                                icon: 'restore-size',
                                tooltip: t('graphs:restore-size'),
                                onClick: () => dispatch('zoom-reset')
                            },
                            {
                                icon: 'zoom-out',
                                tooltip: t('graphs:zoom-out'),
                                onClick: () => dispatch('zoom-out')
                            },
                            {
                                icon: 'zoom-in',
                                tooltip: t('graphs:zoom-in'),
                                onClick: () => dispatch('zoom-in')
                            }
                        ]}
                        reversed
                        tooltipPlace="bottom"
                    />
                    <Content>
                        <iframe
                            ref={iframe}
233
                            src={`${process.env.PUBLIC_PATH ?? ''}/_next/static/netron/index.html`}
P
Peter Pan 已提交
234 235 236 237 238
                            frameBorder={0}
                            scrolling="no"
                            marginWidth={0}
                            marginHeight={0}
                        ></iframe>
239 240 241 242 243 244 245 246
                        <a
                            className="powered-by"
                            href="https://github.com/lutzroeder/netron"
                            target="_blank"
                            rel="noreferrer"
                        >
                            Powered by <img src={`${process.env.PUBLIC_PATH ?? ''}/images/netron.png`} alt="netron" />
                        </a>
P
Peter Pan 已提交
247 248 249 250 251 252 253 254 255 256
                    </Content>
                </RenderContent>
            </Wrapper>
        );
    }
);

Graph.displayName = 'Graph';

export default Graph;