sidebar.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. import React, { Fragment, useEffect, useMemo, useRef, useState } from "react";
  2. import styles from "./home.module.scss";
  3. import { IconButton } from "./button";
  4. import SettingsIcon from "../icons/settings.svg";
  5. import GithubIcon from "../icons/github.svg";
  6. import ChatGptIcon from "../icons/chatgpt.svg";
  7. import AddIcon from "../icons/add.svg";
  8. import DeleteIcon from "../icons/delete.svg";
  9. import MaskIcon from "../icons/mask.svg";
  10. import McpIcon from "../icons/mcp.svg";
  11. import DragIcon from "../icons/drag.svg";
  12. import DiscoveryIcon from "../icons/discovery.svg";
  13. import Locale from "../locales";
  14. import { useAppConfig, useChatStore } from "../store";
  15. import {
  16. DEFAULT_SIDEBAR_WIDTH,
  17. MAX_SIDEBAR_WIDTH,
  18. MIN_SIDEBAR_WIDTH,
  19. NARROW_SIDEBAR_WIDTH,
  20. Path,
  21. REPO_URL,
  22. } from "../constant";
  23. import { Link, useNavigate } from "react-router-dom";
  24. import { isIOS, useMobileScreen } from "../utils";
  25. import dynamic from "next/dynamic";
  26. import { Selector, showConfirm } from "./ui-lib";
  27. import clsx from "clsx";
  28. import { isMcpEnabled } from "../mcp/actions";
  29. const DISCOVERY = [
  30. { name: Locale.Plugin.Name, path: Path.Plugins },
  31. { name: "Stable Diffusion", path: Path.Sd },
  32. { name: Locale.SearchChat.Page.Title, path: Path.SearchChat },
  33. ];
  34. const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
  35. loading: () => null,
  36. });
  37. export function useHotKey() {
  38. const chatStore = useChatStore();
  39. useEffect(() => {
  40. const onKeyDown = (e: KeyboardEvent) => {
  41. if (e.altKey || e.ctrlKey) {
  42. if (e.key === "ArrowUp") {
  43. chatStore.nextSession(-1);
  44. } else if (e.key === "ArrowDown") {
  45. chatStore.nextSession(1);
  46. }
  47. }
  48. };
  49. window.addEventListener("keydown", onKeyDown);
  50. return () => window.removeEventListener("keydown", onKeyDown);
  51. });
  52. }
  53. export function useDragSideBar() {
  54. const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
  55. const config = useAppConfig();
  56. const startX = useRef(0);
  57. const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  58. const lastUpdateTime = useRef(Date.now());
  59. const toggleSideBar = () => {
  60. config.update((config) => {
  61. if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) {
  62. config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH;
  63. } else {
  64. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  65. }
  66. });
  67. };
  68. const onDragStart = (e: MouseEvent) => {
  69. // Remembers the initial width each time the mouse is pressed
  70. startX.current = e.clientX;
  71. startDragWidth.current = config.sidebarWidth;
  72. const dragStartTime = Date.now();
  73. const handleDragMove = (e: MouseEvent) => {
  74. if (Date.now() < lastUpdateTime.current + 20) {
  75. return;
  76. }
  77. lastUpdateTime.current = Date.now();
  78. const d = e.clientX - startX.current;
  79. const nextWidth = limit(startDragWidth.current + d);
  80. config.update((config) => {
  81. if (nextWidth < MIN_SIDEBAR_WIDTH) {
  82. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  83. } else {
  84. config.sidebarWidth = nextWidth;
  85. }
  86. });
  87. };
  88. const handleDragEnd = () => {
  89. // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth
  90. window.removeEventListener("pointermove", handleDragMove);
  91. window.removeEventListener("pointerup", handleDragEnd);
  92. // if user click the drag icon, should toggle the sidebar
  93. const shouldFireClick = Date.now() - dragStartTime < 300;
  94. if (shouldFireClick) {
  95. toggleSideBar();
  96. }
  97. };
  98. window.addEventListener("pointermove", handleDragMove);
  99. window.addEventListener("pointerup", handleDragEnd);
  100. };
  101. const isMobileScreen = useMobileScreen();
  102. const shouldNarrow =
  103. !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;
  104. useEffect(() => {
  105. const barWidth = shouldNarrow
  106. ? NARROW_SIDEBAR_WIDTH
  107. : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  108. const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
  109. document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
  110. }, [config.sidebarWidth, isMobileScreen, shouldNarrow]);
  111. return {
  112. onDragStart,
  113. shouldNarrow,
  114. };
  115. }
  116. export function SideBarContainer(props: {
  117. children: React.ReactNode;
  118. onDragStart: (e: MouseEvent) => void;
  119. shouldNarrow: boolean;
  120. className?: string;
  121. }) {
  122. const isMobileScreen = useMobileScreen();
  123. const isIOSMobile = useMemo(
  124. () => isIOS() && isMobileScreen,
  125. [isMobileScreen],
  126. );
  127. const { children, className, onDragStart, shouldNarrow } = props;
  128. return (
  129. <div
  130. className={clsx(styles.sidebar, className, {
  131. [styles["narrow-sidebar"]]: shouldNarrow,
  132. })}
  133. style={{
  134. // #3016 disable transition on ios mobile screen
  135. transition: isMobileScreen && isIOSMobile ? "none" : undefined,
  136. }}
  137. >
  138. {children}
  139. <div
  140. className={styles["sidebar-drag"]}
  141. onPointerDown={(e) => onDragStart(e as any)}
  142. >
  143. <DragIcon />
  144. </div>
  145. </div>
  146. );
  147. }
  148. export function SideBarHeader(props: {
  149. title?: string | React.ReactNode;
  150. subTitle?: string | React.ReactNode;
  151. logo?: React.ReactNode;
  152. children?: React.ReactNode;
  153. shouldNarrow?: boolean;
  154. }) {
  155. const { title, subTitle, logo, children, shouldNarrow } = props;
  156. return (
  157. <Fragment>
  158. <div
  159. className={clsx(styles["sidebar-header"], {
  160. [styles["sidebar-header-narrow"]]: shouldNarrow,
  161. })}
  162. data-tauri-drag-region
  163. >
  164. <div className={styles["sidebar-title-container"]}>
  165. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  166. {title}
  167. </div>
  168. <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
  169. </div>
  170. <div className={clsx(styles["sidebar-logo"], "no-dark")}>{logo}</div>
  171. </div>
  172. {children}
  173. </Fragment>
  174. );
  175. }
  176. export function SideBarBody(props: {
  177. children: React.ReactNode;
  178. onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  179. }) {
  180. const { onClick, children } = props;
  181. return (
  182. <div className={styles["sidebar-body"]} onClick={onClick}>
  183. {children}
  184. </div>
  185. );
  186. }
  187. export function SideBarTail(props: {
  188. primaryAction?: React.ReactNode;
  189. secondaryAction?: React.ReactNode;
  190. }) {
  191. const { primaryAction, secondaryAction } = props;
  192. return (
  193. <div className={styles["sidebar-tail"]}>
  194. <div className={styles["sidebar-actions"]}>{primaryAction}</div>
  195. <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
  196. </div>
  197. );
  198. }
  199. export function SideBar(props: { className?: string }) {
  200. useHotKey();
  201. const { onDragStart, shouldNarrow } = useDragSideBar();
  202. const [showDiscoverySelector, setshowDiscoverySelector] = useState(false);
  203. const navigate = useNavigate();
  204. const config = useAppConfig();
  205. const chatStore = useChatStore();
  206. const [mcpEnabled, setMcpEnabled] = useState(false);
  207. useEffect(() => {
  208. // 检查 MCP 是否启用
  209. const checkMcpStatus = async () => {
  210. const enabled = await isMcpEnabled();
  211. setMcpEnabled(enabled);
  212. console.log("[SideBar] MCP enabled:", enabled);
  213. };
  214. checkMcpStatus();
  215. }, []);
  216. return (
  217. <SideBarContainer
  218. onDragStart={onDragStart}
  219. shouldNarrow={shouldNarrow}
  220. {...props}
  221. >
  222. <SideBarHeader
  223. title="NextChat"
  224. subTitle="Build your own AI assistant."
  225. logo={<ChatGptIcon />}
  226. shouldNarrow={shouldNarrow}
  227. >
  228. <div className={styles["sidebar-header-bar"]}>
  229. <IconButton
  230. icon={<MaskIcon />}
  231. text={shouldNarrow ? undefined : Locale.Mask.Name}
  232. className={styles["sidebar-bar-button"]}
  233. onClick={() => {
  234. if (config.dontShowMaskSplashScreen !== true) {
  235. navigate(Path.NewChat, { state: { fromHome: true } });
  236. } else {
  237. navigate(Path.Masks, { state: { fromHome: true } });
  238. }
  239. }}
  240. shadow
  241. />
  242. {mcpEnabled && (
  243. <IconButton
  244. icon={<McpIcon />}
  245. text={shouldNarrow ? undefined : Locale.Mcp.Name}
  246. className={styles["sidebar-bar-button"]}
  247. onClick={() => {
  248. navigate(Path.McpMarket, { state: { fromHome: true } });
  249. }}
  250. shadow
  251. />
  252. )}
  253. <IconButton
  254. icon={<DiscoveryIcon />}
  255. text={shouldNarrow ? undefined : Locale.Discovery.Name}
  256. className={styles["sidebar-bar-button"]}
  257. onClick={() => setshowDiscoverySelector(true)}
  258. shadow
  259. />
  260. </div>
  261. {showDiscoverySelector && (
  262. <Selector
  263. items={[
  264. ...DISCOVERY.map((item) => {
  265. return {
  266. title: item.name,
  267. value: item.path,
  268. };
  269. }),
  270. ]}
  271. onClose={() => setshowDiscoverySelector(false)}
  272. onSelection={(s) => {
  273. navigate(s[0], { state: { fromHome: true } });
  274. }}
  275. />
  276. )}
  277. </SideBarHeader>
  278. <SideBarBody
  279. onClick={(e) => {
  280. if (e.target === e.currentTarget) {
  281. navigate(Path.Home);
  282. }
  283. }}
  284. >
  285. <ChatList narrow={shouldNarrow} />
  286. </SideBarBody>
  287. <SideBarTail
  288. primaryAction={
  289. <>
  290. <div className={clsx(styles["sidebar-action"], styles.mobile)}>
  291. <IconButton
  292. icon={<DeleteIcon />}
  293. onClick={async () => {
  294. if (await showConfirm(Locale.Home.DeleteChat)) {
  295. chatStore.deleteSession(chatStore.currentSessionIndex);
  296. }
  297. }}
  298. />
  299. </div>
  300. <div className={styles["sidebar-action"]}>
  301. <Link to={Path.Settings}>
  302. <IconButton
  303. aria={Locale.Settings.Title}
  304. icon={<SettingsIcon />}
  305. shadow
  306. />
  307. </Link>
  308. </div>
  309. <div className={styles["sidebar-action"]}>
  310. <a href={REPO_URL} target="_blank" rel="noopener noreferrer">
  311. <IconButton
  312. aria={Locale.Export.MessageFromChatGPT}
  313. icon={<GithubIcon />}
  314. shadow
  315. />
  316. </a>
  317. </div>
  318. </>
  319. }
  320. secondaryAction={
  321. <IconButton
  322. icon={<AddIcon />}
  323. text={shouldNarrow ? undefined : Locale.Home.NewChat}
  324. onClick={() => {
  325. if (config.dontShowMaskSplashScreen) {
  326. chatStore.newSession();
  327. navigate(Path.Chat);
  328. } else {
  329. navigate(Path.NewChat);
  330. }
  331. }}
  332. shadow
  333. />
  334. }
  335. />
  336. </SideBarContainer>
  337. );
  338. }