ant-design/.dumi/theme/slots/Header/index.tsx
二货爱吃白萝卜 cbcfd38ca7
docs: v5 site upgrade (#38328)
* build: try to use dumi as doc tool

* docs: migrate demo structure to dumi way

* refactor: use type export & import

* docs: migrate demo previewer to dumi

* docs: create empty layout & components

* docs: apply custom rehype plugin

* docs: create empty extra pages

* docs: Add Banner component

* chore: move theme tsconfig.json

* docs: home page init

* docs: migrate header (#37896)

* docs: header

* docs: update

* docs: home init

* clean up

* test: fix site lint

* chore: tsc ignore demo

* chore: dumi demo migrate script

* chore: cards

* docs: home layout

* docs: Update locale logic

* docs: fix getLink logic

* chore: fix ci (#37899)

* chore: fix ci

* ci: remove check-ts-demo

* ci: preview build

* test: ignore demo.tsx

* chore: update script

* test: update snapshot

* test: update node and image test

* chore: add .surgeignore

* docs: layout providers (#37908)

* docs: add components sidebar (#37923)

* docs: sidebar

* docs: update docs title

* docs: update design doc

* chore: code clean

* docs: handle changelog page

* docs: add title

* docs: add subtitle

* docs: active header nav

* chore: code clean

* docs: overview

* chore: code clean

* docs: update intl (#37918)

* docs: update intl

* chore: code clean

* docs: update favicons

* chore: update testPathIgnorePatterns

* chore: code clean

* chore: code clean

* chore: copy 404.html (#37996)

* docs: Home page theme picker

* chore: Update migrate script

* docs: home page update

* docs: theme editor style

* docs: theme lang

* chore: update migrate.js

* docs: fix demo (#38094)

* chore: update migrate.js

* docs: update md

* docs: update demo

* test: fix snapshot

* chore: move debug to code attr in migrate script

* chore: update md

Co-authored-by: PeachScript <scdzwyxst@gmail.com>

* feat: overview page

* feat: Migrate `404` page (#38118)

* feat: migrate IconSearch component (#37916)

* feat<site/IconSearch>: copy IconDisplay from site to .dumi

* feat<site/IconSearch>: change docs of icon

* feat<site/IconSearch>: tweak

* feat<site/IconSearch>: use useIntl instead of injectIntl

* feat<site/IconSearch>: fix ts type error

* feat<site/IconSearch>: use intl.formatMessage to render text

* docs: Adjust home btn sizw

* docs: Update doc

* feat: v5 site overview page (#38131)

* feat: site

* fix: fix

* feat: v5 site overview page

* fix: fix path

* fix: fix

* fix: fix

* docs: fix margin logic

* feat: v5 site change-log page (#38137)

* feat: v5 site change-log page (#38162)

* docs: site redirect to home pag

* docs: theme picker

* docs: use react-intl from dumi (#38183)

* docs: Theme Picker

* docs: update dumi config

* docs: home back fix

* docs: picker colorful

* docs: locale of it

* docs: update components desc

* docs: site of links

* docs: update components list

* docs: update desc

* feat: Migrate `DemoWrapper` component (#38166)

* feat: Migrate `DemoWrapper` component

* feat: remove invalid comments and add comment for `key` prop

* docs: FloatButton pure panel

* chore: update demo

* chore: update dumi config

* Revert "chore: update demo"

This reverts commit 028265d3ba.

* chore: test logic adjust to support cnpm modules

* chore: add locale alias

* docs: /index to /

* docs: add locale redirect head script

* chore: adjust compact

* docs: fix missing token

* feat: compact switch

* chore: code clean

* docs: update home

* docs: fix radius token

* docs: hash of it

* chore: adjust home page

* docs: Add background map

* docs: site theme bac logic

* docs: avatar

* docs: update logo color

* docs: home banner

* docs: adjust tour size

* docs: purepanl update

* docs: transfooter

* docs: update banner gif

* docs: content (#38361)

* docs: title & EditButton

* docs: content

* chore: fix toc

* docs: resource page

* docs: transform resource data from hast

* docs: filename & Resource Card

* chore: enable prerender

* chore: remove less

* docs: toc style

* chore: fix lint

* docs: fix Layout page

* docs: fix CP page

* chore: update demos

* docs: workaround for export dynamic html

* chore: enable demo eslint

* docs: table style

* fix: header shadow

* chore: update snapshot

* fix: toc style

* docs: add title

* docs: Adjust site

* feat: helmet

* docs: site css

* fix: description

* feat: toc debug

* docs: update config-provider

* feat: use colorPanel

* fix: colorPanel value

* feat: anchor ink ball style

* feat: apply theme editor

* fix: code block style

* chore: update demo

* chore: fix lint

* chore: code clean

* chore: update snapshot

* feat: ts2js

* chore: description

* docs: site ready for ssr

includes:
- move client render logic to useEffect in site theme
- extract antd cssinjs to a single css file like bisheng
- workaround to support react@18 pipeableStream for emotion

* chore: bump testing lib

* docs: font size of title

* chore: remove react-sortable-hoc

* chore: update snapshot

* chore: update script

Co-authored-by: PeachScript <scdzwyxst@gmail.com>
Co-authored-by: MadCcc <1075746765@qq.com>
Co-authored-by: zqran <uuxnet@gmail.com>
Co-authored-by: TrickyPi <530257315@qq.com>
Co-authored-by: lijianan <574980606@qq.com>
2022-11-09 12:28:04 +08:00

388 lines
11 KiB
TypeScript

import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import { FormattedMessage, useIntl } from 'dumi';
import classNames from 'classnames';
import { Button, Col, Modal, Popover, Row, Select } from 'antd';
import { MenuOutlined } from '@ant-design/icons';
import canUseDom from 'rc-util/lib/Dom/canUseDom';
import type { DirectionType } from 'antd/es/config-provider';
import * as utils from '../../utils';
import { getThemeConfig, ping } from '../../utils';
import packageJson from '../../../../package.json';
import Logo from './Logo';
import SearchBar from './SearchBar';
import More from './More';
import Navigation from './Navigation';
import Github from './Github';
import type { SiteContextProps } from '../SiteContext';
import SiteContext from '../SiteContext';
import { AlgoliaConfig } from './algolia-config';
import { useLocation, useNavigate } from 'dumi';
import { ClassNames, css } from '@emotion/react';
import useSiteToken from '../../../hooks/useSiteToken';
import useLocale from '../../../hooks/useLocale';
const RESPONSIVE_XS = 1120;
const RESPONSIVE_SM = 1200;
const { Option } = Select;
const antdVersion: string = packageJson.version;
const useStyle = () => {
const { token } = useSiteToken();
return {
header: css`
position: relative;
z-index: 10;
max-width: 100%;
background: ${token.colorBgContainer};
box-shadow: ${token.boxShadow};
@media only screen and (max-width: ${token.mobileMaxWidth}px) {
text-align: center;
}
`,
menuRow: css`
display: flex;
align-items: center;
margin: 0;
> * {
flex: none;
margin: 0 12px 0 0;
&:last-child {
margin-right: 40px;
}
}
${token.antCls}-row-rtl & {
> * {
&:last-child {
margin-right: 12px;
margin-left: 40px;
}
}
}
`,
headerButton: css`
color: ${token.colorText};
border-color: ${token.colorBorder};
`,
popoverMenu: {
width: 300,
[`${token.antCls}-popover-inner-content`]: {
padding: 0,
},
},
};
};
export interface HeaderProps {
changeDirection: (direction: DirectionType) => void;
}
let docsearch: any;
const triggerDocSearchImport = () => {
if (docsearch) {
return Promise.resolve();
}
// @ts-ignore
return import('docsearch.js').then(ds => {
docsearch = ds.default;
});
};
function initDocSearch({ isZhCN, navigate }: { isZhCN: boolean; navigate: any }) {
if (!canUseDom()) {
return;
}
triggerDocSearchImport().then(() => {
docsearch({
appId: AlgoliaConfig.appId,
apiKey: AlgoliaConfig.apiKey,
indexName: AlgoliaConfig.indexName,
inputSelector: '#search-box input',
algoliaOptions: AlgoliaConfig.getSearchParams(isZhCN),
transformData: AlgoliaConfig.transformData,
debug: AlgoliaConfig.debug,
// https://docsearch.algolia.com/docs/behavior#handleselected
handleSelected(input: any, _$1: unknown, suggestion: any) {
navigate(suggestion.url);
setTimeout(() => {
input.setVal('');
});
},
});
});
}
const SHOULD_OPEN_ANT_DESIGN_MIRROR_MODAL = 'ANT_DESIGN_DO_NOT_OPEN_MIRROR_MODAL';
function disableAntdMirrorModal() {
window.localStorage.setItem(SHOULD_OPEN_ANT_DESIGN_MIRROR_MODAL, 'true');
}
function shouldOpenAntdMirrorModal() {
return !window.localStorage.getItem(SHOULD_OPEN_ANT_DESIGN_MIRROR_MODAL);
}
interface HeaderState {
menuVisible: boolean;
windowWidth: number;
searching: boolean;
showTechUIButton: boolean;
}
const Header: React.FC<HeaderProps> = props => {
const intl = useIntl();
const { changeDirection } = props;
const [, lang] = useLocale();
const [isClient, setIsClient] = React.useState(false);
const themeConfig = getThemeConfig();
const [headerState, setHeaderState] = useState<HeaderState>({
menuVisible: false,
windowWidth: 1400,
searching: false,
showTechUIButton: false,
});
const { direction, isMobile } = useContext<SiteContextProps>(SiteContext);
const pingTimer = useRef<NodeJS.Timeout | null>(null);
const location = useLocation();
const { pathname, search } = location;
const navigate = useNavigate();
const style = useStyle();
const handleHideMenu = useCallback(() => {
setHeaderState(prev => ({ ...prev, menuVisible: false }));
}, []);
const onWindowResize = useCallback(() => {
setHeaderState(prev => ({ ...prev, windowWidth: window.innerWidth }));
}, []);
const onTriggerSearching = useCallback((searching: boolean) => {
setHeaderState(prev => ({ ...prev, searching }));
}, []);
const handleShowMenu = useCallback(() => {
setHeaderState(prev => ({ ...prev, menuVisible: true }));
}, []);
const onMenuVisibleChange = useCallback((visible: boolean) => {
setHeaderState(prev => ({ ...prev, menuVisible: visible }));
}, []);
const onDirectionChange = useCallback(() => {
changeDirection?.(direction !== 'rtl' ? 'rtl' : 'ltr');
}, [direction]);
useEffect(() => {
handleHideMenu();
}, [location]);
useEffect(() => {
setIsClient(typeof window !== 'undefined');
initDocSearch({ isZhCN: lang === 'cn', navigate });
onWindowResize();
window.addEventListener('resize', onWindowResize);
pingTimer.current = ping(status => {
if (status !== 'timeout' && status !== 'error') {
setHeaderState(prev => ({ ...prev, showTechUIButton: true }));
if (
process.env.NODE_ENV === 'production' &&
window.location.host !== 'ant-design.antgroup.com' &&
shouldOpenAntdMirrorModal()
) {
Modal.confirm({
title: '提示',
content: '内网用户推荐访问国内镜像以获得极速体验~',
okText: '🚀 立刻前往',
cancelText: '不再弹出',
closable: true,
onOk() {
window.open('https://ant-design.antgroup.com', '_self');
disableAntdMirrorModal();
},
onCancel() {
disableAntdMirrorModal();
},
});
}
}
});
return () => {
window.removeEventListener('resize', onWindowResize);
if (pingTimer.current) {
clearTimeout(pingTimer.current);
}
};
}, []);
// eslint-disable-next-line class-methods-use-this
const handleVersionChange = useCallback((url: string) => {
const currentUrl = window.location.href;
const currentPathname = window.location.pathname;
if (/overview/.test(currentPathname) && /0?[1-39][0-3]?x/.test(url)) {
window.location.href = currentUrl
.replace(window.location.origin, url)
.replace(/\/components\/overview/, `/docs${/0(9|10)x/.test(url) ? '' : '/react'}/introduce`)
.replace(/\/$/, '');
return;
}
window.location.href = currentUrl.replace(window.location.origin, url);
}, []);
const onLangChange = useCallback(() => {
const currentProtocol = `${window.location.protocol}//`;
const currentHref = window.location.href.slice(currentProtocol.length);
if (utils.isLocalStorageNameSupported()) {
localStorage.setItem('locale', utils.isZhCN(pathname) ? 'en-US' : 'zh-CN');
}
window.location.href =
currentProtocol +
currentHref.replace(
window.location.pathname,
utils.getLocalizedPathname(pathname, !utils.isZhCN(pathname), search).pathname,
);
}, [location]);
const nextDirectionText = useMemo<string>(
() => (direction !== 'rtl' ? 'RTL' : 'LTR'),
[direction],
);
const getDropdownStyle = useMemo<React.CSSProperties>(
() => (direction === 'rtl' ? { direction: 'ltr', textAlign: 'right' } : {}),
[direction],
);
const { menuVisible, windowWidth, searching, showTechUIButton } = headerState;
const docVersions: Record<string, string> = {
[antdVersion]: antdVersion,
...themeConfig?.docVersions,
};
const versionOptions = Object.keys(docVersions).map(version => (
<Option value={docVersions[version]} key={version}>
{version}
</Option>
));
const isHome = ['', 'index', 'index-cn'].includes(pathname);
const isZhCN = lang === 'cn';
const isRTL = direction === 'rtl';
let responsive: null | 'narrow' | 'crowded' = null;
if (windowWidth < RESPONSIVE_XS) {
responsive = 'crowded';
} else if (windowWidth < RESPONSIVE_SM) {
responsive = 'narrow';
}
const headerClassName = classNames({
clearfix: true,
'home-header': isHome,
});
const sharedProps = {
isZhCN,
isRTL,
isClient,
};
const navigationNode = (
<Navigation
key="nav"
{...sharedProps}
responsive={responsive}
isMobile={isMobile}
showTechUIButton={showTechUIButton}
directionText={nextDirectionText}
onLangChange={onLangChange}
onDirectionChange={onDirectionChange}
/>
);
let menu: (React.ReactElement | null)[] = [
navigationNode,
<Select
key="version"
className="version"
size="small"
defaultValue={antdVersion}
onChange={handleVersionChange}
dropdownStyle={getDropdownStyle}
getPopupContainer={trigger => trigger.parentNode}
>
{versionOptions}
</Select>,
<Button size="small" onClick={onLangChange} css={style.headerButton} key="lang-button">
<FormattedMessage id="app.header.lang" />
</Button>,
<Button
size="small"
onClick={onDirectionChange}
css={style.headerButton}
key="direction-button"
>
{nextDirectionText}
</Button>,
<More key="more" {...sharedProps} />,
<Github key="github" responsive={responsive} />,
];
if (windowWidth < RESPONSIVE_XS) {
menu = searching ? [] : [navigationNode];
} else if (windowWidth < RESPONSIVE_SM) {
menu = searching ? [] : menu;
}
const colProps = isHome
? [{ flex: 'none' }, { flex: 'auto' }]
: [
{ xxl: 4, xl: 5, lg: 6, md: 6, sm: 24, xs: 24 },
{ xxl: 20, xl: 19, lg: 18, md: 18, sm: 0, xs: 0 },
];
return (
<header css={style.header} className={headerClassName}>
{isMobile && (
<ClassNames>
{({ css }) => (
<Popover
overlayClassName={css(style.popoverMenu)}
placement="bottomRight"
content={menu}
trigger="click"
open={menuVisible}
arrowPointAtCenter
onOpenChange={onMenuVisibleChange}
>
<MenuOutlined className="nav-phone-icon" onClick={handleShowMenu} />
</Popover>
)}
</ClassNames>
)}
<Row style={{ flexFlow: 'nowrap', height: 64 }}>
<Col {...colProps[0]}>
<Logo {...sharedProps} location={location} />
</Col>
<Col {...colProps[1]} css={style.menuRow}>
<SearchBar
key="search"
{...sharedProps}
algoliaConfig={AlgoliaConfig}
responsive={responsive}
onTriggerFocus={onTriggerSearching}
/>
{!isMobile && menu}
</Col>
</Row>
</header>
);
};
export default Header;