home.tsx 8.9 KB

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