home.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. //
  31. // useEffect(() => {
  32. // let isMounted = true;
  33. //
  34. // const intervalId = setInterval(() => {
  35. // if (isMounted && progress < 100) {
  36. // // 每隔一段时间增加1%进度
  37. // setProgress(prevProgress => prevProgress + 1);
  38. // }
  39. // }, 30);// 每10毫秒更新1%进度
  40. //
  41. // return () => {
  42. // isMounted = false;
  43. // clearInterval(intervalId);
  44. // };
  45. // }, [progress]);
  46. return (
  47. <div className={styles["loading-content"] + " no-dark"}>
  48. <img src={loadingIcon.src} />
  49. {/* seceond版本注释掉进度条 */}
  50. {/* <div style={{ width: '60%', height: 15, background: '#F5F6F9', borderRadius: 8, marginTop: '20%', position: 'relative' }}> */}
  51. {/* <div */}
  52. {/* style={{ */}
  53. {/* width: `${progress}%`, */}
  54. {/* height: 15, */}
  55. {/* background: '#265C7D', */}
  56. {/* borderRadius: 8, */}
  57. {/* display: 'flex', */}
  58. {/* justifyContent: 'flex-end', */}
  59. {/* alignItems: 'center', */}
  60. {/* position: 'absolute' */}
  61. {/* }} */}
  62. {/* > */}
  63. {/* <div style={{ color: '#FFFFFF', fontSize: 12, lineHeight: 12, marginRight: 4 }}> */}
  64. {/* {progress}% */}
  65. {/* </div> */}
  66. {/* </div> */}
  67. {/* </div> */}
  68. </div>
  69. );
  70. }
  71. // 延时器
  72. export const delayer = (): Promise<any> => {
  73. // 延时时间-秒
  74. const time: number = 0.1;
  75. return new Promise((resolve, reject) => {
  76. setTimeout(() => {
  77. resolve({});
  78. }, time * 1000);
  79. });
  80. }
  81. const Artifacts = dynamic(
  82. async () => {
  83. await delayer();
  84. return (await import("./artifacts")).Artifacts
  85. },
  86. {
  87. loading: () => <Loading />,
  88. }
  89. );
  90. const Settings = dynamic(
  91. async () => {
  92. await delayer();
  93. return (await import("./settings")).Settings
  94. },
  95. {
  96. loading: () => <Loading />,
  97. }
  98. );
  99. const Chat = dynamic(
  100. async () => {
  101. await delayer();
  102. return (await import("./chat")).Chat
  103. },
  104. {
  105. loading: () => <Loading />,
  106. }
  107. );
  108. const DeepSeekChat = dynamic(
  109. async () => {
  110. await delayer();
  111. return (await import("./DeepSeekChat")).Chat
  112. },
  113. {
  114. loading: () => <Loading />,
  115. }
  116. );
  117. const Record = dynamic(
  118. async () => {
  119. await delayer();
  120. return (await import("./Record"))
  121. },
  122. {
  123. loading: () => <Loading />,
  124. }
  125. );
  126. const HomeApp = dynamic(
  127. async () => {
  128. return (await import("./DeekSeekHome"))
  129. },
  130. {
  131. loading: () => <Loading />,
  132. }
  133. );
  134. const MaskChat = dynamic(
  135. async () => {
  136. await delayer();
  137. return (await import("./mask-chat")).MaskChat
  138. },
  139. {
  140. loading: () => <Loading />,
  141. }
  142. );
  143. const MaskPage = dynamic(
  144. async () => {
  145. await delayer();
  146. return (await import("./mask")).MaskPage
  147. },
  148. {
  149. loading: () => <Loading />,
  150. }
  151. );
  152. export function useSwitchTheme() {
  153. const config = useAppConfig();
  154. useEffect(() => {
  155. document.body.classList.remove("light");
  156. document.body.classList.remove("dark");
  157. if (config.theme === "dark") {
  158. document.body.classList.add("dark");
  159. } else if (config.theme === "light") {
  160. document.body.classList.add("light");
  161. }
  162. const metaDescriptionDark = document.querySelector(
  163. 'meta[name="theme-color"][media*="dark"]',
  164. );
  165. const metaDescriptionLight = document.querySelector(
  166. 'meta[name="theme-color"][media*="light"]',
  167. );
  168. if (config.theme === "auto") {
  169. metaDescriptionDark?.setAttribute("content", "#151515");
  170. metaDescriptionLight?.setAttribute("content", "#fafafa");
  171. } else {
  172. const themeColor = getCSSVar("--theme-color");
  173. metaDescriptionDark?.setAttribute("content", themeColor);
  174. metaDescriptionLight?.setAttribute("content", themeColor);
  175. }
  176. }, [config.theme]);
  177. }
  178. function useHtmlLang() {
  179. useEffect(() => {
  180. const lang = getISOLang();
  181. const htmlLang = document.documentElement.lang;
  182. if (lang !== htmlLang) {
  183. document.documentElement.lang = lang;
  184. }
  185. }, []);
  186. }
  187. const useHasHydrated = () => {
  188. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  189. useEffect(() => {
  190. setHasHydrated(true);
  191. }, []);
  192. return hasHydrated;
  193. };
  194. const loadAsyncGoogleFont = () => {
  195. const linkEl = document.createElement("link");
  196. const proxyFontUrl = "/google-fonts";
  197. const remoteFontUrl = "https://fonts.googleapis.com";
  198. const googleFontUrl =
  199. getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
  200. linkEl.rel = "stylesheet";
  201. linkEl.href =
  202. googleFontUrl +
  203. "/css2?family=" +
  204. encodeURIComponent("Noto Sans:wght@300;400;700;900") +
  205. "&display=swap";
  206. document.head.appendChild(linkEl);
  207. };
  208. export function WindowContent(props: { children: React.ReactNode }) {
  209. return (
  210. <div className={styles["window-content"]} id={SlotID.AppBody}>
  211. {props?.children}
  212. </div>
  213. );
  214. }
  215. function Screen() {
  216. const config = useAppConfig();
  217. const location = useLocation();
  218. const isArtifact = location.pathname.includes(Path.Artifacts);
  219. const isAuth = location.pathname === Path.Auth;
  220. const isMobileScreen = useMobileScreen();
  221. const shouldTightBorder = getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);
  222. useEffect(() => {
  223. loadAsyncGoogleFont();
  224. }, []);
  225. if (isArtifact) {
  226. return (
  227. <Routes>
  228. <Route path="/artifacts/:id" element={<Artifacts />} />
  229. </Routes>
  230. );
  231. }
  232. const renderContent = () => {
  233. if (isAuth) return <AuthPage />;
  234. return (
  235. <>
  236. {
  237. location.pathname !== '/' &&
  238. <SideBar className={styles["sidebar-show"]} />
  239. }
  240. <WindowContent>
  241. <Routes>
  242. <Route path='/' element={<HomeApp />} />
  243. <Route path='/knowledgeChat' element={<Chat />} />
  244. <Route path='/newChat' element={<Chat />} />
  245. <Route path='/deepseekChat' element={<DeepSeekChat />} />
  246. <Route path='/newDeepseekChat' element={<DeepSeekChat />} />
  247. {/* 关闭以下入口 后续有需求再开启*/}
  248. {/* <Route path='/settings' element={<Settings />} /> */}
  249. {/* <Route path='/mask-chat' element={<MaskChat />} /> */}
  250. {/* <Route path='/masks' element={<MaskPage />} /> */}
  251. </Routes>
  252. </WindowContent>
  253. </>
  254. );
  255. };
  256. return (
  257. <div
  258. className={`${styles.container} ${shouldTightBorder ? styles["tight-container"] : styles.container
  259. }`}
  260. >
  261. {renderContent()}
  262. </div>
  263. );
  264. }
  265. export function useLoadData() {
  266. const config = useAppConfig();
  267. const api: ClientApi = getClientApi(config.modelConfig.providerName);
  268. useEffect(() => {
  269. (async () => {
  270. const models = await api.llm.models();
  271. config.mergeModels(models);
  272. })();
  273. }, []);
  274. }
  275. export function Home() {
  276. useSwitchTheme();
  277. useLoadData();
  278. useHtmlLang();
  279. useEffect(() => {
  280. useAccessStore.getState().fetch();
  281. }, []);
  282. if (typeof window !== "undefined") {
  283. window.addEventListener("pageshow", (event) => {
  284. const perfEntries = performance.getEntriesByType("navigation");
  285. if (perfEntries.length > 0) {
  286. const navEntry = perfEntries[0] as PerformanceNavigationTiming;
  287. if (navEntry.type === "back_forward") {
  288. window.location.reload();
  289. }
  290. }
  291. });
  292. }
  293. const jkLogin = async (data: { code: string, redirectUrl: string }, url: string) => {
  294. try {
  295. const res = await api.post('jk_code_login', data);
  296. localStorage.setItem('userInfo', JSON.stringify(res.data));
  297. location.replace(url);
  298. } catch (error: any) {
  299. Modal.error({
  300. title: '登录失败',
  301. content: error.msg,
  302. })
  303. }
  304. }
  305. const frameLogin = async (data: { clientId: string,
  306. workspaceId: string,
  307. workspaceName: string,
  308. userName: string,
  309. timestamp: string,
  310. signature: string }, url: string,fullUrl:string) => {
  311. try {
  312. const res = await api.post('frame_login', data);
  313. localStorage.setItem('userInfo', JSON.stringify(res.data));
  314. location.replace(url);
  315. } catch (error: any) {
  316. Modal.error({
  317. title: '登录失败',
  318. content: error.msg,
  319. });
  320. //停留5秒
  321. setTimeout(() => {
  322. toUninLogin(url,fullUrl);
  323. }, 5000);
  324. }
  325. }
  326. const toUninLogin = async (originUrl:string, fullUrl:string) => {
  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. if (!userInfo) {
  363. //判断是否是frame方式联登/frame
  364. if (fullUrl.includes(originUrl + '/?frame=Y')) {
  365. const workspaceId = urlParams.get('workspace_id');
  366. const workspaceName = urlParams.get('workspace_name');
  367. const username = urlParams.get('username');
  368. const clientId = urlParams.get('client_id');
  369. const timestamp = urlParams.get('timestamp');
  370. const signature = urlParams.get('signature');
  371. if (!clientId || !workspaceId || !workspaceName || !username || !timestamp || !signature) {
  372. // 处理缺失参数的情况
  373. Modal.error({
  374. title: '参数错误',
  375. content: '缺少必要的参数',
  376. });
  377. //停留5秒
  378. setTimeout(() => {
  379. toUninLogin(originUrl,fullUrl);
  380. }, 5000);
  381. return;
  382. }
  383. frameLogin({
  384. clientId: clientId,
  385. workspaceId: workspaceId,
  386. workspaceName: workspaceName,
  387. userName: username,
  388. timestamp: timestamp,
  389. signature: signature
  390. },originUrl,fullUrl);
  391. } else {
  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. }