home.tsx 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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. } from "react-router-dom";
  11. import styles from "./home.module.scss";
  12. import BotIcon from "../icons/bot.svg";
  13. import loadingIcon from "../icons/loading.gif";
  14. import { getCSSVar, useMobileScreen } from "../utils";
  15. import dynamic from "next/dynamic";
  16. import { Path, SlotID } from "../constant";
  17. import { ErrorBoundary } from "./error";
  18. import { getISOLang, getLang } from "../locales";
  19. import { SideBar } from "./sidebar";
  20. import { useAppConfig } from "../store/config";
  21. import { AuthPage } from "./auth";
  22. import { getClientConfig } from "../config/client";
  23. import { type ClientApi, getClientApi } from "../client/api";
  24. import { useAccessStore } from "../store";
  25. import api from "../api/api";
  26. export function Loading() {
  27. /** second版本注释掉进度条 */
  28. // const [progress, setProgress] = useState(1);
  29. //
  30. // useEffect(() => {
  31. // let isMounted = true;
  32. //
  33. // const intervalId = setInterval(() => {
  34. // if (isMounted && progress < 100) {
  35. // // 每隔一段时间增加1%进度
  36. // setProgress(prevProgress => prevProgress + 1);
  37. // }
  38. // }, 30);// 每10毫秒更新1%进度
  39. //
  40. // return () => {
  41. // isMounted = false;
  42. // clearInterval(intervalId);
  43. // };
  44. // }, [progress]);
  45. return (
  46. <div className={styles["loading-content"] + " no-dark"}>
  47. <img src={loadingIcon.src} />
  48. {/* seceond版本注释掉进度条 */}
  49. {/* <div style={{ width: '60%', height: 15, background: '#F5F6F9', borderRadius: 8, marginTop: '20%', position: 'relative' }}> */}
  50. {/* <div */}
  51. {/* style={{ */}
  52. {/* width: `${progress}%`, */}
  53. {/* height: 15, */}
  54. {/* background: '#265C7D', */}
  55. {/* borderRadius: 8, */}
  56. {/* display: 'flex', */}
  57. {/* justifyContent: 'flex-end', */}
  58. {/* alignItems: 'center', */}
  59. {/* position: 'absolute' */}
  60. {/* }} */}
  61. {/* > */}
  62. {/* <div style={{ color: '#FFFFFF', fontSize: 12, lineHeight: 12, marginRight: 4 }}> */}
  63. {/* {progress}% */}
  64. {/* </div> */}
  65. {/* </div> */}
  66. {/* </div> */}
  67. </div>
  68. );
  69. }
  70. // 延时器
  71. export const delayer = (): Promise<any> => {
  72. // 延时时间-秒
  73. const time: number = 0.1;
  74. return new Promise((resolve, reject) => {
  75. setTimeout(() => {
  76. resolve({});
  77. }, time * 1000);
  78. });
  79. }
  80. const Artifacts = dynamic(
  81. async () => {
  82. await delayer();
  83. return (await import("./artifacts")).Artifacts
  84. },
  85. {
  86. loading: () => <Loading />,
  87. }
  88. );
  89. const Settings = dynamic(
  90. async () => {
  91. await delayer();
  92. return (await import("./settings")).Settings
  93. },
  94. {
  95. loading: () => <Loading />,
  96. }
  97. );
  98. const Chat = dynamic(
  99. async () => {
  100. await delayer();
  101. return (await import("./chat")).Chat
  102. },
  103. {
  104. loading: () => <Loading />,
  105. }
  106. );
  107. const DeepSeekChat = dynamic(
  108. async () => {
  109. await delayer();
  110. return (await import("./DeepSeekChat")).Chat
  111. },
  112. {
  113. loading: () => <Loading />,
  114. }
  115. );
  116. const Record = dynamic(
  117. async () => {
  118. await delayer();
  119. return (await import("./Record"))
  120. },
  121. {
  122. loading: () => <Loading />,
  123. }
  124. );
  125. const HomeApp = dynamic(
  126. async () => {
  127. return (await import("./DeekSeekHome"))
  128. },
  129. {
  130. loading: () => <Loading />,
  131. }
  132. );
  133. const NewChat = dynamic(
  134. async () => {
  135. await delayer();
  136. return (await import("./new-chat")).NewChat
  137. },
  138. {
  139. loading: () => <Loading />,
  140. }
  141. );
  142. const MaskPage = dynamic(
  143. async () => {
  144. await delayer();
  145. return (await import("./mask")).MaskPage
  146. },
  147. {
  148. loading: () => <Loading />,
  149. }
  150. );
  151. export function useSwitchTheme() {
  152. const config = useAppConfig();
  153. useEffect(() => {
  154. document.body.classList.remove("light");
  155. document.body.classList.remove("dark");
  156. if (config.theme === "dark") {
  157. document.body.classList.add("dark");
  158. } else if (config.theme === "light") {
  159. document.body.classList.add("light");
  160. }
  161. const metaDescriptionDark = document.querySelector(
  162. 'meta[name="theme-color"][media*="dark"]',
  163. );
  164. const metaDescriptionLight = document.querySelector(
  165. 'meta[name="theme-color"][media*="light"]',
  166. );
  167. if (config.theme === "auto") {
  168. metaDescriptionDark?.setAttribute("content", "#151515");
  169. metaDescriptionLight?.setAttribute("content", "#fafafa");
  170. } else {
  171. const themeColor = getCSSVar("--theme-color");
  172. metaDescriptionDark?.setAttribute("content", themeColor);
  173. metaDescriptionLight?.setAttribute("content", themeColor);
  174. }
  175. }, [config.theme]);
  176. }
  177. function useHtmlLang() {
  178. useEffect(() => {
  179. const lang = getISOLang();
  180. const htmlLang = document.documentElement.lang;
  181. if (lang !== htmlLang) {
  182. document.documentElement.lang = lang;
  183. }
  184. }, []);
  185. }
  186. const useHasHydrated = () => {
  187. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  188. useEffect(() => {
  189. setHasHydrated(true);
  190. }, []);
  191. return hasHydrated;
  192. };
  193. const loadAsyncGoogleFont = () => {
  194. const linkEl = document.createElement("link");
  195. const proxyFontUrl = "/google-fonts";
  196. const remoteFontUrl = "https://fonts.googleapis.com";
  197. const googleFontUrl =
  198. getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
  199. linkEl.rel = "stylesheet";
  200. linkEl.href =
  201. googleFontUrl +
  202. "/css2?family=" +
  203. encodeURIComponent("Noto Sans:wght@300;400;700;900") +
  204. "&display=swap";
  205. document.head.appendChild(linkEl);
  206. };
  207. export function WindowContent(props: { children: React.ReactNode }) {
  208. return (
  209. <div className={styles["window-content"]} id={SlotID.AppBody}>
  210. {props?.children}
  211. </div>
  212. );
  213. }
  214. function Screen() {
  215. const config = useAppConfig();
  216. const location = useLocation();
  217. const isArtifact = location.pathname.includes(Path.Artifacts);
  218. const isAuth = location.pathname === Path.Auth;
  219. const isMobileScreen = useMobileScreen();
  220. const shouldTightBorder = getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);
  221. useEffect(() => {
  222. loadAsyncGoogleFont();
  223. }, []);
  224. if (isArtifact) {
  225. return (
  226. <Routes>
  227. <Route path="/artifacts/:id" element={<Artifacts />} />
  228. </Routes>
  229. );
  230. }
  231. const renderContent = () => {
  232. if (isAuth) return <AuthPage />;
  233. return (
  234. <>
  235. {
  236. location.pathname !== '/' &&
  237. <SideBar className={styles["sidebar-show"]} />
  238. }
  239. <WindowContent>
  240. <Routes>
  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. </Routes>
  247. </WindowContent>
  248. </>
  249. );
  250. };
  251. return (
  252. <div
  253. className={`${styles.container} ${shouldTightBorder ? styles["tight-container"] : styles.container
  254. }`}
  255. >
  256. {renderContent()}
  257. </div>
  258. );
  259. }
  260. export function useLoadData() {
  261. const config = useAppConfig();
  262. const api: ClientApi = getClientApi(config.modelConfig.providerName);
  263. useEffect(() => {
  264. (async () => {
  265. const models = await api.llm.models();
  266. config.mergeModels(models);
  267. })();
  268. }, []);
  269. }
  270. export function Home() {
  271. useSwitchTheme();
  272. useLoadData();
  273. useHtmlLang();
  274. useEffect(() => {
  275. useAccessStore.getState().fetch();
  276. }, []);
  277. const jkLogin = async (data: { code: string, redirectUrl: string }, url: string) => {
  278. try {
  279. const res = await api.post('jk_code_login', data);
  280. localStorage.setItem('userInfo', JSON.stringify(res.data));
  281. window.open(url, '_self');
  282. } catch (error: any) {
  283. Modal.error({
  284. title: '登录失败',
  285. content: error.msg,
  286. })
  287. }
  288. }
  289. useEffect(() => {
  290. // const loginRes = { "nickName": "建科咨询虚拟账号", "userId": "2222331845498970571", "token": "eyJhbGciOiJIUzUxMiJ9.eyJsb2dpbl91c2VyX2tleSI6IjAyMDE4Mzg0LTFmNjctNDhkYi05NjNiLTJkOGNhMDMxNTkzMiJ9.zTkTv8gDgJN7tfyxJko_zG1VsESlZACeYkpdMbITqnIpIfvHkZo8l8_Kcv6zo77GnuDyzdpOEt-GzPufD2Ye8A" };
  291. // if (loginRes) {
  292. // return localStorage.setItem('userInfo', JSON.stringify(loginRes));
  293. // }
  294. const originUrl = window.location.origin;
  295. const fullUrl = window.location.href;
  296. const urlParams = new URLSearchParams(new URL(fullUrl).search);
  297. const code = urlParams.get('code');
  298. const state = urlParams.get('state');
  299. const userInfo = localStorage.getItem('userInfo');
  300. if (fullUrl.includes(originUrl + '/?code') && code && state) {// 通过code登陆
  301. if (!userInfo) {
  302. jkLogin({ code: code, redirectUrl: encodeURIComponent(originUrl) }, state);
  303. }
  304. } else {
  305. //测试环境
  306. //const loginUrl = 'https://esctest.sribs.com.cn/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
  307. //生产环境
  308. const loginUrl = 'http://esc.sribs.com.cn:8080/esc-sso/oauth2.0/authorize?client_id=e97f94cf93761f4d69e8&response_type=code';
  309. const externalLoginUrl = loginUrl + `&redirect_uri=${encodeURIComponent(originUrl)}&state=${encodeURIComponent(fullUrl)}`;
  310. if (!userInfo) {
  311. window.open(externalLoginUrl, '_self');
  312. }
  313. }
  314. }, []);
  315. if (!useHasHydrated()) {
  316. return <Loading />;
  317. }
  318. return (
  319. <ErrorBoundary>
  320. <Router>
  321. <Screen />
  322. </Router>
  323. </ErrorBoundary>
  324. );
  325. }