sidebar.tsx 10 KB

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