graphStatic3.tsx 17.6 KB
Newer Older
R
RotPublic 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* eslint-disable react-hooks/exhaustive-deps */
/**
 * Copyright 2020 Baidu Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import Aside, {AsideSection} from '~/components/Aside';
import type {Documentation, OpenedResult, Properties, SearchItem, SearchResult} from '~/resource/graph/types';
20
import GraphComponent, {GraphRef} from '~/components/GraphPage/GraphStatic3';
R
RotPublic 已提交
21 22 23 24 25
import React, {useImperativeHandle, useCallback, useEffect, useMemo, useRef, useState} from 'react';
import Select, {SelectProps} from '~/components/Select';
import {actions} from '~/store';
import {primaryColor, rem, size} from '~/utils/style';
import {useDispatch} from 'react-redux';
26 27
import XpaddleUploader from '~/components/Onnx2PaddleUpload';
import Paddle2OnnxUpload from '~/components/Paddle2OnnxUpload';
R
RotPublic 已提交
28 29

import type {BlobResponse} from '~/utils/fetch';
30
import Buttons from '~/components/Button';
R
RotPublic 已提交
31
import Checkbox from '~/components/Checkbox';
32
import Content from '~/components/ContentXpaddle';
R
RotPublic 已提交
33 34 35 36 37 38 39 40 41 42 43 44 45 46
import Field from '~/components/Field';
import HashLoader from 'react-spinners/HashLoader';
import ModelPropertiesDialog from '~/components/GraphPage/ModelPropertiesDialog';
import NodeDocumentationSidebar from '~/components/GraphPage/NodeDocumentationSidebar';
import NodePropertiesSidebar from '~/components/GraphPage/NodePropertiesSidebar';
import RadioButton from '~/components/RadioButton';
import RadioGroup from '~/components/RadioGroup';
import Search from '~/components/GraphPage/Search';
import Title from '~/components/Title';
import Uploader from '~/components/GraphPage/Uploader';
import styled from 'styled-components';
import useRequest from '~/hooks/useRequest';
import {useTranslation} from 'react-i18next';

47
const FullWidthButton = styled(Buttons)`
R
RotPublic 已提交
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 79 80 81 82 83 84 85 86 87 88 89 90 91
    width: 100%;
`;

const FullWidthSelect = styled<React.FunctionComponent<SelectProps<NonNullable<OpenedResult['selected']>>>>(Select)`
    width: 100%;
`;

const ExportButtonWrapper = styled.div`
    display: flex;
    justify-content: space-between;

    > * {
        flex: 1 1 auto;

        &:not(:last-child) {
            margin-right: ${rem(20)};
        }
    }
`;

// TODO: better way to auto fit height
const SearchSection = styled(AsideSection)`
    max-height: calc(100% - ${rem(40)});
    display: flex;
    flex-direction: column;

    &:not(:last-child) {
        padding-bottom: 0;
    }
`;

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)};
`;
type GraphProps = {
    changeName: (name: string) => void;
92 93
    changeFlags: (flag: boolean) => void;
    changeFiles2?: (file: any) => void;
R
RotPublic 已提交
94 95
    show?: boolean;
    changeshowdata?: () => void;
96 97
    downloadEvent?: (baseId: number, fileName: string) => void;
    changeLoading?: (value: any) => void;
R
RotPublic 已提交
98
    Xpaddlae?: boolean;
99
    ModelValue?: number;
R
RotPublic 已提交
100 101 102
};
type pageRef = {
    files: FileList | File[] | null;
103
    setnewfiles: () => void;
R
RotPublic 已提交
104 105
    setNodeDocumentations: () => void;
};
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
const Graph = React.forwardRef<pageRef, GraphProps>(
    (
        {
            changeName,
            changeshowdata,
            Xpaddlae,
            show = true,
            changeFlags,
            changeLoading,
            changeFiles2,
            downloadEvent,
            ModelValue
        },
        ref
    ) => {
        const {t} = useTranslation(['graph', 'common']);
R
RotPublic 已提交
122

123 124
        const storeDispatch = useDispatch();
        // const storeModel = useSelector(selectors.graph.model);
R
RotPublic 已提交
125

126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
        const graph = useRef<GraphRef>(null);
        const file = useRef<HTMLInputElement>(null);
        const [files, setFiles] = useState<any>();
        const setModelFile = useCallback(
            (f: FileList | File[]) => {
                storeDispatch(actions.graph.setModel(f));
                const name = f[0].name.substring(f[0].name.lastIndexOf('.') + 1);
                changeName && changeName(name);
                setFiles(f);
                changeFlags(true);
                changeshowdata && changeshowdata();
            },
            [storeDispatch]
        );
        const newsetfiles = (f: FileList | File[]) => {
            // changeFlags(false);
            setRendered(false);
R
RotPublic 已提交
143
            setFiles(f);
144 145 146 147 148
        };
        const onClickFile = useCallback(() => {
            if (file.current) {
                file.current.value = '';
                file.current.click();
R
RotPublic 已提交
149
            }
150 151 152 153 154 155 156 157 158 159
        }, []);
        const onChangeFile = useCallback(
            (e: React.ChangeEvent<HTMLInputElement>) => {
                const target = e.target;
                if (target && target.files && target.files.length) {
                    setModelFile(target.files);
                }
            },
            [setModelFile]
        );
R
RotPublic 已提交
160

161
        // const {data, loading} = useRequest<BlobResponse>(files ? null : '/graph/static_graph');
R
RotPublic 已提交
162

163 164 165 166 167 168
        // useEffect(() => {
        //     if (data?.data?.size) {
        //         setFiles([new File([data.data], data.filename || 'unknown_model')]);
        //     }
        // }, [data]);
        const {loading} = useRequest<BlobResponse>(files ? null : '/graph/graph');
R
RotPublic 已提交
169

170 171 172 173 174 175 176 177 178 179
        const [modelGraphs, setModelGraphs] = useState<OpenedResult['graphs']>([]);
        const [selectedGraph, setSelectedGraph] = useState<NonNullable<OpenedResult['selected']>>('');
        const setOpenedModel = useCallback((data: OpenedResult) => {
            setModelGraphs(data.graphs);
            setSelectedGraph(data.selected || '');
        }, []);
        const changeGraph = useCallback((name: string) => {
            setSelectedGraph(name);
            graph.current?.changeGraph(name);
        }, []);
R
RotPublic 已提交
180

181 182 183 184 185 186 187 188 189 190 191
        const [search, setSearch] = useState('');
        const [searching, setSearching] = useState(false);
        const [searchResult, setSearchResult] = useState<SearchResult>({text: '', result: []});
        const onSearch = useCallback((value: string) => {
            setSearch(value);
            graph.current?.search(value);
        }, []);
        const onSelect = useCallback((item: SearchItem) => {
            setSearch(item.name);
            graph.current?.select(item);
        }, []);
R
RotPublic 已提交
192

193 194 195 196
        const [showAttributes, setShowAttributes] = useState(false);
        const [showInitializers, setShowInitializers] = useState(true);
        const [showNames, setShowNames] = useState(false);
        const [horizontal, setHorizontal] = useState(false);
R
RotPublic 已提交
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
        const [modelData, setModelData] = useState<Properties | null>(null);
        const [nodeData, setNodeData] = useState<Properties | null>(null);
        const [nodeDocumentation, setNodeDocumentation] = useState<Documentation | null>(null);
        const [renderedflag3, setRenderedflag3] = useState(true);
        const [rendered, setRendered] = useState(false);
        useEffect(() => {
            setSearch('');
            setSearchResult({text: '', result: []});
        }, [files, showAttributes, showInitializers, showNames]);
        useEffect(() => {
            if (!show) {
                setRenderedflag3(false);
            } else {
                setRenderedflag3(true);
                setNodeData(null);
            }
        }, [show]);
        useEffect(() => {
            setFiles(undefined);
        }, [ModelValue]);
        // useEffect(() => {
        //     if (nodeData && renderedflag3) {
        //         debugger;
        //         changeFlags(false);
        //     }
        // }, [nodeData, renderedflag3]);
        useEffect(() => {
            if (rendered) {
                // debugger;
                // if ()
                changeFlags(true);
                changeLoading && changeLoading(false);
            }
        }, [rendered]);
        const bottom = useMemo(
            () =>
                searching ? null : (
                    <FullWidthButton type="primary" rounded onClick={onClickFile}>
                        {t('graph:change-model')}
                    </FullWidthButton>
                ),
            [t, onClickFile, searching]
        );
R
RotPublic 已提交
241

242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
        useImperativeHandle(ref, () => ({
            files,
            setnewfiles: () => {
                // debugger;
                setFiles(undefined);
            },
            setNodeDocumentations: () => {
                setRenderedflag3(false);
            }
        }));
        const aside = useMemo(() => {
            if (!rendered || loading) {
                return null;
            }
            if (nodeDocumentation) {
                return (
                    <Aside width={rem(360)}>
                        <NodeDocumentationSidebar
                            data={nodeDocumentation}
                            onClose={() => {
                                changeFlags(true);
                                setNodeDocumentation(null);
                            }}
                        />
                    </Aside>
                );
            }
            console.log('nodeData && renderedflag3', nodeData, renderedflag3);
            if (nodeData && renderedflag3) {
                return (
                    <Aside width={rem(360)}>
                        <NodePropertiesSidebar
                            data={nodeData}
                            onClose={() => {
                                changeFlags(true);
                                setNodeData(null);
                            }}
                            showNodeDocumentation={() => graph.current?.showNodeDocumentation(nodeData)}
                        />
                    </Aside>
                );
            }
R
RotPublic 已提交
284
            return (
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299
                // <Aside bottom={bottom}>

                <Aside>
                    <SearchSection>
                        <Search
                            text={search}
                            data={searchResult}
                            onChange={onSearch}
                            onSelect={onSelect}
                            onActive={() => setSearching(true)}
                            onDeactive={() => setSearching(false)}
                        />
                    </SearchSection>
                    {!searching && (
                        <>
R
RotPublic 已提交
300
                            <AsideSection>
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
                                <FullWidthButton onClick={() => graph.current?.showModelProperties()}>
                                    {t('graph:model-properties')}
                                </FullWidthButton>
                            </AsideSection>
                            {modelGraphs.length > 1 && (
                                <AsideSection>
                                    <Field label={t('graph:subgraph')}>
                                        <FullWidthSelect
                                            list={modelGraphs}
                                            value={selectedGraph}
                                            onChange={changeGraph}
                                        />
                                    </Field>
                                </AsideSection>
                            )}
                            <AsideSection>
                                <Field label={t('graph:display-data')}>
                                    <div>
                                        <Checkbox checked={showAttributes} onChange={setShowAttributes}>
                                            {t('graph:show-attributes')}
                                        </Checkbox>
                                    </div>
                                    <div>
                                        <Checkbox checked={showInitializers} onChange={setShowInitializers}>
                                            {t('graph:show-initializers')}
                                        </Checkbox>
                                    </div>
                                    <div>
                                        <Checkbox checked={showNames} onChange={setShowNames}>
                                            {t('graph:show-node-names')}
                                        </Checkbox>
                                    </div>
R
RotPublic 已提交
333 334
                                </Field>
                            </AsideSection>
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                            <AsideSection>
                                <Field label={t('graph:direction')}>
                                    <RadioGroup value={horizontal} onChange={setHorizontal}>
                                        <RadioButton value={false}>{t('graph:vertical')}</RadioButton>
                                        <RadioButton value={true}>{t('graph:horizontal')}</RadioButton>
                                    </RadioGroup>
                                </Field>
                            </AsideSection>
                            <AsideSection>
                                <Field label={t('graph:export-file')}>
                                    <ExportButtonWrapper>
                                        <Buttons onClick={() => graph.current?.export('png')}>
                                            {t('graph:export-png')}
                                        </Buttons>
                                        <Buttons onClick={() => graph.current?.export('svg')}>
                                            {t('graph:export-svg')}
                                        </Buttons>
                                    </ExportButtonWrapper>
                                </Field>
                            </AsideSection>
                        </>
                    )}
                </Aside>
            );
        }, [
            t,
            bottom,
            search,
            searching,
            searchResult,
            modelGraphs,
            selectedGraph,
            changeGraph,
            onSearch,
            onSelect,
            showAttributes,
            showInitializers,
            showNames,
            horizontal,
            rendered,
            loading,
            nodeData,
            nodeDocumentation,
            renderedflag3
        ]);
        // const uploader = useMemo(
        //     () => <Uploader onClickUpload={onClickFile} onDropFiles={setModelFile} Xpaddlae={Xpaddlae} />,
        //     [onClickFile, setModelFile]
        // );
        // const buttonItemLayout = formLayout === 'horizontal' ? {wrapperCol: {span: 14, offset: 4}} : null;
        const uploader = useMemo(() => {
            if (ModelValue === 1) {
                return (
                    <Paddle2OnnxUpload
                        changeLoading={changeLoading}
                        downloadEvent={downloadEvent}
                        setFiles={newsetfiles}
                        changeFiles2={changeFiles2}
                    ></Paddle2OnnxUpload>
                );
            } else {
                return (
                    <XpaddleUploader
                        changeLoading={changeLoading}
                        downloadEvent={downloadEvent}
                        setFiles={newsetfiles}
                        changeFiles2={changeFiles2}
                    ></XpaddleUploader>
                );
            }
        }, [ModelValue]);
        const flags = files && show;
        console.log('flags', flags, aside);
        const nodeShows = (nodeData && renderedflag3) || nodeDocumentation;
        const nodeShow = nodeShows ? true : false;
        return (
            <>
                <Title>{t('common:graph')}</Title>
                <ModelPropertiesDialog data={modelData} onClose={() => setModelData(null)} />
                <Content show={show} nodeShow={nodeShow} aside={flags ? aside : null}>
                    {loading ? (
                        <Loading>
                            <HashLoader size="60px" color={primaryColor} />
                        </Loading>
                    ) : (
                        <GraphComponent
                            ref={graph}
                            files={files}
                            uploader={uploader}
                            showAttributes={showAttributes}
                            showInitializers={showInitializers}
                            showNames={showNames}
                            horizontal={horizontal}
                            onRendered={flag => setRendered(flag)}
                            onOpened={setOpenedModel}
                            onSearch={data => {
                                setSearchResult(data);
                            }}
                            onShowModelProperties={data => setModelData(data)}
                            onShowNodeProperties={data => {
                                setNodeData(data);
                                setNodeDocumentation(null);
                            }}
                            onShowNodeDocumentation={data => setNodeDocumentation(data)}
                        />
                    )}
                    <input
                        ref={file}
                        type="file"
                        multiple={false}
                        onChange={onChangeFile}
                        style={{
                            display: 'none'
R
RotPublic 已提交
448 449
                        }}
                    />
450 451 452 453 454
                </Content>
            </>
        );
    }
);
R
RotPublic 已提交
455 456

export default Graph;