App.tsx 5.1 KB
Newer Older
P
Peter Pan 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/**
 * 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.
 */

P
Peter Pan 已提交
17
import React, {FunctionComponent, Suspense, useCallback, useEffect, useMemo, useState} from 'react';
18
import {Redirect, Route, BrowserRouter as Router, Switch, useLocation} from 'react-router-dom';
P
Peter Pan 已提交
19
import {THEME, matchMedia} from '~/utils/theme';
20
import {headerHeight, position, size, zIndexes} from '~/utils/style';
21 22

import BodyLoading from '~/components/BodyLoading';
P
Peter Pan 已提交
23 24
import ErrorBoundary from '~/components/ErrorBoundary';
import ErrorPage from '~/pages/error';
25 26 27 28
import {Helmet} from 'react-helmet';
import NProgress from 'nprogress';
import Navbar from '~/components/Navbar';
import {SWRConfig} from 'swr';
P
Peter Pan 已提交
29
import {ToastContainer} from 'react-toastify';
P
Peter Pan 已提交
30
import {actions} from '~/store';
31 32 33 34
import {fetcher} from '~/utils/fetch';
import init from '@visualdl/wasm';
import routes from '~/routes';
import styled from 'styled-components';
P
Peter Pan 已提交
35
import {useDispatch} from 'react-redux';
36 37
import {useTranslation} from 'react-i18next';

38
const BASE_URI: string = import.meta.env.SNOWPACK_PUBLIC_BASE_URI;
39 40 41 42 43 44 45
const PUBLIC_PATH: string = import.meta.env.SNOWPACK_PUBLIC_PATH;

const Main = styled.main`
    padding-top: ${headerHeight};
`;

const Header = styled.header`
46
    z-index: ${zIndexes.header};
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

    ${size(headerHeight, '100%')}
    ${position('fixed', 0, 0, null, 0)}
`;

const defaultRoute = routes.find(route => route.default);
const routers = routes.reduce<Omit<typeof routes[number], 'children'>[]>((m, route) => {
    if (route.children) {
        m.push(...route.children);
    } else {
        m.push(route);
    }
    return m;
}, []);

const Progress: FunctionComponent = () => {
    useEffect(() => {
        NProgress.start();
        return () => {
            NProgress.done();
        };
    }, []);

    return null;
};

const Telemetry: FunctionComponent = () => {
    const location = useLocation();
    useEffect(() => {
P
Peter Pan 已提交
76
        window._hmt.push(['_trackPageview', BASE_URI + location.pathname]);
77 78 79 80 81
    }, [location.pathname]);
    return null;
};

const App: FunctionComponent = () => {
P
Peter Pan 已提交
82
    const {t, i18n} = useTranslation('errors');
83 84 85 86 87 88 89 90 91 92 93 94 95

    const dir = useMemo(() => (i18n.language ? i18n.dir(i18n.language) : ''), [i18n]);

    const [inited, setInited] = useState(false);
    useEffect(() => {
        (async () => {
            if (!inited) {
                await init(`${PUBLIC_PATH}/wasm/visualdl.wasm`);
                setInited(true);
            }
        })();
    }, [inited]);

P
Peter Pan 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
    const dispatch = useDispatch();

    const toggleTheme = useCallback(
        (e: MediaQueryListEvent) => dispatch(actions.theme.setTheme(e.matches ? 'dark' : 'light')),
        [dispatch]
    );

    useEffect(() => {
        if (!THEME) {
            matchMedia.addEventListener('change', toggleTheme);
            return () => {
                matchMedia.removeEventListener('change', toggleTheme);
            };
        }
    }, [toggleTheme]);

112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
    return (
        <div className="app">
            <Helmet defaultTitle="VisualDL" titleTemplate="%s - VisualDL">
                <html lang={i18n.language} dir={dir} />
            </Helmet>
            <SWRConfig
                value={{
                    fetcher,
                    revalidateOnFocus: false,
                    revalidateOnReconnect: false
                }}
            >
                {!inited ? (
                    <BodyLoading />
                ) : (
                    <Main>
128
                        <Router basename={BASE_URI || '/'}>
129 130 131 132
                            <Telemetry />
                            <Header>
                                <Navbar />
                            </Header>
P
Peter Pan 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145
                            <ErrorBoundary fallback={<ErrorPage />}>
                                <Suspense fallback={<Progress />}>
                                    <Switch>
                                        <Redirect exact from="/" to={defaultRoute?.path ?? '/index'} />
                                        {routers.map(route => (
                                            <Route key={route.id} path={route.path} component={route.component} />
                                        ))}
                                        <Route path="*">
                                            <ErrorPage title={t('errors:page-not-found')} />
                                        </Route>
                                    </Switch>
                                </Suspense>
                            </ErrorBoundary>
146 147 148
                        </Router>
                    </Main>
                )}
P
Peter Pan 已提交
149
                <ToastContainer />
150 151 152 153 154 155
            </SWRConfig>
        </div>
    );
};

export default App;