HeaderBar.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. import React, { useContext, useEffect, useState } from 'react';
  2. import { Link, useNavigate } from 'react-router-dom';
  3. import { UserContext } from '../context/User';
  4. import { useSetTheme, useTheme } from '../context/Theme';
  5. import { useTranslation } from 'react-i18next';
  6. import { API, getLogo, getSystemName, isMobile, showSuccess } from '../helpers';
  7. import '../index.css';
  8. import fireworks from 'react-fireworks';
  9. import {
  10. IconClose,
  11. IconHelpCircle,
  12. IconHome,
  13. IconHomeStroked, IconIndentLeft,
  14. IconComment,
  15. IconKey, IconMenu,
  16. IconNoteMoneyStroked,
  17. IconPriceTag,
  18. IconUser,
  19. IconLanguage
  20. } from '@douyinfe/semi-icons';
  21. import { Avatar, Button, Dropdown, Layout, Nav, Switch, Tag } from '@douyinfe/semi-ui';
  22. import { stringToColor } from '../helpers/render';
  23. import Text from '@douyinfe/semi-ui/lib/es/typography/text';
  24. import { StyleContext } from '../context/Style/index.js';
  25. import { StatusContext } from '../context/Status/index.js';
  26. const HeaderBar = () => {
  27. const { t, i18n } = useTranslation();
  28. const [userState, userDispatch] = useContext(UserContext);
  29. const [styleState, styleDispatch] = useContext(StyleContext);
  30. const [statusState, statusDispatch] = useContext(StatusContext);
  31. let navigate = useNavigate();
  32. const [currentLang, setCurrentLang] = useState(i18n.language);
  33. const systemName = getSystemName();
  34. const logo = getLogo();
  35. const currentDate = new Date();
  36. // enable fireworks on new year(1.1 and 2.9-2.24)
  37. const isNewYear =
  38. (currentDate.getMonth() === 0 && currentDate.getDate() === 1);
  39. // Check if self-use mode is enabled
  40. const isSelfUseMode = statusState?.status?.self_use_mode_enabled || false;
  41. const isDemoSiteMode = statusState?.status?.demo_site_enabled || false;
  42. let buttons = [
  43. {
  44. text: t('首页'),
  45. itemKey: 'home',
  46. to: '/',
  47. },
  48. {
  49. text: t('控制台'),
  50. itemKey: 'detail',
  51. to: '/',
  52. },
  53. {
  54. text: t('定价'),
  55. itemKey: 'pricing',
  56. to: '/pricing',
  57. },
  58. {
  59. text: t('关于'),
  60. itemKey: 'about',
  61. to: '/about',
  62. },
  63. ];
  64. async function logout() {
  65. await API.get('/api/user/logout');
  66. showSuccess(t('注销成功!'));
  67. userDispatch({ type: 'logout' });
  68. localStorage.removeItem('user');
  69. navigate('/login');
  70. }
  71. const handleNewYearClick = () => {
  72. fireworks.init('root', {});
  73. fireworks.start();
  74. setTimeout(() => {
  75. fireworks.stop();
  76. setTimeout(() => {
  77. window.location.reload();
  78. }, 10000);
  79. }, 3000);
  80. };
  81. const theme = useTheme();
  82. const setTheme = useSetTheme();
  83. useEffect(() => {
  84. if (theme === 'dark') {
  85. document.body.setAttribute('theme-mode', 'dark');
  86. } else {
  87. document.body.removeAttribute('theme-mode');
  88. }
  89. // 发送当前主题模式给子页面
  90. const iframe = document.querySelector('iframe');
  91. if (iframe) {
  92. iframe.contentWindow.postMessage({ themeMode: theme }, '*');
  93. }
  94. if (isNewYear) {
  95. console.log('Happy New Year!');
  96. }
  97. }, [theme]);
  98. useEffect(() => {
  99. const handleLanguageChanged = (lng) => {
  100. setCurrentLang(lng);
  101. const iframe = document.querySelector('iframe');
  102. if (iframe) {
  103. iframe.contentWindow.postMessage({ lang: lng }, '*');
  104. }
  105. };
  106. i18n.on('languageChanged', handleLanguageChanged);
  107. return () => {
  108. i18n.off('languageChanged', handleLanguageChanged);
  109. };
  110. }, [i18n]);
  111. const handleLanguageChange = (lang) => {
  112. i18n.changeLanguage(lang);
  113. };
  114. return (
  115. <>
  116. <Layout>
  117. <div style={{ width: '100%' }}>
  118. <Nav
  119. className={'topnav'}
  120. mode={'horizontal'}
  121. renderWrapper={({ itemElement, isSubNav, isInSubNav, props }) => {
  122. const routerMap = {
  123. about: '/about',
  124. login: '/login',
  125. register: '/register',
  126. pricing: '/pricing',
  127. detail: '/detail',
  128. home: '/',
  129. chat: '/chat',
  130. };
  131. return (
  132. <div onClick={(e) => {
  133. if (props.itemKey === 'home') {
  134. styleDispatch({ type: 'SET_INNER_PADDING', payload: false });
  135. styleDispatch({ type: 'SET_SIDER', payload: false });
  136. } else {
  137. styleDispatch({ type: 'SET_INNER_PADDING', payload: true });
  138. if (!styleState.isMobile) {
  139. styleDispatch({ type: 'SET_SIDER', payload: true });
  140. }
  141. }
  142. }}>
  143. <Link
  144. className="header-bar-text"
  145. style={{ textDecoration: 'none' }}
  146. to={routerMap[props.itemKey]}
  147. >
  148. {itemElement}
  149. </Link>
  150. </div>
  151. );
  152. }}
  153. selectedKeys={[]}
  154. // items={headerButtons}
  155. onSelect={(key) => {}}
  156. header={styleState.isMobile?{
  157. logo: (
  158. <div style={{ display: 'flex', alignItems: 'center', position: 'relative' }}>
  159. {
  160. !styleState.showSider ?
  161. <Button icon={<IconMenu />} theme="light" aria-label={t('展开侧边栏')} onClick={
  162. () => styleDispatch({ type: 'SET_SIDER', payload: true })
  163. } />:
  164. <Button icon={<IconIndentLeft />} theme="light" aria-label={t('闭侧边栏')} onClick={
  165. () => styleDispatch({ type: 'SET_SIDER', payload: false })
  166. } />
  167. }
  168. {(isSelfUseMode || isDemoSiteMode) && (
  169. <Tag
  170. color={isSelfUseMode ? 'purple' : 'blue'}
  171. style={{
  172. position: 'absolute',
  173. top: '-8px',
  174. right: '-15px',
  175. fontSize: '0.7rem',
  176. padding: '0 4px',
  177. height: 'auto',
  178. lineHeight: '1.2',
  179. zIndex: 1,
  180. pointerEvents: 'none'
  181. }}
  182. >
  183. {isSelfUseMode ? t('自用模式') : t('演示站点')}
  184. </Tag>
  185. )}
  186. </div>
  187. ),
  188. }:{
  189. logo: (
  190. <img src={logo} alt='logo' />
  191. ),
  192. text: (
  193. <div style={{ position: 'relative', display: 'inline-block' }}>
  194. {systemName}
  195. {(isSelfUseMode || isDemoSiteMode) && (
  196. <Tag
  197. color={isSelfUseMode ? 'purple' : 'blue'}
  198. style={{
  199. position: 'absolute',
  200. top: '-10px',
  201. right: '-25px',
  202. fontSize: '0.7rem',
  203. padding: '0 4px',
  204. whiteSpace: 'nowrap',
  205. zIndex: 1,
  206. boxShadow: '0 0 3px rgba(255, 255, 255, 0.7)'
  207. }}
  208. >
  209. {isSelfUseMode ? t('自用模式') : t('演示站点')}
  210. </Tag>
  211. )}
  212. </div>
  213. ),
  214. }}
  215. items={buttons}
  216. footer={
  217. <>
  218. {isNewYear && (
  219. // happy new year
  220. <Dropdown
  221. position='bottomRight'
  222. render={
  223. <Dropdown.Menu>
  224. <Dropdown.Item onClick={handleNewYearClick}>
  225. Happy New Year!!!
  226. </Dropdown.Item>
  227. </Dropdown.Menu>
  228. }
  229. >
  230. <Nav.Item itemKey={'new-year'} text={'🎉'} />
  231. </Dropdown>
  232. )}
  233. {/* <Nav.Item itemKey={'about'} icon={<IconHelpCircle />} /> */}
  234. <>
  235. <Switch
  236. checkedText='🌞'
  237. size={styleState.isMobile?'default':'large'}
  238. checked={theme === 'dark'}
  239. uncheckedText='🌙'
  240. onChange={(checked) => {
  241. setTheme(checked);
  242. }}
  243. />
  244. </>
  245. <Dropdown
  246. position='bottomRight'
  247. render={
  248. <Dropdown.Menu>
  249. <Dropdown.Item
  250. onClick={() => handleLanguageChange('zh')}
  251. type={currentLang === 'zh' ? 'primary' : 'tertiary'}
  252. >
  253. 中文
  254. </Dropdown.Item>
  255. <Dropdown.Item
  256. onClick={() => handleLanguageChange('en')}
  257. type={currentLang === 'en' ? 'primary' : 'tertiary'}
  258. >
  259. English
  260. </Dropdown.Item>
  261. </Dropdown.Menu>
  262. }
  263. >
  264. <Nav.Item
  265. itemKey={'language'}
  266. icon={<IconLanguage />}
  267. />
  268. </Dropdown>
  269. {userState.user ? (
  270. <>
  271. <Dropdown
  272. position='bottomRight'
  273. render={
  274. <Dropdown.Menu>
  275. <Dropdown.Item onClick={logout}>{t('退出')}</Dropdown.Item>
  276. </Dropdown.Menu>
  277. }
  278. >
  279. <Avatar
  280. size='small'
  281. color={stringToColor(userState.user.username)}
  282. style={{ margin: 4 }}
  283. >
  284. {userState.user.username[0]}
  285. </Avatar>
  286. {styleState.isMobile?null:<Text>{userState.user.username}</Text>}
  287. </Dropdown>
  288. </>
  289. ) : (
  290. <>
  291. <Nav.Item
  292. itemKey={'login'}
  293. text={!styleState.isMobile?t('登录'):null}
  294. icon={<IconUser />}
  295. />
  296. {
  297. // Hide register option in self-use mode
  298. !styleState.isMobile && !isSelfUseMode && (
  299. <Nav.Item
  300. itemKey={'register'}
  301. text={t('注册')}
  302. icon={<IconKey />}
  303. />
  304. )
  305. }
  306. </>
  307. )}
  308. </>
  309. }
  310. ></Nav>
  311. </div>
  312. </Layout>
  313. </>
  314. );
  315. };
  316. export default HeaderBar;