Navbar.tsx 8.8 KB
Newer Older
1 2
import {Link, LinkProps, useLocation} from 'react-router-dom';
import React, {FunctionComponent, useCallback, useEffect, useMemo, useState} from 'react';
3
import {
P
Peter Pan 已提交
4
    backgroundFocusedColor,
5
    border,
P
Peter Pan 已提交
6
    borderRadius,
7 8 9
    navbarBackgroundColor,
    navbarHighlightColor,
    navbarHoverBackgroundColor,
P
Peter Pan 已提交
10
    primaryColor,
11 12
    rem,
    size,
P
Peter Pan 已提交
13
    textColor,
14 15 16 17
    textInvertColor,
    transitionProps
} from '~/utils/style';

18 19
import Icon from '~/components/Icon';
import Language from '~/components/Language';
20
import type {Route} from '~/routes';
P
Peter Pan 已提交
21
import Tippy from '@tippyjs/react';
22
import ee from '~/utils/event';
23
import {getApiToken} from '~/utils/fetch';
24
import logo from '~/assets/images/logo.svg';
25
import queryString from 'query-string';
26
import styled from 'styled-components';
27 28
import useNavItems from '~/hooks/useNavItems';
import {useTranslation} from 'react-i18next';
29

30
const BASE_URI: string = import.meta.env.SNOWPACK_PUBLIC_BASE_URI;
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
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()
        }
    });
}
53

54
const Nav = styled.nav`
55 56 57
    background-color: ${navbarBackgroundColor};
    color: ${textInvertColor};
    ${size('100%')}
58 59
    padding: 0 ${rem(20)};
    display: flex;
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    justify-content: space-between;
    align-items: stretch;

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

    > .right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-right: -${rem(20)};
    }
75 76 77 78 79 80 81 82 83 84
`;

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 {
85
        ${size(rem(31), rem(98))}
86 87 88 89 90 91 92 93 94
        vertical-align: middle;
        margin-right: ${rem(8)};
    }

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

95
const NavItem = styled.div<{active?: boolean}>`
96 97 98 99
    height: 100%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
100
    background-color: ${navbarBackgroundColor};
101
    cursor: pointer;
102
    ${transitionProps('background-color')}
103 104

    &:hover {
105
        background-color: ${navbarHoverBackgroundColor};
106 107
    }

108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    &.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)};
123
        padding: ${rem(10)} 0 ${rem(7)};
124 125
        ${props => border('bottom', rem(3), 'solid', props.active ? navbarHighlightColor : 'transparent')}
        ${transitionProps('border-bottom')}
126 127 128 129
        text-transform: uppercase;
    }
`;

P
Peter Pan 已提交
130 131 132 133 134
const SubNav = styled.div`
    overflow: hidden;
    border-radius: ${borderRadius};
`;

135
const NavItemChild = styled.div<{active?: boolean}>`
P
Peter Pan 已提交
136 137 138 139 140 141 142 143 144 145 146 147
    display: block;
    line-height: 3em;

    &,
    &:visited {
        color: ${props => (props.active ? primaryColor : textColor)};
    }

    &:hover {
        background-color: ${backgroundFocusedColor};
    }

148 149 150 151 152
    > a {
        display: block;
        padding: 0 ${rem(20)};
    }
`;
P
Peter Pan 已提交
153

154 155 156 157 158 159
const NavbarLink: FunctionComponent<{to?: string} & Omit<LinkProps, 'to'>> = ({to, children, ...props}) => {
    return (
        <Link to={to ? appendApiToken(to) : ''} {...props}>
            {children}
        </Link>
    );
160 161
};

162
const NavbarItem = React.forwardRef<HTMLDivElement, NavbarItemProps>(({id, cid, path, active}, ref) => {
P
Peter Pan 已提交
163 164 165 166 167 168
    const {t} = useTranslation('common');

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

    if (path) {
        return (
169 170
            <NavItem active={active} ref={ref}>
                <NavbarLink to={path} className="nav-link">
P
Peter Pan 已提交
171
                    <span className="nav-text">{name}</span>
172 173
                </NavbarLink>
            </NavItem>
P
Peter Pan 已提交
174 175
        );
    }
176

P
Peter Pan 已提交
177 178 179 180 181 182 183 184 185
    return (
        <NavItem active={active} ref={ref}>
            <span className="nav-text">{name}</span>
        </NavItem>
    );
});

NavbarItem.displayName = 'NavbarItem';

186
const Navbar: FunctionComponent = () => {
P
Peter Pan 已提交
187
    const {t, i18n} = useTranslation('common');
188 189 190 191 192 193 194 195 196
    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 已提交
197

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

P
Peter Pan 已提交
200
    const [navItems] = useNavItems();
201
    const [items, setItems] = useState<NavbarItemProps[]>([]);
P
Peter Pan 已提交
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
    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]);
239 240 241

    return (
        <Nav>
242
            <div className="left">
243
                <Logo href={appendApiToken(BASE_URI + '/index')}>
244
                    <img alt="PaddlePaddle" src={PUBLIC_PATH + logo} />
245 246
                    <span>VisualDL</span>
                </Logo>
P
Peter Pan 已提交
247 248 249 250 251 252 253 254 255 256 257 258 259 260
                {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 => (
261 262
                                            <NavItemChild active={child.active} key={child.id}>
                                                <NavbarLink to={child.path}>
P
Peter Pan 已提交
263
                                                    {t(item.id)} - {t(child.id)}
264 265
                                                </NavbarLink>
                                            </NavItemChild>
P
Peter Pan 已提交
266 267 268 269 270 271 272 273 274 275
                                        ))}
                                    </SubNav>
                                }
                                key={item.active ? `${item.id}-activated` : item.id}
                            >
                                <NavbarItem {...item} />
                            </Tippy>
                        );
                    }
                    return <NavbarItem {...item} key={item.id} />;
276 277 278
                })}
            </div>
            <div className="right">
279
                <NavItem className="nav-item" onClick={changeLanguage}>
280 281
                    <Language />
                </NavItem>
282
                <NavItem className="nav-item" onClick={() => ee.emit('refresh')}>
283 284 285
                    <Icon type="refresh" />
                </NavItem>
            </div>
286 287 288 289 290
        </Nav>
    );
};

export default Navbar;