sidebar.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 CloseIcon from "../icons/close.svg";
  9. import DeleteIcon from "../icons/delete.svg";
  10. import MaskIcon from "../icons/mask.svg";
  11. import DragIcon from "../icons/drag.svg";
  12. import DiscoveryIcon from "../icons/discovery.svg";
  13. import SearchIcon from "../icons/zoom.svg";
  14. import Locale from "../locales";
  15. import { useAppConfig, useChatStore } from "../store";
  16. import {
  17. DEFAULT_SIDEBAR_WIDTH,
  18. MAX_SIDEBAR_WIDTH,
  19. MIN_SIDEBAR_WIDTH,
  20. NARROW_SIDEBAR_WIDTH,
  21. Path,
  22. PLUGINS,
  23. REPO_URL,
  24. } from "../constant";
  25. import { Link, useNavigate } from "react-router-dom";
  26. import { isIOS, useMobileScreen } from "../utils";
  27. import dynamic from "next/dynamic";
  28. import { showConfirm, Selector } from "./ui-lib";
  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={`${styles.sidebar} ${className} ${
  126. shouldNarrow && styles["narrow-sidebar"]
  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. }) {
  149. const { title, subTitle, logo, children } = props;
  150. return (
  151. <Fragment>
  152. <div className={styles["sidebar-header"]} data-tauri-drag-region>
  153. <div className={styles["sidebar-title-container"]}>
  154. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  155. {title}
  156. </div>
  157. <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
  158. </div>
  159. <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
  160. </div>
  161. {children}
  162. </Fragment>
  163. );
  164. }
  165. export function SideBarBody(props: {
  166. children: React.ReactNode;
  167. onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  168. }) {
  169. const { onClick, children } = props;
  170. return (
  171. <div className={styles["sidebar-body"]} onClick={onClick}>
  172. {children}
  173. </div>
  174. );
  175. }
  176. export function SideBarTail(props: {
  177. primaryAction?: React.ReactNode;
  178. secondaryAction?: React.ReactNode;
  179. }) {
  180. const { primaryAction, secondaryAction } = props;
  181. return (
  182. <div className={styles["sidebar-tail"]}>
  183. <div className={styles["sidebar-actions"]}>{primaryAction}</div>
  184. <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
  185. </div>
  186. );
  187. }
  188. export function SideBar(props: { className?: string }) {
  189. useHotKey();
  190. const { onDragStart, shouldNarrow } = useDragSideBar();
  191. const [showPluginSelector, setShowPluginSelector] = useState(false);
  192. const navigate = useNavigate();
  193. const config = useAppConfig();
  194. const chatStore = useChatStore();
  195. return (
  196. <SideBarContainer
  197. onDragStart={onDragStart}
  198. shouldNarrow={shouldNarrow}
  199. {...props}
  200. >
  201. <SideBarHeader
  202. title="NextChat"
  203. subTitle="Build your own AI assistant."
  204. logo={<ChatGptIcon />}
  205. >
  206. <div className={styles["sidebar-header-bar"]}>
  207. <IconButton
  208. icon={<MaskIcon />}
  209. text={shouldNarrow ? undefined : Locale.Mask.Name}
  210. className={styles["sidebar-bar-button"]}
  211. onClick={() => {
  212. if (config.dontShowMaskSplashScreen !== true) {
  213. navigate(Path.NewChat, { state: { fromHome: true } });
  214. } else {
  215. navigate(Path.Masks, { state: { fromHome: true } });
  216. }
  217. }}
  218. shadow
  219. />
  220. <IconButton
  221. icon={<DiscoveryIcon />}
  222. text={shouldNarrow ? undefined : Locale.Discovery.Name}
  223. className={styles["sidebar-bar-button"]}
  224. onClick={() => setShowPluginSelector(true)}
  225. shadow
  226. />
  227. <IconButton
  228. icon={<SearchIcon />}
  229. text={shouldNarrow ? undefined : Locale.SearchChat.Name}
  230. className={styles["sidebar-bar-button"]}
  231. onClick={() =>
  232. navigate(Path.SearchChat, { state: { fromHome: true } })
  233. }
  234. shadow
  235. />
  236. </div>
  237. {showPluginSelector && (
  238. <Selector
  239. items={[
  240. {
  241. title: "👇 Please select the plugin you need to use",
  242. value: "-",
  243. disable: true,
  244. },
  245. ...PLUGINS.map((item) => {
  246. return {
  247. title: item.name,
  248. value: item.path,
  249. };
  250. }),
  251. ]}
  252. onClose={() => setShowPluginSelector(false)}
  253. onSelection={(s) => {
  254. navigate(s[0], { state: { fromHome: true } });
  255. }}
  256. />
  257. )}
  258. </SideBarHeader>
  259. <SideBarBody
  260. onClick={(e) => {
  261. if (e.target === e.currentTarget) {
  262. navigate(Path.Home);
  263. }
  264. }}
  265. >
  266. <ChatList narrow={shouldNarrow} />
  267. </SideBarBody>
  268. <SideBarTail
  269. primaryAction={
  270. <>
  271. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  272. <IconButton
  273. icon={<DeleteIcon />}
  274. onClick={async () => {
  275. if (await showConfirm(Locale.Home.DeleteChat)) {
  276. chatStore.deleteSession(chatStore.currentSessionIndex);
  277. }
  278. }}
  279. />
  280. </div>
  281. <div className={styles["sidebar-action"]}>
  282. <Link to={Path.Settings}>
  283. <IconButton
  284. aria={Locale.Settings.Title}
  285. icon={<SettingsIcon />}
  286. shadow
  287. />
  288. </Link>
  289. </div>
  290. <div className={styles["sidebar-action"]}>
  291. <a href={REPO_URL} target="_blank" rel="noopener noreferrer">
  292. <IconButton
  293. aria={Locale.Export.MessageFromChatGPT}
  294. icon={<GithubIcon />}
  295. shadow
  296. />
  297. </a>
  298. </div>
  299. </>
  300. }
  301. secondaryAction={
  302. <IconButton
  303. icon={<AddIcon />}
  304. text={shouldNarrow ? undefined : Locale.Home.NewChat}
  305. onClick={() => {
  306. if (config.dontShowMaskSplashScreen) {
  307. chatStore.newSession();
  308. navigate(Path.Chat);
  309. } else {
  310. navigate(Path.NewChat);
  311. }
  312. }}
  313. shadow
  314. />
  315. }
  316. />
  317. </SideBarContainer>
  318. );
  319. }