sidebar.tsx 9.8 KB

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