Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
/*
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 { useState, useEffect, useRef } from 'react';
/**
* 检测容器宽度的 Hook
* @returns {[ref, width]} 容器引用和当前宽度
*/
export const useContainerWidth = () => {
const [width, setWidth] = useState(0);
const ref = useRef(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width: newWidth } = entry.contentRect;
setWidth(newWidth);
}
});
resizeObserver.observe(element);
// 初始化宽度
setWidth(element.getBoundingClientRect().width);
return () => {
resizeObserver.disconnect();
};
}, []);
return [ref, width];
};
+90
View File
@@ -0,0 +1,90 @@
/*
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 { useEffect, useRef, useState } from 'react';
/**
* KPI 数字滚动(count-up)hook。rAF 实现,零依赖。
*
* 设计约束(见 docs/11-前端与体验中心/02-前端风格整体升级方案.md 冲击力护栏):
* - 尊重 prefers-reduced-motion:直接显示终值,不播动画;
* - 只在数值变化时播一次,不循环;
* - 非有限数值(NaN/Infinity)原样返回,不动画。
*
* @param {number} value 目标数值
* @param {object} [opts]
* @param {number} [opts.duration=800] 动画时长 ms
* @param {number} [opts.decimals=0] 保留小数位
* @returns {number} 当前帧应显示的数值(调用方自行格式化)
*/
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
const prefersReducedMotion = () =>
typeof window !== 'undefined' &&
window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
export function useCountUp(value, { duration = 800, decimals = 0 } = {}) {
const [display, setDisplay] = useState(() =>
Number.isFinite(value) ? 0 : value,
);
// 记录上一次的终值,数值更新时从旧值滚到新值而不是从 0 重来
const fromRef = useRef(0);
const rafRef = useRef(null);
useEffect(() => {
if (!Number.isFinite(value)) {
setDisplay(value);
return undefined;
}
if (prefersReducedMotion() || duration <= 0) {
fromRef.current = value;
setDisplay(value);
return undefined;
}
const from = fromRef.current;
const delta = value - from;
if (delta === 0) {
setDisplay(value);
return undefined;
}
let start = null;
const factor = Math.pow(10, decimals);
const tick = (ts) => {
if (start === null) start = ts;
const progress = Math.min((ts - start) / duration, 1);
const current = from + delta * easeOutCubic(progress);
setDisplay(Math.round(current * factor) / factor);
if (progress < 1) {
rafRef.current = requestAnimationFrame(tick);
} else {
fromRef.current = value;
}
};
rafRef.current = requestAnimationFrame(tick);
return () => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
fromRef.current = value;
};
}, [value, duration, decimals]);
return display;
}
export default useCountUp;
+236
View File
@@ -0,0 +1,236 @@
/*
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 { useState, useEffect, useContext, useCallback, useMemo } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useSetTheme, useTheme, useActualTheme } from '../../context/Theme';
import {
getLogo,
getSystemName,
API,
clearUserData,
showSuccess,
} from '../../helpers';
import { rememberUserLanguage } from '../../i18n/bootstrap';
import { useIsMobile } from './useIsMobile';
import { useSidebarCollapsed } from './useSidebarCollapsed';
import { useMinimumLoadingTime } from './useMinimumLoadingTime';
import { useOrgMembership } from './useOrgMembership';
import {
normalizeHeaderNavModules,
normalizeOrgUserNavModules,
} from '../../constants/headerNavModules';
import {
hasEnabledOrgCenterModule,
normalizeSidebarModulesAdmin,
} from '../../constants/sidebarModules';
export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
const { t, i18n } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const isMobile = useIsMobile();
const [collapsed, toggleCollapsed] = useSidebarCollapsed();
const [logoLoaded, setLogoLoaded] = useState(false);
const navigate = useNavigate();
const [currentLang, setCurrentLang] = useState(i18n.language);
const location = useLocation();
const loading = statusState?.status === undefined || userState?.authChecking;
const isLoading = useMinimumLoadingTime(loading, 200);
const systemName = getSystemName();
const logo = getLogo();
const currentDate = new Date();
const isNewYear = currentDate.getMonth() === 0 && currentDate.getDate() === 1;
const isSelfUseMode = statusState?.status?.self_use_mode_enabled || false;
const docsLink = statusState?.status?.docs_link || '';
const isDemoSiteMode = statusState?.status?.demo_site_enabled || false;
// 获取顶栏模块配置
const headerNavModulesConfig = statusState?.status?.HeaderNavModules;
// 企业员工(仅企业资源模式)专用顶栏配置:隐藏 C 端入口,只保留企业相关
const orgUserNavModulesConfig = statusState?.status?.HeaderNavModulesOrgUser;
const isOrgUser = userState?.user?.org_only_mode === true;
// 使用useMemo确保headerNavModules正确响应statusState变化
// 企业员工(org_only)硬性默认:以企业预设(隐藏 C 端入口)为基线,叠加管理员保存的覆盖配置。
// 即「开箱即生效」,无需管理员先配置;管理员可在运营设置里再放开个别项。
const headerNavModules = useMemo(() => {
if (isOrgUser) {
return normalizeOrgUserNavModules(orgUserNavModulesConfig);
}
return normalizeHeaderNavModules(headerNavModulesConfig);
}, [isOrgUser, headerNavModulesConfig, orgUserNavModulesConfig]);
const sidebarModulesAdmin = useMemo(
() =>
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin),
[statusState?.status?.SidebarModulesAdmin],
);
// 企业中心一级入口:用户属于企业才展示,并跟随后台 orgCenter 模块开关
const orgCenterAvailable = useMemo(() => {
const section = sidebarModulesAdmin?.orgCenter;
return hasEnabledOrgCenterModule(section);
}, [sidebarModulesAdmin]);
// 仅当 orgCenter 功能可用时才拉取企业列表,避免无谓的接口请求
const { hasOrg, orgEntryPath } = useOrgMembership(
userState?.user?.id,
orgCenterAvailable,
);
const showOrgEntry = hasOrg && orgCenterAvailable;
// 获取模型广场权限配置
const pricingRequireAuth = useMemo(() => {
if (headerNavModules?.pricing) {
return typeof headerNavModules.pricing === 'object'
? headerNavModules.pricing.requireAuth
: false; // 默认不需要登录
}
return false; // 默认不需要登录
}, [headerNavModules]);
const isConsoleRoute = location.pathname.startsWith('/console');
const theme = useTheme();
const actualTheme = useActualTheme();
const setTheme = useSetTheme();
// Logo loading effect
useEffect(() => {
setLogoLoaded(false);
if (!logo) return;
const img = new Image();
img.src = logo;
img.onload = () => setLogoLoaded(true);
}, [logo]);
// Send theme to iframe
useEffect(() => {
try {
const iframe = document.querySelector('iframe');
const cw = iframe && iframe.contentWindow;
if (cw) {
cw.postMessage({ themeMode: actualTheme }, '*');
}
} catch (e) {
// Silently ignore cross-origin or access errors
}
}, [actualTheme]);
// Language change effect
useEffect(() => {
const handleLanguageChanged = (lng) => {
setCurrentLang(lng);
try {
const iframe = document.querySelector('iframe');
const cw = iframe && iframe.contentWindow;
if (cw) {
cw.postMessage({ lang: lng }, '*');
}
} catch (e) {
// Silently ignore cross-origin or access errors
}
};
i18n.on('languageChanged', handleLanguageChanged);
return () => {
i18n.off('languageChanged', handleLanguageChanged);
};
}, [i18n]);
// Actions
const logout = useCallback(async () => {
await API.get('/api/user/logout');
showSuccess(t('注销成功!'));
userDispatch({ type: 'logout' });
clearUserData();
navigate('/org/login');
}, [navigate, t, userDispatch]);
const handleLanguageChange = useCallback(
(lang) => {
// 记为显式选择:此后优先于 IP 国家判定(后台关闭顶栏切换时失效)
rememberUserLanguage(lang);
i18n.changeLanguage(lang);
},
[i18n],
);
const handleThemeToggle = useCallback(
(newTheme) => {
if (
!newTheme ||
(newTheme !== 'light' && newTheme !== 'dark' && newTheme !== 'auto')
) {
return;
}
setTheme(newTheme);
},
[setTheme],
);
const handleMobileMenuToggle = useCallback(() => {
if (isMobile) {
onMobileMenuToggle();
} else {
toggleCollapsed();
}
}, [isMobile, onMobileMenuToggle, toggleCollapsed]);
return {
// State
userState,
statusState,
isMobile,
collapsed,
logoLoaded,
currentLang,
location,
isLoading,
systemName,
logo,
isNewYear,
isSelfUseMode,
docsLink,
isDemoSiteMode,
isConsoleRoute,
theme,
drawerOpen,
headerNavModules,
sidebarModulesAdmin,
pricingRequireAuth,
showOrgEntry,
orgEntryPath,
isOrgUser,
// Actions
logout,
handleLanguageChange,
handleThemeToggle,
handleMobileMenuToggle,
navigate,
t,
};
};
+35
View File
@@ -0,0 +1,35 @@
/*
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
*/
export const MOBILE_BREAKPOINT = 768;
import { useSyncExternalStore } from 'react';
export const useIsMobile = () => {
const query = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
return useSyncExternalStore(
(callback) => {
const mql = window.matchMedia(query);
mql.addEventListener('change', callback);
return () => mql.removeEventListener('change', callback);
},
() => window.matchMedia(query).matches,
() => false,
);
};
+50
View File
@@ -0,0 +1,50 @@
/*
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 { useState, useEffect, useRef } from 'react';
/**
* 自定义 Hook:确保骨架屏至少显示指定的时间
* @param {boolean} loading - 实际的加载状态
* @param {number} minimumTime - 最小显示时间(毫秒),默认 1000ms
* @returns {boolean} showSkeleton - 是否显示骨架屏的状态
*/
export const useMinimumLoadingTime = (loading, minimumTime = 1000) => {
const [showSkeleton, setShowSkeleton] = useState(loading);
const loadingStartRef = useRef(Date.now());
useEffect(() => {
if (loading) {
loadingStartRef.current = Date.now();
setShowSkeleton(true);
} else {
const elapsed = Date.now() - loadingStartRef.current;
const remaining = Math.max(0, minimumTime - elapsed);
if (remaining === 0) {
setShowSkeleton(false);
} else {
const timer = setTimeout(() => setShowSkeleton(false), remaining);
return () => clearTimeout(timer);
}
}
}, [loading, minimumTime]);
return showSkeleton;
};
+201
View File
@@ -0,0 +1,201 @@
/*
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 { useMemo } from 'react';
import {
getConfigGroups,
isConfigEnabled,
isGroupAllowed,
} from '../../helpers/navigationVisibility';
import { getHeaderModuleRequireAuth } from '../../constants/headerNavModules';
import { useWeyAiWebEntry } from './useWeyAiWebEntry';
export const useNavigation = (
t,
docsLink,
headerNavModules,
userRole = 0,
userGroup = 'default',
orgEntry = {},
) => {
// 解构成基础类型,避免父组件每次渲染传入新对象字面量导致 useMemo 失效
const { showOrgEntry = false, orgEntryPath = '/org' } = orgEntry;
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
const mainNavLinks = useMemo(() => {
const isAdminUser = userRole >= 10;
// 默认配置,如果没有传入配置则显示所有模块
const defaultModules = {
home: { enabled: true, groups: [] },
console: { enabled: true, groups: [] },
experienceCenter: { enabled: true, requireAuth: false, groups: [] },
keyManagement: { enabled: true, requireAuth: false, groups: [] },
userCenter: { enabled: true, requireAuth: false, groups: [] },
pricing: { enabled: true, requireAuth: false, groups: [] },
docs: { enabled: true, requireAuth: false, groups: [] },
weyai: { enabled: true, groups: [] },
about: { enabled: true, groups: [] },
};
// 合并默认配置和传入配置,确保新增模块有默认值
const modules = headerNavModules
? { ...defaultModules, ...headerNavModules }
: defaultModules;
// 模块是否对当前用户可见:开关 + 「可见用户分组」。顶栏管理里每个模块都有
// 分组控件,过滤却一度只看开关,分组配了等于没配;右侧功能按钮
// (isHeaderActionButtonVisible)一直是看分组的,这里对齐
const isModuleVisible = (key) => {
const module = modules[key];
return (
isConfigEnabled(module) &&
isGroupAllowed(getConfigGroups(module), userGroup)
);
};
const isInternalDocsLink = (link) => {
if (!link) return false;
if (link === '/docs' || link === '/docs/') return true;
if (link.startsWith('/docs')) return true;
try {
const url = new URL(link, window.location.origin);
const currentOrigin = window.location.origin;
if (url.origin === currentOrigin && url.pathname.startsWith('/docs')) {
return true;
}
} catch (_e) {
return false;
}
return false;
};
const getDocsLinkConfig = () => {
const baseConfig = {
itemKey: 'docs',
requireAuth: getHeaderModuleRequireAuth(modules, 'docs'),
};
if (isInternalDocsLink(docsLink) || !docsLink) {
return {
...baseConfig,
text: t('文档'),
to: '/docs',
};
}
return {
...baseConfig,
text: t('文档'),
isExternal: true,
externalLink: docsLink,
};
};
const allLinks = [
{
text: t('秘钥管理'),
itemKey: 'keyManagement',
to: '/key-management',
requireAuth: getHeaderModuleRequireAuth(modules, 'keyManagement'),
},
{
text: t('体验中心'),
itemKey: 'experienceCenter',
to: '/experience-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'experienceCenter'),
},
{
text: t('模型超市'),
itemKey: 'pricing',
to: '/market',
requireAuth: getHeaderModuleRequireAuth(modules, 'pricing'),
},
{
text: t('技能超市'),
itemKey: 'skillMarket',
to: '/skill-market',
requireAuth: getHeaderModuleRequireAuth(modules, 'skillMarket'),
},
getDocsLinkConfig(),
{
text: t('用户中心'),
itemKey: 'userCenter',
to: '/user-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
},
// WeyAi 网页端:外链到网关的 /sso/start(每次点击都重新走一遍免登录授权),
// 需要登录;管理员可在「顶栏管理」里关闭
...(weyaiVisible
? [
{
text: t('WeyAi'),
itemKey: 'weyai',
isExternal: true,
externalLink: weyaiUrl,
requireAuth: true,
},
]
: []),
// 企业中心:仅当用户属于某个企业时作为一级入口展示(不跟随 headerNavModules 配置,
// 由 showOrgEntry 统一控制可见性,故标记 alwaysShow 跳过模块开关过滤)
...(showOrgEntry
? [
{
text: t('企业中心'),
itemKey: 'orgCenter',
to: orgEntryPath || '/org',
activePrefix: '/org',
requireAuth: true,
alwaysShow: true,
},
]
: []),
{
text: t('控制台'),
itemKey: 'console',
to: '/console/analytics',
activePrefix: '/console',
adminOnly: true,
requireAuth: true,
},
];
return allLinks.filter((link) => {
if (link.adminOnly && !isAdminUser) {
return false;
}
if (link.alwaysShow) {
return true;
}
return isModuleVisible(link.itemKey);
});
}, [
t,
docsLink,
headerNavModules,
userRole,
userGroup,
showOrgEntry,
orgEntryPath,
weyaiVisible,
weyaiUrl,
]);
return {
mainNavLinks,
};
};
+94
View File
@@ -0,0 +1,94 @@
/*
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 { useState, useEffect } from 'react';
export const useNotifications = (statusState) => {
const [noticeVisible, setNoticeVisible] = useState(false);
const [unreadCount, setUnreadCount] = useState(0);
const announcements = statusState?.status?.announcements || [];
// Helper functions
const getAnnouncementKey = (a) =>
`${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`;
const calculateUnreadCount = () => {
if (!announcements.length) return 0;
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements.filter((a) => !readSet.has(getAnnouncementKey(a)))
.length;
};
const getUnreadKeys = () => {
if (!announcements.length) return [];
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements
.filter((a) => !readSet.has(getAnnouncementKey(a)))
.map(getAnnouncementKey);
};
// Effects
useEffect(() => {
setUnreadCount(calculateUnreadCount());
}, [announcements]);
// Actions
const handleNoticeOpen = () => {
setNoticeVisible(true);
};
const handleNoticeClose = () => {
setNoticeVisible(false);
if (announcements.length) {
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const mergedKeys = Array.from(
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
);
localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys));
}
setUnreadCount(0);
};
return {
noticeVisible,
unreadCount,
announcements,
handleNoticeOpen,
handleNoticeClose,
getUnreadKeys,
};
};
+96
View File
@@ -0,0 +1,96 @@
/*
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 { useState, useEffect } from 'react';
import { API } from '../../helpers';
const ADMIN_ROLES = ['owner', 'admin', 'super_admin'];
/**
* 拉取当前用户所属企业,用于判断是否在顶部一级导航展示「企业中心」入口。
* 仅登录且 orgCenter 功能可用时拉取一次;否则返回 hasOrg=false 且不发请求。
*
* @param {number|undefined} userId 当前登录用户 id(未登录为 undefined)
* @param {boolean} enabled orgCenter 功能是否可用(关闭时跳过请求)
* @returns {{hasOrg: boolean, orgEntryPath: string, activeOrg: object|null,
* isOrgAdmin: boolean, loaded: boolean}}
* loaded 区分"确定不是管理员"与"还不知道":调用方若拿 isOrgAdmin 做重定向类
* 判定,必须等 loaded,否则会在企业列表回来之前就把人重定向走(不可逆)。
*/
export const useOrgMembership = (userId, enabled = true) => {
const [orgs, setOrgs] = useState([]);
// 记录"已完成加载的那组入参",而不是一个裸布尔。裸布尔在这里是不够的:
// App 首帧 user 还是 undefined(loadUser 异步 dispatch),enabled 为 false,
// effect 会立刻把它置 true;等 /api/user/self 回来那一帧 enabled 翻 true,
// 但已 commit 的布尔仍是 true,调用方当帧就按"已知"做了重定向判定——正是
// 本标志要防的那条路径。改成在渲染期比对 key,入参一变 loaded 立即为 false。
const [loadedKey, setLoadedKey] = useState(null);
const currentKey = `${userId || 0}:${enabled ? 1 : 0}`;
const loaded = loadedKey === currentKey;
useEffect(() => {
let cancelled = false;
if (!userId || !enabled) {
setOrgs([]);
// 不需要拉取时直接视为"已知",避免调用方永久等待一个不会发生的请求。
setLoadedKey(currentKey);
return undefined;
}
(async () => {
try {
const res = await API.get('/api/org/list');
if (!cancelled && res?.data?.success) {
setOrgs(res.data.data || []);
}
} catch {
// 静默失败:拿不到企业列表时不展示入口即可
} finally {
// 失败也置位:否则一次网络抖动会让依赖 loaded 的分支永久挂起。
if (!cancelled) setLoadedKey(currentKey);
}
})();
return () => {
cancelled = true;
};
}, [userId, enabled, currentKey]);
const hasOrg = orgs.length > 0;
// 选取当前企业:优先 localStorage 记录的,否则取第一个
let activeOrg = null;
if (hasOrg) {
const savedId = parseInt(localStorage.getItem('current_org_id') || '0', 10);
activeOrg = orgs.find((o) => o.id === savedId) || orgs[0];
}
const role = activeOrg?.role || 'member';
// 按角色决定落地页,保证入口层级最浅:管理员进数据看板,员工进工作台
const orgEntryPath = ADMIN_ROLES.includes(role)
? '/org/dashboard'
: '/org/workbench';
// activeOrg / isOrgAdmin 供平台级页面(如技能超市)按企业身份做渐进增强。
// 复用同一套"当前企业"选取规则,避免各页面各自实现后与顶栏入口指向不同的企业。
return {
hasOrg,
orgEntryPath,
activeOrg,
isOrgAdmin: ADMIN_ROLES.includes(role),
loaded,
};
};
+274
View File
@@ -0,0 +1,274 @@
/*
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 { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { SecureVerificationService } from '../../services/secureVerification';
import { showError, showSuccess } from '../../helpers';
import { isVerificationRequiredError } from '../../helpers/secureApiCall';
/**
* 通用安全验证 Hook
* @param {Object} options - 配置选项
* @param {Function} options.onSuccess - 验证成功回调
* @param {Function} options.onError - 验证失败回调
* @param {string} options.successMessage - 成功提示消息
* @param {boolean} options.autoReset - 验证完成后是否自动重置状态,默认为 true
*/
export const useSecureVerification = ({
onSuccess,
onError,
successMessage,
autoReset = true,
} = {}) => {
const { t } = useTranslation();
// 验证方式可用性状态
const [verificationMethods, setVerificationMethods] = useState({
has2FA: false,
hasPasskey: false,
passkeySupported: false,
});
// 模态框状态
const [isModalVisible, setIsModalVisible] = useState(false);
// 当前验证状态
const [verificationState, setVerificationState] = useState({
method: null, // '2fa' | 'passkey'
loading: false,
code: '',
apiCall: null,
});
// 检查可用的验证方式
const checkVerificationMethods = useCallback(async () => {
const methods =
await SecureVerificationService.checkAvailableVerificationMethods();
setVerificationMethods(methods);
return methods;
}, []);
// 初始化时检查验证方式
useEffect(() => {
checkVerificationMethods();
}, [checkVerificationMethods]);
// 重置状态
const resetState = useCallback(() => {
setVerificationState({
method: null,
loading: false,
code: '',
apiCall: null,
});
setIsModalVisible(false);
}, []);
// 开始验证流程
const startVerification = useCallback(
async (apiCall, options = {}) => {
const { preferredMethod, title, description } = options;
// 检查验证方式
const methods = await checkVerificationMethods();
if (!methods.has2FA && !methods.hasPasskey) {
const errorMessage = t('您需要先启用两步验证或 Passkey 才能执行此操作');
showError(errorMessage);
onError?.(new Error(errorMessage));
return false;
}
// 设置默认验证方式
let defaultMethod = preferredMethod;
if (!defaultMethod) {
if (methods.hasPasskey && methods.passkeySupported) {
defaultMethod = 'passkey';
} else if (methods.has2FA) {
defaultMethod = '2fa';
}
}
setVerificationState((prev) => ({
...prev,
method: defaultMethod,
apiCall,
title,
description,
}));
setIsModalVisible(true);
return true;
},
[checkVerificationMethods, onError, t],
);
// 执行验证
const executeVerification = useCallback(
async (method, code = '') => {
if (!verificationState.apiCall) {
showError(t('验证配置错误'));
return;
}
setVerificationState((prev) => ({ ...prev, loading: true }));
try {
// 先调用验证 API,成功后后端会设置 session
await SecureVerificationService.verify(method, code);
// 验证成功,调用业务 API(此时中间件会通过)
const result = await verificationState.apiCall();
// 显示成功消息
if (successMessage) {
showSuccess(successMessage);
}
// 调用成功回调
onSuccess?.(result, method);
// 自动重置状态
if (autoReset) {
resetState();
}
return result;
} catch (error) {
showError(error.message || t('验证失败,请重试'));
onError?.(error);
throw error;
} finally {
setVerificationState((prev) => ({ ...prev, loading: false }));
}
},
[
verificationState.apiCall,
successMessage,
onSuccess,
onError,
autoReset,
resetState,
t,
],
);
// 设置验证码
const setVerificationCode = useCallback((code) => {
setVerificationState((prev) => ({ ...prev, code }));
}, []);
// 切换验证方式
const switchVerificationMethod = useCallback((method) => {
setVerificationState((prev) => ({ ...prev, method, code: '' }));
}, []);
// 取消验证
const cancelVerification = useCallback(() => {
resetState();
}, [resetState]);
// 检查是否可以使用某种验证方式
const canUseMethod = useCallback(
(method) => {
switch (method) {
case '2fa':
return verificationMethods.has2FA;
case 'passkey':
return (
verificationMethods.hasPasskey &&
verificationMethods.passkeySupported
);
default:
return false;
}
},
[verificationMethods],
);
// 获取推荐的验证方式
const getRecommendedMethod = useCallback(() => {
if (
verificationMethods.hasPasskey &&
verificationMethods.passkeySupported
) {
return 'passkey';
}
if (verificationMethods.has2FA) {
return '2fa';
}
return null;
}, [verificationMethods]);
/**
* 包装 API 调用,自动处理验证错误
* 当 API 返回需要验证的错误时,自动弹出验证模态框
* @param {Function} apiCall - API 调用函数
* @param {Object} options - 验证选项(同 startVerification)
* @returns {Promise<any>}
*/
const withVerification = useCallback(
async (apiCall, options = {}) => {
try {
// 直接尝试调用 API
return await apiCall();
} catch (error) {
// 检查是否是需要验证的错误
if (isVerificationRequiredError(error)) {
// 自动触发验证流程
await startVerification(apiCall, options);
// 不抛出错误,让验证模态框处理
return null;
}
// 其他错误继续抛出
throw error;
}
},
[startVerification],
);
return {
// 状态
isModalVisible,
verificationMethods,
verificationState,
// 方法
startVerification,
executeVerification,
cancelVerification,
resetState,
setVerificationCode,
switchVerificationMethod,
checkVerificationMethods,
// 辅助方法
canUseMethod,
getRecommendedMethod,
withVerification, // 新增:自动处理验证的包装函数
// 便捷属性
hasAnyVerificationMethod:
verificationMethods.has2FA || verificationMethods.hasPasskey,
isLoading: verificationState.loading,
currentMethod: verificationState.method,
code: verificationState.code,
};
};
+262
View File
@@ -0,0 +1,262 @@
/*
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 { useState, useEffect, useMemo, useContext, useRef } from 'react';
import { StatusContext } from '../../context/Status';
import { API } from '../../helpers';
import { isGroupAllowed } from '../../helpers/navigationVisibility';
import { getDefaultSidebarModulesAdmin } from '../../constants/sidebarModules';
const sidebarEventTarget = new EventTarget();
const SIDEBAR_REFRESH_EVENT = 'sidebar-refresh';
const SIDEBAR_META_KEYS = new Set(['enabled', 'groups', 'moduleGroups']);
// 默认配置从 constants/sidebarModules.js 单一事实源派生,仅补上分组过滤用的
// groups/moduleGroups 元字段。此前这里手工维护了一份副本,与 constants 漂移:
// admin 区缺 skill-platform key,导致「平台 Skill 中心」入口在未保存过
// SidebarModulesAdmin 的部署上凭空消失(finalConfig 只遍历此处存在的 key,
// isModuleVisible 对缺失 key 恒 false)。派生后两处不可能再漂移。
const defaultAdminConfig = Object.entries(
getDefaultSidebarModulesAdmin(),
).reduce((acc, [sectionKey, section]) => {
acc[sectionKey] = { groups: [], moduleGroups: {}, ...section };
return acc;
}, {});
const buildDefaultUserConfig = (adminConfig) => {
const defaultUserConfig = {};
Object.keys(adminConfig).forEach((sectionKey) => {
if (adminConfig[sectionKey]?.enabled) {
defaultUserConfig[sectionKey] = { enabled: true };
Object.keys(adminConfig[sectionKey]).forEach((moduleKey) => {
if (
!SIDEBAR_META_KEYS.has(moduleKey) &&
adminConfig[sectionKey][moduleKey]
) {
defaultUserConfig[sectionKey][moduleKey] = true;
}
});
}
});
return defaultUserConfig;
};
export const useSidebar = () => {
const [statusState] = useContext(StatusContext);
const [userConfig, setUserConfig] = useState(null);
const [userGroup, setUserGroup] = useState('default');
const [loading, setLoading] = useState(true);
const instanceIdRef = useRef(null);
const hasLoadedOnceRef = useRef(false);
if (!instanceIdRef.current) {
const randomPart = Math.random().toString(16).slice(2);
instanceIdRef.current = `sidebar-${Date.now()}-${randomPart}`;
}
const adminConfig = useMemo(() => {
if (statusState?.status?.SidebarModulesAdmin) {
try {
const savedConfig = JSON.parse(statusState.status.SidebarModulesAdmin);
const mergedConfig = {};
Object.keys(defaultAdminConfig).forEach((sectionKey) => {
mergedConfig[sectionKey] = {
...defaultAdminConfig[sectionKey],
...(savedConfig[sectionKey] || {}),
};
});
Object.keys(savedConfig).forEach((sectionKey) => {
if (!mergedConfig[sectionKey]) {
mergedConfig[sectionKey] = savedConfig[sectionKey];
}
});
return mergedConfig;
} catch (error) {
return defaultAdminConfig;
}
}
return defaultAdminConfig;
}, [statusState?.status?.SidebarModulesAdmin]);
const loadUserConfig = async ({ withLoading } = {}) => {
const shouldShowLoader =
typeof withLoading === 'boolean'
? withLoading
: !hasLoadedOnceRef.current;
try {
if (shouldShowLoader) {
setLoading(true);
}
const res = await API.get('/api/user/self');
if (res.data.success) {
setUserGroup(res.data.data?.group || 'default');
}
if (res.data.success && res.data.data.sidebar_modules) {
let config;
if (typeof res.data.data.sidebar_modules === 'string') {
config = JSON.parse(res.data.data.sidebar_modules);
} else {
config = res.data.data.sidebar_modules;
}
setUserConfig(config);
} else {
setUserConfig(buildDefaultUserConfig(adminConfig));
}
} catch (error) {
setUserConfig(buildDefaultUserConfig(adminConfig));
} finally {
if (shouldShowLoader) {
setLoading(false);
}
hasLoadedOnceRef.current = true;
}
};
const refreshUserConfig = async () => {
if (Object.keys(adminConfig).length > 0) {
await loadUserConfig({ withLoading: false });
}
sidebarEventTarget.dispatchEvent(
new CustomEvent(SIDEBAR_REFRESH_EVENT, {
detail: { sourceId: instanceIdRef.current, skipLoader: true },
}),
);
};
useEffect(() => {
if (Object.keys(adminConfig).length > 0) {
loadUserConfig();
}
}, [adminConfig]);
useEffect(() => {
const handleRefresh = (event) => {
if (event?.detail?.sourceId === instanceIdRef.current) {
return;
}
if (Object.keys(adminConfig).length > 0) {
loadUserConfig({
withLoading: event?.detail?.skipLoader ? false : undefined,
});
}
};
sidebarEventTarget.addEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
return () => {
sidebarEventTarget.removeEventListener(
SIDEBAR_REFRESH_EVENT,
handleRefresh,
);
};
}, [adminConfig]);
const finalConfig = useMemo(() => {
const result = {};
if (!adminConfig || Object.keys(adminConfig).length === 0) {
return result;
}
if (!userConfig) {
return result;
}
Object.keys(adminConfig).forEach((sectionKey) => {
const adminSection = adminConfig[sectionKey];
const userSection = userConfig[sectionKey];
const sectionGroupAllowed = isGroupAllowed(
adminSection?.groups,
userGroup,
);
if (!adminSection?.enabled || !sectionGroupAllowed) {
result[sectionKey] = { enabled: false };
return;
}
const sectionEnabled = userSection ? userSection.enabled !== false : true;
result[sectionKey] = { enabled: sectionEnabled };
Object.keys(adminSection).forEach((moduleKey) => {
if (SIDEBAR_META_KEYS.has(moduleKey)) return;
const adminAllowed = adminSection[moduleKey] !== false;
const userAllowed = userSection
? userSection[moduleKey] !== false
: true;
const moduleGroupAllowed = isGroupAllowed(
adminSection.moduleGroups?.[moduleKey],
userGroup,
);
result[sectionKey][moduleKey] =
adminAllowed && userAllowed && moduleGroupAllowed && sectionEnabled;
});
});
return result;
}, [adminConfig, userConfig, userGroup]);
const isModuleVisible = (sectionKey, moduleKey = null) => {
if (moduleKey) {
return finalConfig[sectionKey]?.[moduleKey] === true;
}
return finalConfig[sectionKey]?.enabled === true;
};
const hasSectionVisibleModules = (sectionKey) => {
const section = finalConfig[sectionKey];
if (!section?.enabled) return false;
return Object.keys(section).some(
(key) => key !== 'enabled' && section[key] === true,
);
};
const getVisibleModules = (sectionKey) => {
const section = finalConfig[sectionKey];
if (!section?.enabled) return [];
return Object.keys(section).filter(
(key) => key !== 'enabled' && section[key] === true,
);
};
return {
loading,
adminConfig,
userConfig,
finalConfig,
isModuleVisible,
hasSectionVisibleModules,
getVisibleModules,
refreshUserConfig,
};
};
+95
View File
@@ -0,0 +1,95 @@
/*
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 { useCallback, useSyncExternalStore } from 'react';
const KEY = 'default_collapse_sidebar';
/*
* 侧栏折叠态是「一份跨组件共享的状态」,不能用 useState——
* 本 hook 有 6 个调用方(PageLayout / SiderBar / useHeaderBar / ExperienceSidebar /
* OrgSidebar / UserCenterSidebar),useState 会让每个调用方各自持有一份副本,
* 只在挂载时读一次 localStorage,之后彼此不同步。
*
* 由此产生过一个真实故障:手机上打开控制台侧栏抽屉时,PageLayout 调
* setCollapsed(false) 想把抽屉展开,但只改到自己那份副本,SiderBar 那份仍是
* true,于是抽屉渲染成 60px 的纯图标窄条、看不到任何导航文字——表现为
* 「移动端看不到左侧 tab,只能停留在默认页面」。
*
* 改成模块级 store + useSyncExternalStore:一处写入,所有调用方同步重渲染。
*/
// 注意:这段在模块求值期执行,抛异常会直接中断 app-shell chunk(白屏,错误边界都够不着)。
// typeof window 只挡得住 SSR,挡不住「存储被拒绝」——Safari 全面禁用 Cookie、
// 三方/沙箱 iframe、部分企业策略下,光是访问 localStorage 就会抛 SecurityError。
// 与下方写入侧保持同样的 try/catch 保护。
const readPersisted = () => {
try {
return localStorage.getItem(KEY) === 'true';
} catch (e) {
return false;
}
};
let collapsedState = typeof window !== 'undefined' && readPersisted();
const listeners = new Set();
const emit = () => {
listeners.forEach((listener) => listener());
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const getSnapshot = () => collapsedState;
// SSR/首屏快照:与 useIsMobile 保持同一取值策略,返回稳定的默认值
const getServerSnapshot = () => false;
const setCollapsedState = (value) => {
const next = Boolean(value);
if (next === collapsedState) return;
collapsedState = next;
try {
localStorage.setItem(KEY, next.toString());
} catch (e) {
// 隐私模式下 localStorage 可能不可写,内存态仍然生效
}
emit();
};
export const useSidebarCollapsed = () => {
const collapsed = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
const toggle = useCallback(() => {
setCollapsedState(!collapsedState);
}, []);
const set = useCallback((value) => {
setCollapsedState(value);
}, []);
return [collapsed, toggle, set];
};
+58
View File
@@ -0,0 +1,58 @@
/*
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 { useState, useEffect, useCallback } from 'react';
import { getTableCompactMode, setTableCompactMode } from '../../helpers';
import { TABLE_COMPACT_MODES_KEY } from '../../constants';
/**
* 自定义 Hook:管理表格紧凑/自适应模式
* 返回 [compactMode, setCompactMode]。
* 内部使用 localStorage 保存状态,并监听 storage 事件保持多标签页同步。
*/
export function useTableCompactMode(tableKey = 'global') {
const [compactMode, setCompactModeState] = useState(() =>
getTableCompactMode(tableKey),
);
const setCompactMode = useCallback(
(value) => {
setCompactModeState(value);
setTableCompactMode(value, tableKey);
},
[tableKey],
);
useEffect(() => {
const handleStorage = (e) => {
if (e.key === TABLE_COMPACT_MODES_KEY) {
try {
const modes = JSON.parse(e.newValue || '{}');
setCompactModeState(!!modes[tableKey]);
} catch {
// ignore parse error
}
}
};
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, [tableKey]);
return [compactMode, setCompactMode];
}
+119
View File
@@ -0,0 +1,119 @@
/*
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 { useState, useEffect } from 'react';
import { API } from '../../helpers';
/**
* 用户权限钩子 - 从后端获取用户权限,替代前端角色判断
* 确保权限控制的安全性,防止前端绕过
*/
export const useUserPermissions = () => {
const [permissions, setPermissions] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// 加载用户权限(从用户信息接口获取)
const loadPermissions = async () => {
try {
setLoading(true);
setError(null);
const res = await API.get('/api/user/self');
if (res.data.success) {
const userPermissions = res.data.data.permissions;
setPermissions(userPermissions);
console.log('用户权限加载成功:', userPermissions);
} else {
setError(res.data.message || '获取权限失败');
console.error('获取权限失败:', res.data.message);
}
} catch (error) {
setError('网络错误,请重试');
console.error('加载用户权限异常:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadPermissions();
}, []);
// 检查是否有边栏设置权限
const hasSidebarSettingsPermission = () => {
return permissions?.sidebar_settings === true;
};
// 检查是否允许访问特定的边栏区域
const isSidebarSectionAllowed = (sectionKey) => {
if (!permissions?.sidebar_modules) return true;
const sectionPerms = permissions.sidebar_modules[sectionKey];
return sectionPerms !== false;
};
// 检查是否允许访问特定的边栏模块
const isSidebarModuleAllowed = (sectionKey, moduleKey) => {
if (!permissions?.sidebar_modules) return true;
const sectionPerms = permissions.sidebar_modules[sectionKey];
// 如果整个区域被禁用
if (sectionPerms === false) return false;
// 如果区域存在但模块被禁用
if (sectionPerms && sectionPerms[moduleKey] === false) return false;
return true;
};
// 获取允许的边栏区域列表
const getAllowedSidebarSections = () => {
if (!permissions?.sidebar_modules) return [];
return Object.keys(permissions.sidebar_modules).filter((sectionKey) =>
isSidebarSectionAllowed(sectionKey),
);
};
// 获取特定区域允许的模块列表
const getAllowedSidebarModules = (sectionKey) => {
if (!permissions?.sidebar_modules) return [];
const sectionPerms = permissions.sidebar_modules[sectionKey];
if (sectionPerms === false) return [];
if (!sectionPerms || typeof sectionPerms !== 'object') return [];
return Object.keys(sectionPerms).filter(
(moduleKey) =>
moduleKey !== 'enabled' && sectionPerms[moduleKey] === true,
);
};
return {
permissions,
loading,
error,
loadPermissions,
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
getAllowedSidebarSections,
getAllowedSidebarModules,
};
};
export default useUserPermissions;
+169
View File
@@ -0,0 +1,169 @@
/*
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 { useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers/api';
import { normalizeLanguage } from '../../i18n/language';
import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import { toSafeHttpUrl } from '../../helpers/safeUrl';
// 同一用户的网页端开放结果缓存,避免每次顶栏重渲染都请求。
// 带 TTL:开放范围(分组/企业/黑名单)是管理员随时可改的,永不过期的缓存会
// 让"已被移出开放范围"的用户在整页刷新前一直看得到入口,点进去才被拒。
// 与后端 AccessCheckCacheTTL 取同一个 60 秒口径。
const ACCESS_CACHE_TTL = 60 * 1000;
const accessCache = new Map(); // userId -> { allowed, expires }
// 顶栏常驻,hook 的 effect 只在依赖变化时重跑:缓存过期或被清掉本身不会触发
// 任何实例重查,入口就一直停在页面加载时的判定上,直到整页刷新。这里用一个
// 模块级版本号把"该重查了"通知到每个实例:清缓存、每 60 秒一次、回到页面时各
// 推一版;缓存未过期的实例收到通知后不发请求
let accessVersion = 0;
const accessListeners = new Set();
function bumpAccessVersion() {
accessVersion += 1;
accessListeners.forEach((listener) => listener(accessVersion));
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') bumpAccessVersion();
});
setInterval(() => {
if (document.visibilityState === 'visible' && accessListeners.size > 0) {
bumpAccessVersion();
}
}, ACCESS_CACHE_TTL);
}
// 管理员在系统设置里改了开放范围后调用,让顶栏入口立刻重新询问后端,而不是
// 等 60 秒缓存过期
export function invalidateWeyAiAccessCache() {
accessCache.clear();
bumpAccessVersion();
}
function cachedAllowed(userId) {
const cached = userId ? accessCache.get(userId) : undefined;
return !!cached && cached.expires > Date.now() && cached.allowed === true;
}
// 只接受 http(s) 绝对地址,其他协议一律当作未配置
function trimTrailingSlash(url) {
return toSafeHttpUrl(url).replace(/\/+$/, '');
}
/**
* 顶部导航「WeyAi」入口(方案 4.7):
* - /api/status 的 weyai_web_enabled 为真且配置了 weyai_web_url 才考虑显示;
* - 已登录时按 GET /api/client/v1/web/access 的 allowed 决定;
* - 未登录时照常显示,点击由导航按 requireAuth 引导去登录。
* 返回 { visible, url },url 为 `<weyai_web_url>/sso/start?lang=<当前界面语言>`。
*
* lang 是把本站当前的界面语言交给网关:网关的启动/提示页本来按浏览器语言显示,
* 两者不一致时(系统中文、在这里选了英文)跳过去就换了语言。网关支持
* zh / zh-TW / en / ja / ko / th(与 LANGUAGE_CATALOG 同码),其余忽略并回落到
* Accept-Language;它把这个值跟着 SSO state 带到登录完成才存,所以中途跳转、
* rel="noreferrer" 都不影响。
*/
export function useWeyAiWebEntry() {
const { i18n } = useTranslation();
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const status = statusState?.status;
const enabled =
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
const baseUrl = trimTrailingSlash(status?.weyai_web_url);
const userId = userState?.user?.id || 0;
// 初值必须取缓存里的布尔结果而不是缓存条目本身:条目对象永远为真,会让
// 被拒用户在每次顶栏重挂载时先闪一下 WeyAi 入口
const [allowed, setAllowed] = useState(() => cachedAllowed(userId));
const [version, setVersion] = useState(accessVersion);
useEffect(() => {
accessListeners.add(setVersion);
return () => {
accessListeners.delete(setVersion);
};
}, []);
useEffect(() => {
if (!enabled || !baseUrl || !userId) {
setAllowed(false);
return undefined;
}
const cached = accessCache.get(userId);
if (cached && cached.expires > Date.now()) {
setAllowed(cached.allowed);
return undefined;
}
let cancelled = false;
API.get('/api/client/v1/web/access', { skipErrorHandler: true })
.then((res) => {
const body = res?.data;
const data = body && 'data' in body ? body.data : body;
const ok = body?.success !== false && data?.allowed === true;
accessCache.set(userId, {
allowed: ok,
expires: Date.now() + ACCESS_CACHE_TTL,
});
if (!cancelled) setAllowed(ok);
})
.catch(() => {
// 接口不可用(例如后端尚未部署)时不显示入口,也不缓存;下一版通知
//(60 秒、回到页面、管理员改范围)再试
if (!cancelled) setAllowed(false);
});
return () => {
cancelled = true;
};
}, [enabled, baseUrl, userId, version]);
const visible = enabled && !!baseUrl && (!userId || allowed);
const lang = normalizeLanguage(i18n.language);
return {
visible,
url: baseUrl ? `${baseUrl}/sso/start?lang=${encodeURIComponent(lang)}` : '',
};
}
/**
* 桌面端下载入口(顶栏按钮 / 用户中心侧栏项共用一套判定):
* - 后台未开「桌面端下载页」→ 不显示;
* - 网页端未配置(开关/地址/密钥缺一)→ 桌面端没有独立的开放范围,登录即可用,只看下载开关;
* - 网页端已配置 → 沿用网页端开放范围(含黑名单):管理员没开放 WeyAi 的人不推送入口。
* 只对已登录用户为真;/weyai/download 本身是公开路由,未登录访客仍可直接访问。
*/
export function useWeyAiDownloadEntry() {
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const status = statusState?.status;
const downloadEnabled =
status?.weyai_download_enabled === true ||
status?.weyai_download_enabled === 'true';
const webEnabled =
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
const { visible: webVisible } = useWeyAiWebEntry();
const loggedIn = !!userState?.user?.id;
return {
visible: downloadEnabled && loggedIn && (!webEnabled || webVisible),
};
}