Navbar.tsx 16.3 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
import {Link, LinkProps, useLocation} from 'react-router-dom';
20
import {useHistory} from 'react-router-dom';
21
import React, {FunctionComponent, useCallback, useEffect, useMemo, useState} from 'react';
P
Peter Pan 已提交
22
import {border, borderRadius, rem, size, transitionProps, triangle} from '~/utils/style';
23

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

42
const BASE_URI: string = import.meta.env.SNOWPACK_PUBLIC_BASE_URI;
43 44 45
const PUBLIC_PATH: string = import.meta.env.SNOWPACK_PUBLIC_PATH;
const API_TOKEN_KEY: string = import.meta.env.SNOWPACK_PUBLIC_API_TOKEN_KEY;

46
const MAX_ITEM_COUNT_IN_NAVBAR = 6;
P
Peter Pan 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67

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;
68
    cid?: string;
P
Peter Pan 已提交
69
    name: string;
70
    active: boolean;
P
Peter Pan 已提交
71 72
    path?: Route['path'];
    children?: NavbarItemType[];
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
}

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

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

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

    > .right {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        margin-right: -${rem(20)};
    }
111 112 113 114 115 116 117 118 119 120
`;

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 {
121
        ${size(rem(31), rem(98))}
122 123 124 125 126 127 128 129 130
        vertical-align: middle;
        margin-right: ${rem(8)};
    }

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

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

    &:hover {
P
Peter Pan 已提交
141
        background-color: var(--navbar-hover-background-color);
142 143
    }

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

        &.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'
                })}
            }
        }
180 181 182
    }
`;

P
Peter Pan 已提交
183
const SubNavWrapper = styled.div`
P
Peter Pan 已提交
184 185 186 187
    overflow: hidden;
    border-radius: ${borderRadius};
`;

188
const NavItemChild = styled.div<{active?: boolean}>`
P
Peter Pan 已提交
189 190 191 192 193
    display: block;
    line-height: 3em;

    &,
    &:visited {
P
Peter Pan 已提交
194
        color: ${props => (props.active ? 'var(--primary-color)' : 'var(--text-color)')};
P
Peter Pan 已提交
195 196 197
    }

    &:hover {
P
Peter Pan 已提交
198
        background-color: var(--background-focused-color);
P
Peter Pan 已提交
199 200
    }

201 202 203 204 205
    > a {
        display: block;
        padding: 0 ${rem(20)};
    }
`;
P
Peter Pan 已提交
206

P
Peter Pan 已提交
207 208 209 210 211 212 213 214 215
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 已提交
216 217
        const classNames = useClassNames('nav-text', {'dropdown-icon': showDropdownIcon}, [showDropdownIcon]);

P
Peter Pan 已提交
218 219 220 221
        if (path) {
            return (
                <NavItem active={active} ref={ref}>
                    <NavbarLink to={path} className="nav-link">
P
Peter Pan 已提交
222
                        <span className={classNames}>{children}</span>
P
Peter Pan 已提交
223 224 225 226
                    </NavbarLink>
                </NavItem>
            );
        }
P
Peter Pan 已提交
227 228

        return (
229
            <NavItem active={active} ref={ref}>
P
Peter Pan 已提交
230
                <span className={classNames}>{children}</span>
231
            </NavItem>
P
Peter Pan 已提交
232 233
        );
    }
P
Peter Pan 已提交
234
);
P
Peter Pan 已提交
235 236 237

NavbarItem.displayName = 'NavbarItem';

P
Peter Pan 已提交
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 263 264 265 266 267
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>
);

268
const Navbar: FunctionComponent = () => {
269
    const history = useHistory();
P
Peter Pan 已提交
270
    const {t, i18n} = useTranslation('common');
271
    const {pathname} = useLocation();
272
    const [navList, setNavlist] = useState<string[]>([]);
273 274 275 276 277 278 279
    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]);
280 281 282 283 284 285 286
    const routeEm: any = useMemo(() => {
        return {
            scalar: 'scalar',
            histogram: 'histogram',
            image: 'image',
            audio: 'audio',
            text: 'text',
R
RotPublic 已提交
287
            graphStatic: 'static_graph',
288 289 290 291 292 293 294 295 296 297
            graphDynamic: 'dynamic_graph',
            'high-dimensional': 'embeddings',
            'pr-curve': 'pr_curve',
            'roc-curve': 'roc_curve',
            profiler: 'profiler',
            'hyper-parameter': 'hyper_parameters',
            x2paddle: 'x2paddle',
            fastdeploy_server: 'fastdeploy_server'
        };
    }, []);
298
    const currentPath = useMemo(() => pathname.replace(BASE_URI, ''), [pathname]);
P
Peter Pan 已提交
299

300
    const [components] = useComponents();
R
RotPublic 已提交
301 302
    const routePush = (route: any, component: any) => {
        const Components = isArray(component) ? [...component] : [...component.values()];
303 304
        if (navList.includes(routeEm[route.id])) {
            // debugger;
P
Peter Pan 已提交
305

306 307 308 309 310 311 312 313 314 315
            return true;
            // setDefaultRoute(route.id);
        }
        if (route.children) {
            for (const Route of route.children) {
                routePush(Route, Components);
            }
        }
    };
    const newcomponents = useMemo(() => {
R
RotPublic 已提交
316 317
        const Components = new Map();

318 319 320 321 322
        const parent: any[] = [];
        if (navList.length > 0) {
            for (const item of components) {
                // const Id: any = item.id;
                if (navList.includes(routeEm[item.id])) {
R
RotPublic 已提交
323 324
                    // Components.push(item);
                    Components.set(item.id, item);
325 326 327 328 329 330
                }
                if (item.children) {
                    for (const Route of item.children) {
                        const flag = routePush(Route, Components);
                        if (flag && !parent.includes(item.id)) {
                            parent.push(item.id);
R
RotPublic 已提交
331 332 333 334 335 336 337 338 339 340 341 342 343
                            const newItems = {
                                ...item,
                                children: [Route]
                            };
                            Components.set(item.id, newItems);
                        } else if (flag && parent.includes(item.id)) {
                            // debugger;
                            const newItem = Components.get(item.id);
                            const newItems = {
                                ...newItem,
                                children: [...newItem.children, Route]
                            };
                            Components.set(item.id, newItems);
344 345 346 347 348
                        }
                    }
                }
            }
        }
R
RotPublic 已提交
349 350 351
        console.log('Components', [...Components], Components);
        // debugger;
        return [...Components.values()];
352 353 354 355 356 357
    }, [components, navList]);
    const componentsInNavbar = useMemo(() => newcomponents.slice(0, MAX_ITEM_COUNT_IN_NAVBAR), [newcomponents]);
    const flattenMoreComponents = useMemo(
        () => flatten(newcomponents.slice(MAX_ITEM_COUNT_IN_NAVBAR)),
        [newcomponents]
    );
R
RotPublic 已提交
358
    const componentsInMoreMenu: any = useMemo(
P
Peter Pan 已提交
359 360 361 362 363 364 365 366
        () =>
            flattenMoreComponents.map(item => ({
                ...item,
                active: currentPath === item.path
            })),
        [currentPath, flattenMoreComponents]
    );
    const [navItemsInNavbar, setNavItemsInNavbar] = useState<NavbarItemType[]>([]);
R
RotPublic 已提交
367 368
    const routesChange = (route: any, parentPath?: any) => {
        // debugger;
369 370
        if (navList.includes(routeEm[route.id])) {
            // debugger;
R
RotPublic 已提交
371 372 373 374 375 376 377
            if (parentPath) {
                history.push(`${parentPath}/${route.id}`);
                return true;
            } else {
                history.push(`/${route.id}`);
                return true;
            }
378 379
            // setDefaultRoute(route.id);
        }
R
RotPublic 已提交
380 381 382
        if (route.children) {
            for (const Route of route.children) {
                routesChange(Route, `/${route.id}`);
383 384
            }
        }
R
RotPublic 已提交
385
        // return false;
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403
    };
    useEffect(() => {
        // setLoading(true);
        fetcher('/component_tabs').then((res: any) => {
            setNavlist(res);
        });
    }, []);
    useEffect(() => {
        // const defaultRoute = routes;
        if (navList.length > 0) {
            for (const route of routes) {
                const flag = routesChange(route);
                if (flag) {
                    return;
                }
            }
        }
    }, [navList]);
P
Peter Pan 已提交
404
    useEffect(() => {
P
Peter Pan 已提交
405 406
        setNavItemsInNavbar(oldItems =>
            componentsInNavbar.map(item => {
R
RotPublic 已提交
407
                const children = item.children?.map((child: any) => ({
P
Peter Pan 已提交
408 409 410 411
                    ...child,
                    active: child.path === currentPath
                }));
                if (item.children && !item.path) {
R
RotPublic 已提交
412
                    const child = item.children.find((child: any) => child.path === currentPath);
P
Peter Pan 已提交
413 414 415 416
                    if (child) {
                        return {
                            ...item,
                            cid: child.id,
P
Peter Pan 已提交
417
                            name: child.name,
P
Peter Pan 已提交
418 419 420 421 422 423 424 425 426 427
                            path: currentPath,
                            active: true,
                            children
                        };
                    } else {
                        const oldItem = oldItems.find(oldItem => oldItem.id === item.id);
                        if (oldItem) {
                            return {
                                ...item,
                                ...oldItem,
R
RotPublic 已提交
428
                                name: item.children?.find((c: any) => c.id === oldItem.cid)?.name ?? item.name,
P
Peter Pan 已提交
429 430 431 432 433 434 435 436 437 438 439 440 441
                                active: false,
                                children
                            };
                        }
                    }
                }
                return {
                    ...item,
                    active: currentPath === item.path,
                    children
                };
            })
        );
442 443
    }, [componentsInNavbar, currentPath, navList]);
    console.log('componentsInNavbar', componentsInNavbar);
444 445 446

    return (
        <Nav>
447
            <div className="left">
448
                <Logo href={appendApiToken(BASE_URI + '/index')}>
449
                    <img alt="PaddlePaddle" src={PUBLIC_PATH + logo} />
450 451
                    <span>VisualDL</span>
                </Logo>
P
Peter Pan 已提交
452
                {navItemsInNavbar.map(item => {
P
Peter Pan 已提交
453 454
                    if (item.children) {
                        return (
P
Peter Pan 已提交
455 456 457 458
                            <SubNav
                                menu={item.children}
                                active={item.active}
                                path={item.path}
P
Peter Pan 已提交
459 460
                                key={item.active ? `${item.id}-activated` : item.id}
                            >
P
Peter Pan 已提交
461 462
                                {item.name}
                            </SubNav>
P
Peter Pan 已提交
463 464
                        );
                    }
P
Peter Pan 已提交
465 466 467 468 469
                    return (
                        <NavbarItem active={item.active} path={item.path} key={item.id}>
                            {item.name}
                        </NavbarItem>
                    );
470
                })}
P
Peter Pan 已提交
471 472 473 474 475
                {componentsInMoreMenu.length ? (
                    <SubNav menu={componentsInMoreMenu} showDropdownIcon>
                        {t('common:more')}
                    </SubNav>
                ) : null}
476 477
            </div>
            <div className="right">
P
Peter Pan 已提交
478 479 480 481 482 483 484 485 486
                <Tippy
                    placement="bottom-end"
                    animation="shift-away-subtle"
                    interactive
                    arrow={false}
                    offset={[18, 0]}
                    hideOnClick={false}
                    role="menu"
                    content={
P
Peter Pan 已提交
487
                        <SubNavWrapper>
P
Peter Pan 已提交
488
                            <ThemeToggle />
P
Peter Pan 已提交
489
                        </SubNavWrapper>
P
Peter Pan 已提交
490 491 492 493 494 495
                    }
                >
                    <NavItem className="nav-item">
                        <Icon type="theme" />
                    </NavItem>
                </Tippy>
496
                <NavItem className="nav-item" onClick={changeLanguage}>
497 498
                    <Language />
                </NavItem>
499
                <NavItem className="nav-item" onClick={() => ee.emit('refresh')}>
500 501 502
                    <Icon type="refresh" />
                </NavItem>
            </div>
503 504 505 506 507
        </Nav>
    );
};

export default Navbar;