Files
qinglong/src/layouts/index.tsx
T

424 lines
12 KiB
TypeScript

import config from '@/utils/config';
import { useCtx, useTheme } from '@/utils/hooks';
import { request } from '@/utils/http';
import {
LogoutOutlined,
MenuFoldOutlined,
MenuUnfoldOutlined,
UserOutlined,
} from '@ant-design/icons';
import ProLayout, { PageLoading } from '@ant-design/pro-layout';
import { history, Link, Outlet, useLocation } from '@umijs/max';
import * as DarkReader from '@umijs/ssr-darkreader';
import { Avatar, Badge, Dropdown, Image, MenuProps, Tooltip } from 'antd';
import React, { useEffect, useState } from 'react';
import intl from 'react-intl-universal';
import vhCheck from 'vh-check';
import defaultProps from './defaultProps';
import './index.less';
import { init } from '../utils/init';
import WebSocketManager from '../utils/websocket';
import { observePageLoadTiming } from '../utils/navigationTiming';
import UpgradeNotice from '@/components/UpgradeNotice';
import { completionKey, reloadKey, upgradeStore } from '@/hooks/useUpgrade';
export interface SharedContext {
headerStyle: React.CSSProperties;
isPhone: boolean;
siteTitle: string;
theme: 'vs' | 'vs-dark';
user: any;
reloadUser: (needLoading?: boolean) => void;
reloadSystemConfig: () => void;
reloadTheme: () => void;
systemInfo: TSystemInfo;
}
interface TSystemInfo {
branch: 'develop' | 'master';
isInitialized: boolean;
publishTime: number;
version: string;
changeLog: string;
changeLogLink: string;
}
export default function () {
const location = useLocation();
const ctx = useCtx();
const { theme, reloadTheme } = useTheme();
const [user, setUser] = useState<any>({});
const [loading, setLoading] = useState<boolean>(true);
const [systemInfo, setSystemInfo] = useState<TSystemInfo>();
const [siteTitle, setSiteTitle] = useState(
() =>
localStorage.getItem('qinglong_panel_title')?.trim() || intl.get('青龙'),
);
const [collapsed, setCollapsed] = useState(false);
const [initLoading, setInitLoading] = useState<boolean>(true);
const observeUpgrade =
Boolean(user.username) &&
!['/login', '/initialization'].includes(location.pathname);
const {
enable: enableDarkMode,
disable: disableDarkMode,
exportGeneratedCSS: collectCSS,
setFetchMethod,
auto: followSystemColorScheme,
} = DarkReader || {};
const logout = () => {
request.post(`${config.apiPrefix}user/logout`).then(() => {
localStorage.removeItem(config.authKey);
history.push('/login');
});
};
const getSystemInfo = () => {
request
.get(`${config.apiPrefix}system`)
.then(({ code, data }) => {
if (code === 200) {
setSystemInfo(data);
if (!data.isInitialized) {
history.push('/initialization');
} else {
init(data.version);
getUser();
}
}
})
.catch((error) => {
console.log(error);
});
};
const getUser = (needLoading = true) => {
needLoading && setLoading(true);
request
.get(`${config.apiPrefix}user`)
.then(({ code, data }) => {
if (code === 200 && data.username) {
setUser(data);
if (location.pathname === '/') {
history.push('/dashboard');
}
}
needLoading && setLoading(false);
})
.catch((error) => {
console.log(error);
});
};
const getHealthStatus = () => {
request
.get(`${config.apiPrefix}health`)
.then((res) => {
if (res?.data?.status === 'ok') {
getSystemInfo();
} else {
history.push('/error');
}
})
.catch(() => {
// Health is anonymous; a failure must not trigger a page reload loop.
history.push('/error');
})
.finally(() => setInitLoading(false));
};
const reloadUser = (needLoading = false) => {
getUser(needLoading);
};
const reloadSystemConfig = () => {
request
.get(`${config.apiPrefix}system/config`)
.then(({ data }: any) => {
const panelTitle = data?.info?.panelTitle?.trim();
if (panelTitle) {
setSiteTitle(panelTitle);
localStorage.setItem('qinglong_panel_title', panelTitle);
} else {
setSiteTitle(intl.get('青龙'));
localStorage.removeItem('qinglong_panel_title');
}
if (!data?.info?.lang) {
const browserLang =
localStorage.getItem('lang') ||
navigator.language?.slice(0, 2) ||
'zh';
request
.put(`${config.apiPrefix}system/config/lang`, { lang: browserLang })
.catch(() => {});
}
})
.catch(() => {});
};
useEffect(() => {
if (systemInfo && systemInfo.isInitialized && !user) {
getUser();
}
}, [location.pathname]);
useEffect(() => {
getHealthStatus();
}, []);
useEffect(() => {
// A reload during restart may initially land on the health error page.
// Keep recovering the accepted job even before the sidebar can mount.
if (
observeUpgrade ||
sessionStorage.getItem(reloadKey) ||
sessionStorage.getItem(completionKey)
) {
return upgradeStore.subscribe(() => {});
}
}, [observeUpgrade]);
useEffect(() => {
reloadSystemConfig();
}, []);
useEffect(() => {
if (!['/login', '/initialization', '/error'].includes(location.pathname)) {
return;
}
const title =
(config.documentTitleMap as any)[location.pathname] || intl.get('未找到');
document.title = `${title} - ${siteTitle}`;
}, [location.pathname, siteTitle]);
useEffect(() => {
if (theme === 'vs-dark') {
document.body.setAttribute('data-dark', 'true');
} else {
document.body.setAttribute('data-dark', 'false');
}
}, [theme]);
useEffect(() => {
vhCheck();
const _theme = localStorage.getItem('qinglong_dark_theme') || 'auto';
if (typeof window === 'undefined') return;
if (typeof window.matchMedia === 'undefined') return;
if (!DarkReader) {
return () => null;
}
setFetchMethod(fetch);
if (_theme === 'dark') {
enableDarkMode({});
} else if (_theme === 'light') {
disableDarkMode();
} else {
followSystemColorScheme({});
}
return () => {
disableDarkMode();
};
}, []);
useEffect(() => {
if (!user || !user.username) return;
const ws = WebSocketManager.getInstance(
`${window.location.origin}${
config.apiPrefix
}ws?token=${localStorage.getItem(config.authKey)}`,
);
return () => {
ws.close();
};
}, [user]);
useEffect(() => {
return observePageLoadTiming((durations) => {
const metrics = [
['白屏时间', durations.responseTime],
['请求完毕至DOM加载', durations.domReadyTime],
['解释DOM树耗时', durations.domParseTime],
['从开始至load总耗时', durations.loadTime],
] as const;
for (const [label, duration] of metrics) {
if (duration !== undefined) console.log(intl.get(label, { duration }));
}
});
}, []);
if (initLoading) {
return <PageLoading />;
}
if (['/login', '/initialization', '/error'].includes(location.pathname)) {
if (systemInfo?.isInitialized && location.pathname === '/initialization') {
history.push('/dashboard');
}
if (systemInfo || location.pathname === '/error') {
return (
<Outlet
context={{
...ctx,
theme,
user,
reloadUser,
reloadSystemConfig,
reloadTheme,
siteTitle,
systemInfo,
}}
/>
);
}
}
const menu: MenuProps = {
items: [
{
label: intl.get('退出登录'),
className: 'side-menu-user-drop-menu',
onClick: logout,
key: 'logout',
icon: <LogoutOutlined />,
},
],
};
return loading ? (
<PageLoading />
) : (
<ProLayout
selectedKeys={[location.pathname]}
loading={loading}
logo={
<>
<Image preview={false} src="https://qn.whyour.cn/logo.png" />
<div className="brand-title">
<span className="brand-name">{intl.get('青龙')}</span>
{systemInfo?.version && (
<Tooltip
title={`v${systemInfo.version} · ${
systemInfo.branch === 'develop'
? intl.get('开发版')
: intl.get('正式版')
}`}
>
<span
className="brand-version-link"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
window.open(systemInfo.changeLogLink, '_blank');
}}
>
<Badge size="small" dot={systemInfo.branch === 'develop'}>
<span className="brand-version">v{systemInfo.version}</span>
</Badge>
</span>
</Tooltip>
)}
</div>
</>
}
title={false}
menuFooterRender={(props) => (
<UpgradeNotice
collapsed={Boolean(props?.collapsed)}
systemInfo={systemInfo}
/>
)}
menuItemRender={(menuItemProps: any, defaultDom: any) => {
if (
menuItemProps.isUrl ||
!menuItemProps.path ||
location.pathname === menuItemProps.path
) {
return defaultDom;
}
return <Link to={menuItemProps.path}>{defaultDom}</Link>;
}}
pageTitleRender={(props, pageName, info) => {
const title =
(config.documentTitleMap as any)[location.pathname] ||
intl.get('未找到');
return `${title} - ${siteTitle}`;
}}
onCollapse={setCollapsed}
collapsed={collapsed}
rightContentRender={() =>
ctx.isPhone && (
<Dropdown menu={menu} placement="bottomRight" trigger={['click']}>
<span className="side-menu-user-wrapper">
<Avatar
shape="square"
size="small"
icon={<UserOutlined />}
src={
user.avatar ? `${config.apiPrefix}static/${user.avatar}` : ''
}
/>
<span className="side-menu-username" title={user.username}>
{user.username}
</span>
</span>
</Dropdown>
)
}
collapsedButtonRender={(collapsed) => (
<span
className="side-menu-container"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
}}
>
{!collapsed && !ctx.isPhone && (
<Dropdown menu={menu} placement="topLeft" trigger={['hover']}>
<span className="side-menu-user-wrapper">
<Avatar
shape="square"
size="small"
icon={<UserOutlined />}
src={
user.avatar
? `${config.apiPrefix}static/${user.avatar}`
: ''
}
/>
<span className="side-menu-username" title={user.username}>
{user.username}
</span>
</span>
</Dropdown>
)}
<span
className="side-menu-collapse-button"
onClick={() => setCollapsed(!collapsed)}
>
{collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
</span>
</span>
)}
{...defaultProps}
>
<Outlet
context={{
...ctx,
theme,
user,
reloadUser,
reloadSystemConfig,
reloadTheme,
siteTitle,
systemInfo,
}}
/>
</ProLayout>
);
}