Navbar.tsx 8.7 KB
Newer Older
1 2
import {Link, LinkProps, useLocation} from 'react-router-dom';
import React, {FunctionComponent, useCallback, useEffect, useMemo, useState} from 'react';
P
Peter Pan 已提交
3
import {border, borderRadius, rem, size, transitionProps} from '~/utils/style';
4

5 6
import Icon from '~/components/Icon';
import Language from '~/components/Language';
7
import type {Route} from '~/routes';
P
Peter Pan 已提交
8
import Tippy from '@tippyjs/react';
9
import ee from '~/utils/event';
10
import {getApiToken} from '~/utils/fetch';
11
import logo from '~/assets/images/logo.svg';
12
import queryString from 'query-string';
13
import styled from 'styled-components';
14 15
import useNavItems from '~/hooks/useNavItems';
import {useTranslation} from 'react-i18next';
16

17
const BASE_URI: string = import.meta.env.SNOWPACK_PUBLIC_BASE_URI;
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
const PUBLIC_PATH: string = import.meta.env.SNOWPACK_PUBLIC_PATH;
const API_TOKEN_KEY: string = import.meta.env.SNOWPACK_PUBLIC_API_TOKEN_KEY;

interface NavbarItemProps extends Route {
    cid?: string;
    active: boolean;
    children?: ({active: boolean} & NonNullable<Route['children']>[number])[];
}

function appendApiToken(url: string) {
    if (!API_TOKEN_KEY) {
        return url;
    }
    const parsed = queryString.parseUrl(url);
    return queryString.stringifyUrl({
        ...parsed,
        query: {
            ...parsed.query,
            [API_TOKEN_KEY]: getApiToken()
        }
    });
}
40

41
const Nav = styled.nav`
P
Peter Pan 已提交
42 43
    background-color: var(--navbar-background-color);
    color: var(--navbar-text-color);
44
    ${size('100%')}
45 46
    padding: 0 ${rem(20)};
    display: flex;
47 48
    justify-content: space-between;
    align-items: stretch;
P
Peter Pan 已提交
49
    ${transitionProps(['background-color', 'color'])}
50 51 52 53 54 55 56 57 58 59 60 61 62

    > .left {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    > .right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-right: -${rem(20)};
    }
63 64 65 66 67 68 69 70 71 72
`;

const Logo = styled.a`
    font-size: ${rem(20)};
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif,
        'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol';
    font-weight: 600;
    margin-right: ${rem(40)};

    > img {
73
        ${size(rem(31), rem(98))}
74 75 76 77 78 79 80 81 82
        vertical-align: middle;
        margin-right: ${rem(8)};
    }

    > span {
        vertical-align: middle;
    }
`;

83
const NavItem = styled.div<{active?: boolean}>`
84 85 86 87
    height: 100%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
P
Peter Pan 已提交
88
    background-color: var(--navbar-background-color);
89
    cursor: pointer;
90
    ${transitionProps('background-color')}
91 92

    &:hover {
P
Peter Pan 已提交
93
        background-color: var(--navbar-hover-background-color);
94 95
    }

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    &.nav-item {
        padding: 0 ${rem(20)};
    }

    .nav-link {
        display: inline-block;
        width: 100%;
        height: 100%;
        display: inline-flex;
        justify-content: center;
        align-items: center;
    }

    .nav-text {
        margin: ${rem(20)};
111
        padding: ${rem(10)} 0 ${rem(7)};
P
Peter Pan 已提交
112
        ${props => border('bottom', rem(3), 'solid', props.active ? 'var(--navbar-highlight-color)' : 'transparent')}
113
        ${transitionProps('border-bottom')}
114 115 116 117
        text-transform: uppercase;
    }
`;

P
Peter Pan 已提交
118 119 120 121 122
const SubNav = styled.div`
    overflow: hidden;
    border-radius: ${borderRadius};
`;

123
const NavItemChild = styled.div<{active?: boolean}>`
P
Peter Pan 已提交
124 125 126 127 128
    display: block;
    line-height: 3em;

    &,
    &:visited {
P
Peter Pan 已提交
129
        color: ${props => (props.active ? 'var(--primary-color)' : 'var(--text-color)')};
P
Peter Pan 已提交
130 131 132
    }

    &:hover {
P
Peter Pan 已提交
133
        background-color: var(--background-focused-color);
P
Peter Pan 已提交
134 135
    }

136 137 138 139 140
    > a {
        display: block;
        padding: 0 ${rem(20)};
    }
`;
P
Peter Pan 已提交
141

142 143 144 145 146 147
const NavbarLink: FunctionComponent<{to?: string} & Omit<LinkProps, 'to'>> = ({to, children, ...props}) => {
    return (
        <Link to={to ? appendApiToken(to) : ''} {...props}>
            {children}
        </Link>
    );
148 149
};

150
const NavbarItem = React.forwardRef<HTMLDivElement, NavbarItemProps>(({id, cid, path, active}, ref) => {
P
Peter Pan 已提交
151 152 153 154 155 156
    const {t} = useTranslation('common');

    const name = useMemo(() => (cid ? `${t(id)} - ${t(cid)}` : t(id)), [t, id, cid]);

    if (path) {
        return (
157 158
            <NavItem active={active} ref={ref}>
                <NavbarLink to={path} className="nav-link">
P
Peter Pan 已提交
159
                    <span className="nav-text">{name}</span>
160 161
                </NavbarLink>
            </NavItem>
P
Peter Pan 已提交
162 163
        );
    }
164

P
Peter Pan 已提交
165 166 167 168 169 170 171 172 173
    return (
        <NavItem active={active} ref={ref}>
            <span className="nav-text">{name}</span>
        </NavItem>
    );
});

NavbarItem.displayName = 'NavbarItem';

174
const Navbar: FunctionComponent = () => {
P
Peter Pan 已提交
175
    const {t, i18n} = useTranslation('common');
176 177 178 179 180 181 182 183 184
    const {pathname} = useLocation();

    const changeLanguage = useCallback(() => {
        const language = i18n.language;
        const allLanguages = (i18n.options.supportedLngs || []).filter(lng => lng !== 'cimode');
        const index = allLanguages.indexOf(language);
        const nextLanguage = index < 0 || index >= allLanguages.length - 1 ? allLanguages[0] : allLanguages[index + 1];
        i18n.changeLanguage(nextLanguage);
    }, [i18n]);
P
Peter Pan 已提交
185

186
    const currentPath = useMemo(() => pathname.replace(BASE_URI, ''), [pathname]);
P
Peter Pan 已提交
187

P
Peter Pan 已提交
188
    const [navItems] = useNavItems();
189
    const [items, setItems] = useState<NavbarItemProps[]>([]);
P
Peter Pan 已提交
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
    useEffect(() => {
        setItems(oldItems =>
            navItems.map(item => {
                const children = item.children?.map(child => ({
                    ...child,
                    active: child.path === currentPath
                }));
                if (item.children && !item.path) {
                    const child = item.children.find(child => child.path === currentPath);
                    if (child) {
                        return {
                            ...item,
                            cid: child.id,
                            path: currentPath,
                            active: true,
                            children
                        };
                    } else {
                        const oldItem = oldItems.find(oldItem => oldItem.id === item.id);
                        if (oldItem) {
                            return {
                                ...item,
                                ...oldItem,
                                active: false,
                                children
                            };
                        }
                    }
                }
                return {
                    ...item,
                    active: currentPath === item.path,
                    children
                };
            })
        );
    }, [navItems, currentPath]);
227 228 229

    return (
        <Nav>
230
            <div className="left">
231
                <Logo href={appendApiToken(BASE_URI + '/index')}>
232
                    <img alt="PaddlePaddle" src={PUBLIC_PATH + logo} />
233 234
                    <span>VisualDL</span>
                </Logo>
P
Peter Pan 已提交
235 236 237 238 239 240 241 242 243 244 245 246 247 248
                {items.map(item => {
                    if (item.children) {
                        return (
                            <Tippy
                                placement="bottom-start"
                                animation="shift-away-subtle"
                                interactive
                                arrow={false}
                                offset={[0, 0]}
                                hideOnClick={false}
                                role="menu"
                                content={
                                    <SubNav>
                                        {item.children.map(child => (
249 250
                                            <NavItemChild active={child.active} key={child.id}>
                                                <NavbarLink to={child.path}>
P
Peter Pan 已提交
251
                                                    {t(item.id)} - {t(child.id)}
252 253
                                                </NavbarLink>
                                            </NavItemChild>
P
Peter Pan 已提交
254 255 256 257 258 259 260 261 262 263
                                        ))}
                                    </SubNav>
                                }
                                key={item.active ? `${item.id}-activated` : item.id}
                            >
                                <NavbarItem {...item} />
                            </Tippy>
                        );
                    }
                    return <NavbarItem {...item} key={item.id} />;
264 265 266
                })}
            </div>
            <div className="right">
267
                <NavItem className="nav-item" onClick={changeLanguage}>
268 269
                    <Language />
                </NavItem>
270
                <NavItem className="nav-item" onClick={() => ee.emit('refresh')}>
271 272 273
                    <Icon type="refresh" />
                </NavItem>
            </div>
274 275 276 277 278
        </Nav>
    );
};

export default Navbar;