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 18
// cSpell:words pageview inited

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

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

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

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

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

    ${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 已提交
78
        window._hmt.push(['_trackPageview', BASE_URI + location.pathname]);
79 80 81 82 83
    }, [location.pathname]);
    return null;
};

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

    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 已提交
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
    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]);

114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
    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>
130
                        <Router basename={BASE_URI || '/'}>
131 132 133 134
                            <Telemetry />
                            <Header>
                                <Navbar />
                            </Header>
P
Peter Pan 已提交
135 136 137 138 139 140 141 142 143 144 145 146 147
                            <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>
148 149 150
                        </Router>
                    </Main>
                )}
P
Peter Pan 已提交
151
                <ToastContainer />
152 153 154 155 156 157
            </SWRConfig>
        </div>
    );
};

export default App;