Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
Copyright (C) 2025 QuantumNous
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as
|
||||
published by the Free Software Foundation, either version 3 of the
|
||||
License, or (at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
For commercial licensing, please contact support@quantumnous.com
|
||||
*/
|
||||
|
||||
import HeaderBar from './headerbar';
|
||||
import { Layout } from '@douyinfe/semi-ui';
|
||||
import SiderBar from './SiderBar';
|
||||
import App from '../../App';
|
||||
import { ToastContainer } from 'react-toastify';
|
||||
import React, {
|
||||
useContext,
|
||||
useEffect,
|
||||
useState,
|
||||
lazy,
|
||||
Suspense,
|
||||
useRef,
|
||||
} from 'react';
|
||||
import { useIsMobile } from '../../hooks/common/useIsMobile';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import {
|
||||
API,
|
||||
clearUserData,
|
||||
getUserData,
|
||||
getLogo,
|
||||
getSystemName,
|
||||
isAuthPagePath,
|
||||
showError,
|
||||
setStatusData,
|
||||
setUserData,
|
||||
} from '../../helpers';
|
||||
import { UserContext } from '../../context/User';
|
||||
import { StatusContext } from '../../context/Status';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import { applyTheme, setPresetOverrides } from '../../helpers/theme';
|
||||
// 用户问卷功能已禁用
|
||||
// import UserSurveyModal from '../common/modals/UserSurveyModal';
|
||||
import NewUserGiftModal from '../common/modals/NewUserGiftModal';
|
||||
|
||||
// 懒加载客服浮窗组件 - 非核心功能,延迟加载
|
||||
const CustomerServiceFloat = lazy(() => import('../customer-service'));
|
||||
|
||||
// 跑马灯公告组件
|
||||
import Marquee from './Marquee';
|
||||
|
||||
const { Sider, Content, Header } = Layout;
|
||||
|
||||
// 控制台欢迎语只打印一次(loadStatus 可能被多次触发)
|
||||
let consoleWelcomePrinted = false;
|
||||
const printConsoleWelcome = (status) => {
|
||||
if (consoleWelcomePrinted) return;
|
||||
consoleWelcomePrinted = true;
|
||||
const title = (status?.console_welcome_title || '').trim();
|
||||
const link = (status?.official_website || '').trim();
|
||||
if (!title && !link) return;
|
||||
console.log(
|
||||
`%c${title}%c${link ? ` 官网: ${link}` : ''}`,
|
||||
'color: #10b981; font-weight: bold; font-size: 24px;',
|
||||
'color: inherit; font-size: 14px;',
|
||||
);
|
||||
};
|
||||
|
||||
const PageLayout = () => {
|
||||
console.log('[PageLayout] Component rendering...');
|
||||
const [userState, userDispatch] = useContext(UserContext);
|
||||
const [statusState, statusDispatch] = useContext(StatusContext);
|
||||
const isMobile = useIsMobile();
|
||||
const [drawerOpen, setDrawerOpen] = useState(false);
|
||||
const { i18n } = useTranslation();
|
||||
const location = useLocation();
|
||||
|
||||
// 用户问卷弹窗状态 - 功能已禁用
|
||||
// const [showSurveyModal, setShowSurveyModal] = useState(false);
|
||||
// const surveyCheckedRef = useRef(false);
|
||||
|
||||
// 新用户注册赠送额度弹窗
|
||||
const [showGiftModal, setShowGiftModal] = useState(false);
|
||||
const [giftQuota, setGiftQuota] = useState(0);
|
||||
|
||||
const shouldInnerPadding =
|
||||
location.pathname.includes('/console') &&
|
||||
!location.pathname.startsWith('/console/chat') &&
|
||||
location.pathname !== '/console/playground';
|
||||
|
||||
const isConsoleRoute = location.pathname.startsWith('/console');
|
||||
const showSider = isConsoleRoute && (!isMobile || drawerOpen);
|
||||
const isHomePage = location.pathname === '/';
|
||||
|
||||
// 隐私政策和用户协议页面需要隐藏顶部工具栏
|
||||
const isLegalPage =
|
||||
location.pathname === '/user-agreement' ||
|
||||
location.pathname === '/privacy-policy';
|
||||
const hideHeader = isHomePage || isLegalPage;
|
||||
|
||||
// 这些页面有自己的滚动控制,不需要外部滚动
|
||||
const isExperienceCenter = location.pathname.includes('/experience-center');
|
||||
const isUserCenter = location.pathname.includes('/user-center');
|
||||
|
||||
// 认证页(登录/注册/企业登录等):内容垂直居中的独立屏
|
||||
const isAuthPage = isAuthPagePath(location.pathname);
|
||||
|
||||
// 企业管理页面有自己的布局和滚动控制。
|
||||
// 注意排除 /org/login、/org/register、/org/:slug/login 等认证页——
|
||||
// 它们没有内部滚动容器,若被禁用外层滚动,内容超出视口(如企业注册开启邮箱验证时)会被截断且无法滚动。
|
||||
const isOrgPage =
|
||||
location.pathname.startsWith('/org') &&
|
||||
location.pathname !== '/org/create' &&
|
||||
!isAuthPage;
|
||||
|
||||
// 需要禁用外层滚动的页面(这些页面内部有自己的滚动容器)
|
||||
const disableOuterScroll =
|
||||
isExperienceCenter || isUserCenter || isHomePage || isOrgPage;
|
||||
|
||||
// 需要显示可见滚动条的页面(覆盖 semi-layout 默认隐藏滚动条的行为)。
|
||||
// 认证页也纳入:内容确实超出视口时(小屏/长表单)用主题色滚动条明示,而不是隐形滚动导致卡片"莫名移动"。
|
||||
const isKeyManagement = location.pathname === '/key-management';
|
||||
const showVisibleScrollbar = isKeyManagement || isAuthPage;
|
||||
|
||||
// 跑马灯公告是否存在(用于动态计算头部总高度)。
|
||||
// 认证页(登录/注册/企业登录/企业注册)不展示:用户尚未进入平台,公告是面向平台内用户的信息。
|
||||
const hasMarquee =
|
||||
!hideHeader &&
|
||||
!isAuthPage &&
|
||||
!!statusState?.status?.marquee_content?.trim();
|
||||
const marqueeHeight = hasMarquee ? 40 : 0; // h-10 = 40px
|
||||
const headerBarHeight = isMobile ? 56 : 64; // h-14(56px) on mobile, h-16(64px) on desktop
|
||||
const totalHeaderHeight = headerBarHeight + marqueeHeight;
|
||||
|
||||
// 滚动容器引用
|
||||
const scrollContainerRef = useRef(null);
|
||||
const authBootstrappedRef = useRef(false);
|
||||
|
||||
// 路由切换兜底:
|
||||
// (1) 清除 Semi Modal/SideSheet 在并发开关/异常 unmount 时残留的 body 锁。
|
||||
// Semi 的 enabledBodyScroll 有 `bodyOverflow !== 'hidden'` 保护,多 modal 并发或
|
||||
// visible=true 时被强制卸载,会跳过还原,表现为"滚动条可见但滚不动,刷新才好"。
|
||||
// (2) 重置外层滚动位置(注:scrollContainerRef 当前挂在 Semi Layout 上无法直接拿到 DOM,
|
||||
// scrollTop 赋值是 no-op;保留是为了未来把 ref 换成原生 div 后能立即生效)。
|
||||
useEffect(() => {
|
||||
document.body.style.overflow = '';
|
||||
document.body.style.width = '';
|
||||
// 抽屉态必须跟着路由清掉:它此前只由 SiderBar 的 onNavigate 复位,
|
||||
// 用户从顶栏导航离开控制台时会残留 true,回到 /console 就自动带着遮罩打开,
|
||||
// 整页发暗且看不出原因(遮罩上线前这个残留是不可见的)。
|
||||
setDrawerOpen(false);
|
||||
if (scrollContainerRef.current) {
|
||||
scrollContainerRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [location.pathname]);
|
||||
|
||||
// 跨断点同理:桌面态残留的 drawerOpen 会在缩窄到手机时凭空展开一个带遮罩的抽屉
|
||||
useEffect(() => {
|
||||
setDrawerOpen(false);
|
||||
}, [isMobile]);
|
||||
|
||||
// 手机抽屉恒定展开:不再用 setCollapsed(false) 改写持久化偏好——
|
||||
// 那会让用户在桌面端收起过的侧栏,因为在手机上开过一次抽屉就被重置。
|
||||
// 改为把 forceExpanded 透传给 SiderBar,只影响这一次渲染。
|
||||
const siderForceExpanded = isMobile && drawerOpen;
|
||||
|
||||
// 顶栏总高(顶栏 + 跑马灯)发布成全局 CSS 变量。
|
||||
// 顶栏是 position:fixed,内容区从视口 0 开始流动,任何 `sticky top-0` 的页内元素
|
||||
// 都会吸到顶栏底下被盖住。页面无从得知跑马灯开没开,只能由这里统一给出。
|
||||
useEffect(() => {
|
||||
const root = document.documentElement;
|
||||
root.style.setProperty('--app-header-height', `${totalHeaderHeight}px`);
|
||||
}, [totalHeaderHeight]);
|
||||
|
||||
// 抽屉支持 Esc 关闭:遮罩是 aria-hidden 的纯点击区,键盘用户否则只能回到汉堡按钮
|
||||
useEffect(() => {
|
||||
if (!siderForceExpanded) return;
|
||||
const onKeyDown = (e) => {
|
||||
if (e.key === 'Escape') setDrawerOpen(false);
|
||||
};
|
||||
document.addEventListener('keydown', onKeyDown);
|
||||
return () => document.removeEventListener('keydown', onKeyDown);
|
||||
}, [siderForceExpanded]);
|
||||
|
||||
const loadUser = async () => {
|
||||
const cachedUser = getUserData();
|
||||
if (!cachedUser) {
|
||||
userDispatch({ type: 'auth_checked' });
|
||||
return;
|
||||
}
|
||||
|
||||
userDispatch({ type: 'auth_start' });
|
||||
try {
|
||||
const res = await API.get('/api/user/self', {
|
||||
skipErrorHandler: true,
|
||||
disableDuplicate: true,
|
||||
});
|
||||
const { success, data } = res.data;
|
||||
if (success && data) {
|
||||
setUserData(data);
|
||||
userDispatch({ type: 'login', payload: data });
|
||||
} else {
|
||||
clearUserData();
|
||||
userDispatch({ type: 'logout' });
|
||||
}
|
||||
} catch (error) {
|
||||
if (error?.response?.status === 401 || error?.response?.status === 403) {
|
||||
clearUserData();
|
||||
userDispatch({ type: 'logout' });
|
||||
return;
|
||||
}
|
||||
|
||||
// 网络临时异常时保留本地展示态,后续接口仍会按真实 session 鉴权。
|
||||
userDispatch({ type: 'login', payload: cachedUser });
|
||||
}
|
||||
};
|
||||
|
||||
const loadStatus = async () => {
|
||||
console.log('[PageLayout] Loading status from API...');
|
||||
try {
|
||||
const res = await API.get('/api/status');
|
||||
console.log('[PageLayout] API response received:', res.data);
|
||||
const { success, data } = res.data;
|
||||
if (success) {
|
||||
statusDispatch({ type: 'set', payload: data });
|
||||
setStatusData(data);
|
||||
printConsoleWelcome(data);
|
||||
// 先同步预设覆盖(管理员编辑过的预设模板),再应用主题
|
||||
if (data.theme_presets !== undefined) {
|
||||
setPresetOverrides(data.theme_presets);
|
||||
}
|
||||
// 用服务器最新主题配置覆盖 cache 注入的版本
|
||||
if (data.theme_config !== undefined) {
|
||||
applyTheme(data.theme_config);
|
||||
}
|
||||
console.log('[PageLayout] Status loaded successfully');
|
||||
} else {
|
||||
console.error('[PageLayout] API returned success=false');
|
||||
showError('Unable to connect to server');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('[PageLayout] Failed to load status:', error);
|
||||
showError('Failed to load status');
|
||||
throw error; // 重新抛出以便上层catch
|
||||
}
|
||||
};
|
||||
|
||||
// 检查用户是否需要填写问卷 - 功能已禁用
|
||||
// const checkUserSurvey = useCallback(async () => {
|
||||
// // 已经检查过且已完成,不再检查
|
||||
// if (surveyCheckedRef.current === 'completed') return;
|
||||
//
|
||||
// try {
|
||||
// const res = await API.get('/api/user/survey/check');
|
||||
// const { success, data } = res.data;
|
||||
// if (success) {
|
||||
// if (data && !data.survey_completed) {
|
||||
// setShowSurveyModal(true);
|
||||
// surveyCheckedRef.current = 'pending'; // 等待用户填写
|
||||
// } else {
|
||||
// surveyCheckedRef.current = 'completed'; // 已完成,不再检查
|
||||
// }
|
||||
// }
|
||||
// // 如果请求失败(success=false),不设置状态,下次还会重试
|
||||
// } catch (error) {
|
||||
// console.error('Check survey failed:', error);
|
||||
// // 网络错误时不设置状态,下次还会重试
|
||||
// }
|
||||
// }, []);
|
||||
|
||||
// 当用户登录状态变化时检查问卷 - 功能已禁用
|
||||
// useEffect(() => {
|
||||
// if (userState?.user?.id) {
|
||||
// checkUserSurvey();
|
||||
// } else {
|
||||
// // 用户登出时重置检查状态
|
||||
// surveyCheckedRef.current = null;
|
||||
// setShowSurveyModal(false);
|
||||
// }
|
||||
// }, [userState?.user?.id, checkUserSurvey]);
|
||||
|
||||
// 问卷提交成功后的回调 - 功能已禁用
|
||||
// const handleSurveySuccess = useCallback(() => {
|
||||
// surveyCheckedRef.current = 'completed';
|
||||
// setShowSurveyModal(false);
|
||||
// }, []);
|
||||
|
||||
// 新用户注册赠送额度弹窗:登录后检查是否是刚注册的用户
|
||||
useEffect(() => {
|
||||
const userId = userState?.user?.id;
|
||||
const username = userState?.user?.username;
|
||||
if (!userId || !username) return;
|
||||
|
||||
const pendingUser = localStorage.getItem('new_user_gift_pending');
|
||||
if (pendingUser === username) {
|
||||
localStorage.removeItem('new_user_gift_pending');
|
||||
const quota = userState?.user?.quota || 0;
|
||||
if (quota > 0) {
|
||||
setGiftQuota(quota);
|
||||
setShowGiftModal(true);
|
||||
}
|
||||
}
|
||||
}, [userState?.user?.id]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authBootstrappedRef.current) {
|
||||
authBootstrappedRef.current = true;
|
||||
loadUser();
|
||||
}
|
||||
loadStatus().catch((error) => {
|
||||
console.error('Failed to load status:', error);
|
||||
// 即使加载失败也设置一个默认状态,避免卡住
|
||||
statusDispatch({ type: 'set', payload: { setup: true } });
|
||||
});
|
||||
let systemName = getSystemName();
|
||||
if (systemName) {
|
||||
document.title = systemName;
|
||||
}
|
||||
let logo = getLogo();
|
||||
if (logo) {
|
||||
let linkElement = document.querySelector("link[rel~='icon']");
|
||||
if (linkElement) {
|
||||
linkElement.href = logo;
|
||||
}
|
||||
}
|
||||
// 界面语言已由 i18n/bootstrap.js 在渲染前判定,这里不再读取语言缓存
|
||||
}, [i18n]);
|
||||
|
||||
return (
|
||||
<Layout
|
||||
style={{
|
||||
height: '100vh',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden', // 外层保持 hidden,滚动由内部 scrollContainerRef 控制
|
||||
}}
|
||||
>
|
||||
{!hideHeader && (
|
||||
<Header
|
||||
style={{
|
||||
padding: 0,
|
||||
height: 'auto',
|
||||
lineHeight: 'normal',
|
||||
position: 'fixed',
|
||||
width: '100%',
|
||||
top: 0,
|
||||
zIndex: 100,
|
||||
}}
|
||||
>
|
||||
<HeaderBar
|
||||
onMobileMenuToggle={() => setDrawerOpen((prev) => !prev)}
|
||||
drawerOpen={drawerOpen}
|
||||
/>
|
||||
{/* 跑马灯公告 - 固定在导航栏正下方;认证页不展示(与 hasMarquee 的高度计算保持一致) */}
|
||||
{!isAuthPage && <Marquee />}
|
||||
</Header>
|
||||
)}
|
||||
<Layout
|
||||
ref={scrollContainerRef}
|
||||
className={showVisibleScrollbar ? 'app-scrollbar' : undefined}
|
||||
style={{
|
||||
// 部分页面有自己的滚动控制,不需要外层滚动
|
||||
overflowY: disableOuterScroll ? 'hidden' : 'auto',
|
||||
overflowX: 'hidden',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flex: 1,
|
||||
WebkitOverflowScrolling: 'touch', // iOS 平滑滚动
|
||||
}}
|
||||
>
|
||||
{/* 手机抽屉遮罩:点击关闭。没有它时抽屉浮在内容上、只能再点汉堡才能收,
|
||||
且看不出「当前处于抽屉态」。层级压在 Sider(99) 之下、内容之上。 */}
|
||||
{showSider && isMobile && (
|
||||
<div
|
||||
className='fixed inset-x-0 bottom-0 z-[98] bg-black/45 backdrop-blur-[2px]'
|
||||
style={{ top: `${totalHeaderHeight}px` }}
|
||||
onClick={() => setDrawerOpen(false)}
|
||||
aria-hidden='true'
|
||||
/>
|
||||
)}
|
||||
{showSider && (
|
||||
<Sider
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: 0,
|
||||
top: `${totalHeaderHeight}px`,
|
||||
zIndex: 99,
|
||||
border: 'none',
|
||||
paddingRight: '0',
|
||||
height: `calc(100vh - ${totalHeaderHeight}px)`,
|
||||
// 手机抽屉不跟随桌面的折叠宽度,否则用户在桌面收起过侧栏后,
|
||||
// 抽屉会变成 60px 纯图标窄条,等于看不到导航
|
||||
width: siderForceExpanded
|
||||
? 'var(--sidebar-width)'
|
||||
: 'var(--sidebar-current-width)',
|
||||
boxShadow: siderForceExpanded
|
||||
? '0 0 24px rgba(0,0,0,0.28)'
|
||||
: undefined,
|
||||
}}
|
||||
>
|
||||
<SiderBar
|
||||
forceExpanded={siderForceExpanded}
|
||||
onNavigate={() => {
|
||||
if (isMobile) setDrawerOpen(false);
|
||||
}}
|
||||
/>
|
||||
</Sider>
|
||||
)}
|
||||
<Layout
|
||||
style={{
|
||||
marginLeft: isMobile
|
||||
? '0'
|
||||
: showSider
|
||||
? 'var(--sidebar-current-width)'
|
||||
: '0',
|
||||
flex: '1 0 auto',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
minHeight: disableOuterScroll ? '100%' : 'auto', // 内部滚动的页面需要撑满高度
|
||||
}}
|
||||
>
|
||||
<Content
|
||||
style={{
|
||||
flex: '1 0 auto',
|
||||
WebkitOverflowScrolling: 'touch',
|
||||
padding: shouldInnerPadding
|
||||
? isMobile
|
||||
? '5px'
|
||||
: '24px 24px 0 24px'
|
||||
: '0',
|
||||
position: 'relative',
|
||||
// 认证页等 min-height:100vh 的独立屏用它抵扣上方跑马灯占位的高度,
|
||||
// 保证「占位 + 容器」总高恰为 100vh(无占位时回退 0px,不影响其他页面)
|
||||
'--content-top-offset': `${marqueeHeight}px`,
|
||||
}}
|
||||
>
|
||||
{/* 跑马灯占位:当跑马灯存在时,为内容区域顶部增加等高间距,防止被固定头部遮挡 */}
|
||||
{/* 注意:ExperienceCenter、UserCenter 和 Organization 使用 h-screen 并自行处理顶部偏移,不需要这个占位。
|
||||
认证页保留占位(防内容顶部被跑马灯遮挡且滚不出来),并通过 Content 上的
|
||||
--content-top-offset 变量让认证页容器等量收缩(calc(100vh - offset)),
|
||||
总高度恰为 100vh,不会出现"滚轮一动登录卡片就上下漂移"的幽灵滚动 */}
|
||||
{marqueeHeight > 0 &&
|
||||
!isExperienceCenter &&
|
||||
!isUserCenter &&
|
||||
!isOrgPage && (
|
||||
<div style={{ height: marqueeHeight, flexShrink: 0 }} />
|
||||
)}
|
||||
<App />
|
||||
</Content>
|
||||
</Layout>
|
||||
</Layout>
|
||||
<ToastContainer />
|
||||
<Suspense fallback={null}>
|
||||
<CustomerServiceFloat />
|
||||
</Suspense>
|
||||
|
||||
{/* 用户问卷弹窗 - 功能已禁用 */}
|
||||
{/* <UserSurveyModal
|
||||
visible={showSurveyModal}
|
||||
onClose={() => setShowSurveyModal(false)}
|
||||
onSuccess={handleSurveySuccess}
|
||||
/> */}
|
||||
|
||||
{/* 新用户注册赠送额度弹窗 */}
|
||||
<NewUserGiftModal
|
||||
visible={showGiftModal}
|
||||
onClose={() => setShowGiftModal(false)}
|
||||
quota={giftQuota}
|
||||
/>
|
||||
</Layout>
|
||||
);
|
||||
};
|
||||
|
||||
export default PageLayout;
|
||||
Reference in New Issue
Block a user