sidebar.tsx 9.8 KB

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