home.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. "use client";
  2. require("../polyfill");
  3. import { useEffect, useState } from "react";
  4. import styles from "./home.module.scss";
  5. import BotIcon from "../icons/bot.svg";
  6. import LoadingIcon from "../icons/three-dots.svg";
  7. import { getCSSVar, useMobileScreen } from "../utils";
  8. import dynamic from "next/dynamic";
  9. import { Path, SlotID } from "../constant";
  10. import { ErrorBoundary } from "./error";
  11. import { getISOLang, getLang } from "../locales";
  12. import {
  13. HashRouter as Router,
  14. Route,
  15. Routes,
  16. useLocation,
  17. } from "react-router-dom";
  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 clsx from "clsx";
  25. import { initializeMcpSystem, isMcpEnabled } from "../mcp/actions";
  26. export function Loading(props: { noLogo?: boolean }) {
  27. return (
  28. <div className={clsx("no-dark", styles["loading-content"])}>
  29. {!props.noLogo && <BotIcon />}
  30. <LoadingIcon />
  31. </div>
  32. );
  33. }
  34. const Artifacts = dynamic(async () => (await import("./artifacts")).Artifacts, {
  35. loading: () => <Loading noLogo />,
  36. });
  37. const Settings = dynamic(async () => (await import("./settings")).Settings, {
  38. loading: () => <Loading noLogo />,
  39. });
  40. const Chat = dynamic(async () => (await import("./chat")).Chat, {
  41. loading: () => <Loading noLogo />,
  42. });
  43. const NewChat = dynamic(async () => (await import("./new-chat")).NewChat, {
  44. loading: () => <Loading noLogo />,
  45. });
  46. const MaskPage = dynamic(async () => (await import("./mask")).MaskPage, {
  47. loading: () => <Loading noLogo />,
  48. });
  49. const PluginPage = dynamic(async () => (await import("./plugin")).PluginPage, {
  50. loading: () => <Loading noLogo />,
  51. });
  52. const SearchChat = dynamic(
  53. async () => (await import("./search-chat")).SearchChatPage,
  54. {
  55. loading: () => <Loading noLogo />,
  56. },
  57. );
  58. const McpMarketPage = dynamic(
  59. async () => (await import("./mcp-market")).McpMarketPage,
  60. {
  61. loading: () => <Loading noLogo />,
  62. },
  63. );
  64. export function useSwitchTheme() {
  65. const config = useAppConfig();
  66. useEffect(() => {
  67. document.body.classList.remove("light");
  68. document.body.classList.remove("dark");
  69. if (config.theme === "dark") {
  70. document.body.classList.add("dark");
  71. } else if (config.theme === "light") {
  72. document.body.classList.add("light");
  73. }
  74. const metaDescriptionDark = document.querySelector(
  75. 'meta[name="theme-color"][media*="dark"]',
  76. );
  77. const metaDescriptionLight = document.querySelector(
  78. 'meta[name="theme-color"][media*="light"]',
  79. );
  80. if (config.theme === "auto") {
  81. metaDescriptionDark?.setAttribute("content", "#151515");
  82. metaDescriptionLight?.setAttribute("content", "#fafafa");
  83. } else {
  84. const themeColor = getCSSVar("--theme-color");
  85. metaDescriptionDark?.setAttribute("content", themeColor);
  86. metaDescriptionLight?.setAttribute("content", themeColor);
  87. }
  88. }, [config.theme]);
  89. }
  90. function useHtmlLang() {
  91. useEffect(() => {
  92. const lang = getISOLang();
  93. const htmlLang = document.documentElement.lang;
  94. if (lang !== htmlLang) {
  95. document.documentElement.lang = lang;
  96. }
  97. }, []);
  98. }
  99. const useHasHydrated = () => {
  100. const [hasHydrated, setHasHydrated] = useState<boolean>(false);
  101. useEffect(() => {
  102. setHasHydrated(true);
  103. }, []);
  104. return hasHydrated;
  105. };
  106. const loadAsyncGoogleFont = () => {
  107. const linkEl = document.createElement("link");
  108. const proxyFontUrl = "/google-fonts";
  109. const remoteFontUrl = "https://fonts.googleapis.com";
  110. const googleFontUrl =
  111. getClientConfig()?.buildMode === "export" ? remoteFontUrl : proxyFontUrl;
  112. linkEl.rel = "stylesheet";
  113. linkEl.href =
  114. googleFontUrl +
  115. "/css2?family=" +
  116. encodeURIComponent("Noto Sans:wght@300;400;700;900") +
  117. "&display=swap";
  118. document.head.appendChild(linkEl);
  119. };
  120. export function WindowContent(props: { children: React.ReactNode }) {
  121. return (
  122. <div className={styles["window-content"]} id={SlotID.AppBody}>
  123. {props?.children}
  124. </div>
  125. );
  126. }
  127. function Screen() {
  128. const config = useAppConfig();
  129. const location = useLocation();
  130. const isArtifact = location.pathname.includes(Path.Artifacts);
  131. const isHome = location.pathname === Path.Home;
  132. const isAuth = location.pathname === Path.Auth;
  133. const isMobileScreen = useMobileScreen();
  134. const shouldTightBorder =
  135. getClientConfig()?.isApp || (config.tightBorder && !isMobileScreen);
  136. useEffect(() => {
  137. loadAsyncGoogleFont();
  138. }, []);
  139. if (isArtifact) {
  140. return (
  141. <Routes>
  142. <Route path="/artifacts/:id" element={<Artifacts />} />
  143. </Routes>
  144. );
  145. }
  146. const renderContent = () => {
  147. if (isAuth) return <AuthPage />;
  148. return (
  149. <>
  150. <SideBar
  151. className={clsx({
  152. [styles["sidebar-show"]]: isHome,
  153. })}
  154. />
  155. <WindowContent>
  156. <Routes>
  157. <Route path={Path.Home} element={<Chat />} />
  158. <Route path={Path.NewChat} element={<NewChat />} />
  159. <Route path={Path.Masks} element={<MaskPage />} />
  160. <Route path={Path.Plugins} element={<PluginPage />} />
  161. <Route path={Path.SearchChat} element={<SearchChat />} />
  162. <Route path={Path.Chat} element={<Chat />} />
  163. <Route path={Path.Settings} element={<Settings />} />
  164. <Route path={Path.McpMarket} element={<McpMarketPage />} />
  165. </Routes>
  166. </WindowContent>
  167. </>
  168. );
  169. };
  170. return (
  171. <div
  172. className={clsx(styles.container, {
  173. [styles["tight-container"]]: shouldTightBorder,
  174. [styles["rtl-screen"]]: getLang() === "ar",
  175. })}
  176. >
  177. {renderContent()}
  178. </div>
  179. );
  180. }
  181. export function useLoadData() {
  182. const config = useAppConfig();
  183. const api: ClientApi = getClientApi(config.modelConfig.providerName);
  184. useEffect(() => {
  185. (async () => {
  186. const models = await api.llm.models();
  187. config.mergeModels(models);
  188. })();
  189. // eslint-disable-next-line react-hooks/exhaustive-deps
  190. }, []);
  191. }
  192. export function Home() {
  193. useSwitchTheme();
  194. useLoadData();
  195. useHtmlLang();
  196. useEffect(() => {
  197. console.log("[Config] got config from build time", getClientConfig());
  198. useAccessStore.getState().fetch();
  199. const initMcp = async () => {
  200. try {
  201. const enabled = await isMcpEnabled();
  202. if (enabled) {
  203. console.log("[MCP] initializing...");
  204. await initializeMcpSystem();
  205. console.log("[MCP] initialized");
  206. }
  207. } catch (err) {
  208. console.error("[MCP] failed to initialize:", err);
  209. }
  210. };
  211. initMcp();
  212. }, []);
  213. if (!useHasHydrated()) {
  214. return <Loading />;
  215. }
  216. return (
  217. <ErrorBoundary>
  218. <Router>
  219. <Screen />
  220. </Router>
  221. </ErrorBoundary>
  222. );
  223. }