home.tsx 7.0 KB

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