sidebar.tsx 10 KB

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