home.tsx 14 KB

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