home.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. "use client";
  2. import { Modal } from "antd";
  3. require("../polyfill");
  4. import { useState, useEffect } from "react";
  5. import {
  6. HashRouter as Router,
  7. Routes,
  8. Route,
  9. useLocation,
  10. useNavigate
  11. } from "react-router-dom";
  12. import styles from "./home.module.scss";
  13. import BotIcon from "../icons/bot.svg";
  14. import loadingIcon from "../icons/loading.gif";
  15. import { getCSSVar, useMobileScreen } from "../utils";
  16. import dynamic from "next/dynamic";
  17. import { Path, SlotID } from "../constant";
  18. import { ErrorBoundary } from "./error";
  19. import { getISOLang, getLang } from "../locales";
  20. import { SideBar } from "./sidebar";
  21. import { useAppConfig } from "../store/config";
  22. import { AuthPage } from "./auth";
  23. import { getClientConfig } from "../config/client";
  24. import { type ClientApi, getClientApi } from "../client/api";
  25. import { useAccessStore } from "../store";
  26. import api from "../api/api";
  27. export function Loading() {
  28. /** second版本注释掉进度条 */
  29. const [progress, setProgress] = useState(1);
  30. useEffect(() => {
  31. let isMounted = true;
  32. const intervalId = setInterval(() => {
  33. if (isMounted && progress < 100) {
  34. // 每隔一段时间增加1%进度
  35. setProgress(prevProgress => prevProgress + 1);
  36. }
  37. }, 30);// 每10毫秒更新1%进度
  38. return () => {
  39. isMounted = false;
  40. clearInterval(intervalId);
  41. };
  42. }, [progress]);
  43. return (
  44. <div className={styles["loading-content"] + " no-dark"}>
  45. <img src={loadingIcon.src} />
  46. {/* seceond版本注释掉进度条 */}
  47. <div style={{ width: '60%', height: 15, background: '#F5F6F9', borderRadius: 8, marginTop: '20%', position: 'relative' }}>
  48. <div
  49. style={{
  50. width: `${progress}%`,
  51. height: 15,
  52. background: '#265C7D',
  53. borderRadius: 8,
  54. display: 'flex',
  55. justifyContent: 'flex-end',
  56. alignItems: 'center',
  57. position: 'absolute'
  58. }}
  59. >
  60. <div style={{ color: '#FFFFFF', fontSize: 12, lineHeight: 12, marginRight: 4 }}>
  61. {progress}%
  62. </div>
  63. </div>
  64. </div>
  65. </div>
  66. );
  67. }
  68. // 延时器
  69. export const delayer = (): Promise<any> => {
  70. // 延时时间-秒
  71. const time: number = 0.1;
  72. return new Promise((resolve, reject) => {
  73. setTimeout(() => {
  74. resolve({});
  75. }, time * 1000);
  76. });
  77. }
  78. const Artifacts = dynamic(
  79. async () => {
  80. await delayer();
  81. return (await import("./artifacts")).Artifacts
  82. },
  83. {
  84. loading: () => <Loading />,
  85. }
  86. );
  87. const Settings = dynamic(
  88. async () => {
  89. await delayer();
  90. return (await import("./settings")).Settings
  91. },
  92. {
  93. loading: () => <Loading />,
  94. }
  95. );
  96. const Chat = dynamic(
  97. async () => {
  98. await delayer();
  99. return (await import("./chat")).Chat
  100. },
  101. {
  102. loading: () => <Loading />,
  103. }
  104. );
  105. const DeepSeekChat = dynamic(
  106. async () => {
  107. await delayer();
  108. return (await import("./DeepSeekChat")).Chat
  109. },
  110. {
  111. loading: () => <Loading />,
  112. }
  113. );
  114. const Record = dynamic(
  115. async () => {
  116. await delayer();
  117. return (await import("./Record"))
  118. },
  119. {
  120. loading: () => <Loading />,
  121. }
  122. );
  123. const HomeApp = dynamic(
  124. async () => {
  125. return (await import("./DeekSeekHome"))
  126. },
  127. {
  128. loading: () => <Loading />,
  129. }
  130. );
  131. const MaskChat = dynamic(
  132. async () => {
  133. await delayer();
  134. return (await import("./mask-chat")).MaskChat
  135. },
  136. {
  137. loading: () => <Loading />,
  138. }
  139. );
  140. const MaskPage = dynamic(
  141. async () => {
  142. await delayer();
  143. return (await import("./mask")).MaskPage
  144. },
  145. {
  146. loading: () => <Loading />,
  147. }
  148. );
  149. export function useSwitchTheme() {
  150. const config = useAppConfig();
  151. useEffect(() => {
  152. document.body.classList.remove("light");
  153. document.body.classList.remove("dark");
  154. if (config.theme === "dark") {
  155. document.body.classList.add("dark");
  156. } else if (config.theme === "light") {
  157. document.body.classList.add("light");
  158. }
  159. const metaDescriptionDark = document.querySelector(
  160. 'meta[name="theme-color"][media*="dark"]',
  161. );
  162. const metaDescriptionLight = document.querySelector(
  163. 'meta[name="theme-color"][media*="light"]',
  164. );
  165. if (config.theme === "auto") {
  166. metaDescriptionDark?.setAttribute("content", "#151515");
  167. metaDescriptionLight?.setAttribute("content", "#fafafa");
  168. } else {
  169. const themeColor = getCSSVar("--theme-color");
  170. metaDescriptionDark?.setAttribute("content", themeColor);
  171. metaDescriptionLight?.setAttribute("content", themeColor);
  172. }
  173. }, [config.theme]);
  174. }
  175. function useHtmlLang() {
  176. useEffect(() => {
  177. const lang = getISOLang();
  178. const htmlLang = document.documentElement.lang;
  179. if (lang !== htmlLang) {
  180. document.documentElement.lang = lang;
  181. }
  182. }, []);
  183. }
  184. const useHasHydrated = () => {
  185. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  186. useEffect(() => {
  187. setHasHydrated(true);
  188. }, []);
  189. return hasHydrated;
  190. };
  191. const loadAsyncGoogleFont = () => {
  192. const linkEl = document.createElement("link");
  193. const proxyFontUrl = "/google-fonts";
  194. const remoteFontUrl = "https://fonts.googleapis.com";
  195. const googleFontUrl =
  196. getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
  197. linkEl.rel = "stylesheet";
  198. linkEl.href =
  199. googleFontUrl +
  200. "/css2?family=" +
  201. encodeURIComponent("Noto Sans:wght@300;400;700;900") +
  202. "&display=swap";
  203. document.head.appendChild(linkEl);
  204. };
  205. export function WindowContent(props: { children: React.ReactNode }) {
  206. return (
  207. <div className={styles["window-content"]} id={SlotID.AppBody}>
  208. {props?.children}
  209. </div>
  210. );
  211. }
  212. function Screen() {
  213. const config = useAppConfig();
  214. const location = useLocation();
  215. const isArtifact = location.pathname.includes(Path.Artifacts);
  216. const isAuth = location.pathname === Path.Auth;
  217. const isMobileScreen = useMobileScreen();
  218. const shouldTightBorder = getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);
  219. useEffect(() => {
  220. loadAsyncGoogleFont();
  221. }, []);
  222. if (isArtifact) {
  223. return (
  224. <Routes>
  225. <Route path="/artifacts/:id" element={<Artifacts />} />
  226. </Routes>
  227. );
  228. }
  229. const renderContent = () => {
  230. if (isAuth) return <AuthPage />;
  231. return (
  232. <>
  233. {/* 招聘首页去除左边历史消息 */}
  234. {
  235. false&&location.pathname !== '/' &&
  236. <SideBar className={styles["sidebar-show"]} />
  237. }
  238. <WindowContent>
  239. <Routes>
  240. <Route path='/' element={<Chat />} />
  241. {/* <Route path='/' element={<HomeApp />} /> */}
  242. <Route path='/knowledgeChat' element={<Chat />} />
  243. <Route path='/newChat' element={<Chat />} />
  244. <Route path='/deepseekChat' element={<DeepSeekChat />} />
  245. <Route path='/newDeepseekChat' element={<DeepSeekChat />} />
  246. {/* 关闭以下入口 后续有需求再开启*/}
  247. {/* <Route path='/settings' element={<Settings />} /> */}
  248. {/* <Route path='/mask-chat' element={<MaskChat />} /> */}
  249. {/* <Route path='/masks' element={<MaskPage />} /> */}
  250. </Routes>
  251. </WindowContent>
  252. </>
  253. );
  254. };
  255. return (
  256. <div
  257. className={`${styles.container} ${shouldTightBorder ? styles["tight-container"] : styles.container
  258. }`}
  259. >
  260. {renderContent()}
  261. </div>
  262. );
  263. }
  264. export function useLoadData() {
  265. const config = useAppConfig();
  266. const api: ClientApi = getClientApi(config.modelConfig.providerName);
  267. useEffect(() => {
  268. (async () => {
  269. const models = await api.llm.models();
  270. config.mergeModels(models);
  271. })();
  272. }, []);
  273. }
  274. export function Home() {
  275. useSwitchTheme();
  276. useLoadData();
  277. useHtmlLang();
  278. useEffect(() => {
  279. useAccessStore.getState().fetch();
  280. }, []);
  281. if (typeof window !== "undefined") {
  282. window.addEventListener("pageshow", (event) => {
  283. const perfEntries = performance.getEntriesByType("navigation");
  284. if (perfEntries.length > 0) {
  285. const navEntry = perfEntries[0] as PerformanceNavigationTiming;
  286. if (navEntry.type === "back_forward") {
  287. window.location.reload();
  288. }
  289. }
  290. });
  291. }
  292. const jkLogin = async (data: { code: string, redirectUrl: string }, url: string) => {
  293. try {
  294. const res = await api.post('jk_code_login', data);
  295. localStorage.setItem('userInfo', JSON.stringify(res.data));
  296. location.replace(url);
  297. } catch (error: any) {
  298. Modal.error({
  299. title: '登录失败',
  300. content: error.msg,
  301. })
  302. }
  303. }
  304. const frameLogin = async (data: { clientId: string,
  305. workspaceId: string,
  306. workspaceName: string,
  307. userName: string,
  308. timestamp: string,
  309. signature: string }, url: string,fullUrl:string) => {
  310. try {
  311. const res = await api.post('frame_login', data);
  312. localStorage.setItem('userInfo', JSON.stringify(res.data));
  313. location.replace(url);
  314. } catch (error: any) {
  315. Modal.error({
  316. title: '登录失败',
  317. content: error.msg,
  318. });
  319. //停留5秒
  320. setTimeout(() => {
  321. toUninLogin(url,fullUrl);
  322. }, 5000);
  323. }
  324. }
  325. const toUninLogin = async (originUrl:string, fullUrl:string) => {
  326. return
  327. //测试环境
  328. //const loginUrl = 'https://esctest.sribs.com.cn/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
  329. //生产环境
  330. const loginUrl = 'http://esc.sribs.com.cn:8080/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
  331. const externalLoginUrl = loginUrl + `&redirect_uri=${encodeURIComponent(originUrl)}&state=${encodeURIComponent(fullUrl)}`;
  332. location.replace(externalLoginUrl);
  333. }
  334. useEffect(() => {
  335. // ==============
  336. // 环境开关:暂时屏蔽 toUninLogin 跳转验证
  337. // 说明:设置 NEXT_PUBLIC_DISABLE_UNIN_LOGIN=1 时,跳过所有统一登录跳转
  338. // 用法:
  339. // 1) 临时禁用:NEXT_PUBLIC_DISABLE_UNIN_LOGIN=1 yarn dev
  340. // 2) 或在 .env.local 中加入 NEXT_PUBLIC_DISABLE_UNIN_LOGIN=1
  341. // ==============
  342. // const DISABLE_UNIN_LOGIN = typeof process !== 'undefined' && process.env.NEXT_PUBLIC_DISABLE_UNIN_LOGIN === '1';
  343. // if (DISABLE_UNIN_LOGIN) {
  344. // console.log('[Home] 统一登录验证已禁用,跳过 toUninLogin 验证');
  345. // return;
  346. // }
  347. // const loginRes = { "nickName": "建科咨询虚拟账号", "userId": "2222331845498970571", "token": "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjAyMDE4Mzg0LTFmNjctNDhkYi05NjNiLTJkOGNhMDMxNTkzMiJ9.zTkTv8gDgJN7tfyxJko_zG1VsESlZACeYkpdMbITqnIpIfvHkZo8l8_Kcv6zo77GnuDyzdpOEt-GzPufD2Ye8A" };
  348. // if (loginRes) {
  349. // return localStorage.setItem('userInfo', JSON.stringify(loginRes));
  350. // }
  351. const originUrl = window.location.origin;
  352. const fullUrl = window.location.href;
  353. const urlParams = new URLSearchParams(new URL(fullUrl).search);
  354. const code = urlParams.get('code');
  355. const state = urlParams.get('state');
  356. const userInfo = localStorage.getItem('userInfo');
  357. if (fullUrl.includes(originUrl + '/?code') && code && state) {// 通过code登陆
  358. if (!userInfo) {
  359. jkLogin({ code: code, redirectUrl: encodeURIComponent(originUrl) }, state);
  360. }
  361. } else {
  362. //判断是否是frame方式联登/frame
  363. if (fullUrl.includes(originUrl + '/?frame=Y')) {
  364. const workspaceId = urlParams.get('workspace_id');
  365. const workspaceName = urlParams.get('workspace_name');
  366. const username = urlParams.get('username');
  367. const clientId = urlParams.get('client_id');
  368. const timestamp = urlParams.get('timestamp');
  369. const signature = urlParams.get('signature');
  370. if (!clientId || !workspaceId || !workspaceName || !username || !timestamp || !signature) {
  371. // 处理缺失参数的情况
  372. Modal.error({
  373. title: '参数错误',
  374. content: '缺少必要的参数',
  375. });
  376. //停留5秒
  377. setTimeout(() => {
  378. toUninLogin(originUrl,fullUrl);
  379. }, 5000);
  380. return;
  381. }
  382. frameLogin({
  383. clientId: clientId,
  384. workspaceId: workspaceId,
  385. workspaceName: workspaceName,
  386. userName: username,
  387. timestamp: timestamp,
  388. signature: signature
  389. },originUrl,fullUrl);
  390. } else {
  391. if (!userInfo) {
  392. toUninLogin(originUrl, fullUrl);
  393. }
  394. }
  395. }
  396. }, []);
  397. if (!useHasHydrated()) {
  398. return <Loading />;
  399. }
  400. return (
  401. <ErrorBoundary>
  402. <Router>
  403. <Screen />
  404. </Router>
  405. </ErrorBoundary>
  406. );
  407. }