Navbar.tsx 12.2 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 cimode

19 20
import {Link, LinkProps, useLocation} from 'react-router-dom';
import React, {FunctionComponent, useCallback, useEffect, useMemo, useState} from 'react';
P
Peter Pan 已提交
21
import {border, borderRadius, rem, size, transitionProps, triangle} from '~/utils/style';
22

23 24
import Icon from '~/components/Icon';
import Language from '~/components/Language';
25
import type {Route} from '~/routes';
P
Peter Pan 已提交
26
import ThemeToggle from '~/components/ThemeToggle';
P
Peter Pan 已提交
27
import Tippy from '@tippyjs/react';
28
import ee from '~/utils/event';
29
import {getApiToken} from '~/utils/fetch';
30
import logo from '~/assets/images/logo.svg';
31
import queryString from 'query-string';
32
import styled from 'styled-components';
P
Peter Pan 已提交
33
import useClassNames from '~/hooks/useClassNames';
34
import useComponents from '~/hooks/useComponents';
35
import {useTranslation} from 'react-i18next';
36

37
const BASE_URI: string = import.meta.env.SNOWPACK_PUBLIC_BASE_URI;
38 39 40
const PUBLIC_PATH: string = import.meta.env.SNOWPACK_PUBLIC_PATH;
const API_TOKEN_KEY: string = import.meta.env.SNOWPACK_PUBLIC_API_TOKEN_KEY;

41
const MAX_ITEM_COUNT_IN_NAVBAR = 6;
P
Peter Pan 已提交
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

const flatten = <T extends {children?: T[]}>(routes: T[]) => {
    const result: Omit<T, 'children'>[] = [];
    routes.forEach(route => {
        if (route.children) {
            result.push(...flatten(route.children));
        } else {
            result.push(route);
        }
    });
    return result;
};

interface NavbarItemProps {
    active: boolean;
    path?: Route['path'];
    showDropdownIcon?: boolean;
}

interface NavbarItemType {
    id: string;
63
    cid?: string;
P
Peter Pan 已提交
64
    name: string;
65
    active: boolean;
P
Peter Pan 已提交
66 67
    path?: Route['path'];
    children?: NavbarItemType[];
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
}

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()
        }
    });
}
83

84
const Nav = styled.nav`
P
Peter Pan 已提交
85 86
    background-color: var(--navbar-background-color);
    color: var(--navbar-text-color);
87
    ${size('100%')}
88 89
    padding: 0 ${rem(20)};
    display: flex;
90 91
    justify-content: space-between;
    align-items: stretch;
P
Peter Pan 已提交
92
    ${transitionProps(['background-color', 'color'])}
93 94 95 96 97 98 99 100 101 102 103 104 105

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

    > .right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-right: -${rem(20)};
    }
106 107 108 109 110 111 112 113 114 115
`;

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 {
116
        ${size(rem(31), rem(98))}
117 118 119 120 121 122 123 124 125
        vertical-align: middle;
        margin-right: ${rem(8)};
    }

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

126
const NavItem = styled.div<{active?: boolean}>`
127 128 129 130
    height: 100%;
    display: inline-flex;
    justify-content: center;
    align-items: center;
P
Peter Pan 已提交
131
    background-color: var(--navbar-background-color);
132
    cursor: pointer;
133
    ${transitionProps('background-color')}
134 135

    &:hover {
P
Peter Pan 已提交
136
        background-color: var(--navbar-hover-background-color);
137 138
    }

139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    &.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)};
154
        padding: ${rem(10)} 0 ${rem(7)};
P
Peter Pan 已提交
155
        ${props => border('bottom', rem(3), 'solid', props.active ? 'var(--navbar-highlight-color)' : 'transparent')}
156
        ${transitionProps('border-bottom')}
157
        text-transform: uppercase;
P
Peter Pan 已提交
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

        &.dropdown-icon {
            &::after {
                content: '';
                display: inline-block;
                width: 0;
                height: 0;
                margin-left: 0.5rem;
                vertical-align: middle;
                ${triangle({
                    pointingDirection: 'bottom',
                    width: rem(8),
                    height: rem(5),
                    foregroundColor: 'currentColor'
                })}
            }
        }
175 176 177
    }
`;

P
Peter Pan 已提交
178
const SubNavWrapper = styled.div`
P
Peter Pan 已提交
179 180 181 182
    overflow: hidden;
    border-radius: ${borderRadius};
`;

183
const NavItemChild = styled.div<{active?: boolean}>`
P
Peter Pan 已提交
184 185 186 187 188
    display: block;
    line-height: 3em;

    &,
    &:visited {
P
Peter Pan 已提交
189
        color: ${props => (props.active ? 'var(--primary-color)' : 'var(--text-color)')};
P
Peter Pan 已提交
190 191 192
    }

    &:hover {
P
Peter Pan 已提交
193
        background-color: var(--background-focused-color);
P
Peter Pan 已提交
194 195
    }

196 197 198 199 200
    > a {
        display: block;
        padding: 0 ${rem(20)};
    }
`;
P
Peter Pan 已提交
201

P
Peter Pan 已提交
202 203 204 205 206 207 208 209 210
const NavbarLink: FunctionComponent<{to?: string} & Omit<LinkProps, 'to'>> = ({to, children, ...props}) => (
    <Link to={to ? appendApiToken(to) : ''} {...props}>
        {children}
    </Link>
);

// FIXME: why we need to add children type here... that's weird...
const NavbarItem = React.forwardRef<HTMLDivElement, NavbarItemProps & {children?: React.ReactNode}>(
    ({path, active, showDropdownIcon, children}, ref) => {
P
Peter Pan 已提交
211 212
        const classNames = useClassNames('nav-text', {'dropdown-icon': showDropdownIcon}, [showDropdownIcon]);

P
Peter Pan 已提交
213 214 215 216
        if (path) {
            return (
                <NavItem active={active} ref={ref}>
                    <NavbarLink to={path} className="nav-link">
P
Peter Pan 已提交
217
                        <span className={classNames}>{children}</span>
P
Peter Pan 已提交
218 219 220 221
                    </NavbarLink>
                </NavItem>
            );
        }
P
Peter Pan 已提交
222 223

        return (
224
            <NavItem active={active} ref={ref}>
P
Peter Pan 已提交
225
                <span className={classNames}>{children}</span>
226
            </NavItem>
P
Peter Pan 已提交
227 228
        );
    }
P
Peter Pan 已提交
229
);
P
Peter Pan 已提交
230 231 232

NavbarItem.displayName = 'NavbarItem';

P
Peter Pan 已提交
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
const SubNav: FunctionComponent<{
    menu: Omit<NavbarItemType, 'children' | 'cid'>[];
    active?: boolean;
    path?: string;
    showDropdownIcon?: boolean;
}> = ({menu, active, path, showDropdownIcon, children}) => (
    <Tippy
        placement="bottom-start"
        animation="shift-away-subtle"
        interactive
        arrow={false}
        offset={[0, 0]}
        hideOnClick={false}
        role="menu"
        content={
            <SubNavWrapper>
                {menu.map(item => (
                    <NavItemChild active={item.active} key={item.id}>
                        <NavbarLink to={item.path}>{item.name}</NavbarLink>
                    </NavItemChild>
                ))}
            </SubNavWrapper>
        }
    >
        <NavbarItem active={active || false} path={path} showDropdownIcon={showDropdownIcon}>
            {children}
        </NavbarItem>
    </Tippy>
);

263
const Navbar: FunctionComponent = () => {
P
Peter Pan 已提交
264
    const {t, i18n} = useTranslation('common');
265 266 267 268 269 270 271 272 273
    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 已提交
274

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

277
    const [components] = useComponents();
P
Peter Pan 已提交
278 279 280 281 282 283 284 285 286 287 288 289

    const componentsInNavbar = useMemo(() => components.slice(0, MAX_ITEM_COUNT_IN_NAVBAR), [components]);
    const flattenMoreComponents = useMemo(() => flatten(components.slice(MAX_ITEM_COUNT_IN_NAVBAR)), [components]);
    const componentsInMoreMenu = useMemo(
        () =>
            flattenMoreComponents.map(item => ({
                ...item,
                active: currentPath === item.path
            })),
        [currentPath, flattenMoreComponents]
    );
    const [navItemsInNavbar, setNavItemsInNavbar] = useState<NavbarItemType[]>([]);
P
Peter Pan 已提交
290
    useEffect(() => {
P
Peter Pan 已提交
291 292
        setNavItemsInNavbar(oldItems =>
            componentsInNavbar.map(item => {
P
Peter Pan 已提交
293 294 295 296 297 298 299 300 301 302
                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,
P
Peter Pan 已提交
303
                            name: child.name,
P
Peter Pan 已提交
304 305 306 307 308 309 310 311 312 313
                            path: currentPath,
                            active: true,
                            children
                        };
                    } else {
                        const oldItem = oldItems.find(oldItem => oldItem.id === item.id);
                        if (oldItem) {
                            return {
                                ...item,
                                ...oldItem,
P
Peter Pan 已提交
314
                                name: item.children?.find(c => c.id === oldItem.cid)?.name ?? item.name,
P
Peter Pan 已提交
315 316 317 318 319 320 321 322 323 324 325 326 327
                                active: false,
                                children
                            };
                        }
                    }
                }
                return {
                    ...item,
                    active: currentPath === item.path,
                    children
                };
            })
        );
P
Peter Pan 已提交
328
    }, [componentsInNavbar, currentPath]);
329 330 331

    return (
        <Nav>
332
            <div className="left">
333
                <Logo href={appendApiToken(BASE_URI + '/index')}>
334
                    <img alt="PaddlePaddle" src={PUBLIC_PATH + logo} />
335 336
                    <span>VisualDL</span>
                </Logo>
P
Peter Pan 已提交
337
                {navItemsInNavbar.map(item => {
P
Peter Pan 已提交
338 339
                    if (item.children) {
                        return (
P
Peter Pan 已提交
340 341 342 343
                            <SubNav
                                menu={item.children}
                                active={item.active}
                                path={item.path}
P
Peter Pan 已提交
344 345
                                key={item.active ? `${item.id}-activated` : item.id}
                            >
P
Peter Pan 已提交
346 347
                                {item.name}
                            </SubNav>
P
Peter Pan 已提交
348 349
                        );
                    }
P
Peter Pan 已提交
350 351 352 353 354
                    return (
                        <NavbarItem active={item.active} path={item.path} key={item.id}>
                            {item.name}
                        </NavbarItem>
                    );
355
                })}
P
Peter Pan 已提交
356 357 358 359 360
                {componentsInMoreMenu.length ? (
                    <SubNav menu={componentsInMoreMenu} showDropdownIcon>
                        {t('common:more')}
                    </SubNav>
                ) : null}
361 362
            </div>
            <div className="right">
P
Peter Pan 已提交
363 364 365 366 367 368 369 370 371
                <Tippy
                    placement="bottom-end"
                    animation="shift-away-subtle"
                    interactive
                    arrow={false}
                    offset={[18, 0]}
                    hideOnClick={false}
                    role="menu"
                    content={
P
Peter Pan 已提交
372
                        <SubNavWrapper>
P
Peter Pan 已提交
373
                            <ThemeToggle />
P
Peter Pan 已提交
374
                        </SubNavWrapper>
P
Peter Pan 已提交
375 376 377 378 379 380
                    }
                >
                    <NavItem className="nav-item">
                        <Icon type="theme" />
                    </NavItem>
                </Tippy>
381
                <NavItem className="nav-item" onClick={changeLanguage}>
382 383
                    <Language />
                </NavItem>
384
                <NavItem className="nav-item" onClick={() => ee.emit('refresh')}>
385 386 387
                    <Icon type="refresh" />
                </NavItem>
            </div>
388 389 390 391 392
        </Nav>
    );
};

export default Navbar;