sidebar.tsx 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  1. import React, { useEffect, useRef, useMemo, useState } 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 PluginIcon from "../icons/plugin.svg";
  12. import DragIcon from "../icons/drag.svg";
  13. import Locale from "../locales";
  14. import { ModelType, 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, useLocation, useNavigate } from "react-router-dom";
  25. import { isIOS, useMobileScreen } from "../utils";
  26. import dynamic from "next/dynamic";
  27. import { Selector, showConfirm, showToast } from "./ui-lib";
  28. const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
  29. loading: () => null,
  30. });
  31. const SdPanel = dynamic(async () => (await import("./sd-panel")).SdPanel, {
  32. loading: () => null,
  33. });
  34. 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. 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 SideBar(props: { className?: string }) {
  114. const chatStore = useChatStore();
  115. // drag side bar
  116. const { onDragStart, shouldNarrow } = useDragSideBar();
  117. const navigate = useNavigate();
  118. const config = useAppConfig();
  119. const isMobileScreen = useMobileScreen();
  120. const isIOSMobile = useMemo(
  121. () => isIOS() && isMobileScreen,
  122. [isMobileScreen],
  123. );
  124. const [showPluginSelector, setShowPluginSelector] = useState(false);
  125. const location = useLocation();
  126. useHotKey();
  127. let bodyComponent: React.JSX.Element;
  128. let isChat: boolean = false;
  129. switch (location.pathname) {
  130. case Path.Sd:
  131. case Path.SdPanel:
  132. bodyComponent = <SdPanel />;
  133. break;
  134. default:
  135. isChat = true;
  136. bodyComponent = <ChatList narrow={shouldNarrow} />;
  137. }
  138. // @ts-ignore
  139. return (
  140. <div
  141. className={`${styles.sidebar} ${props.className} ${
  142. shouldNarrow && styles["narrow-sidebar"]
  143. }`}
  144. style={{
  145. // #3016 disable transition on ios mobile screen
  146. transition: isMobileScreen && isIOSMobile ? "none" : undefined,
  147. }}
  148. >
  149. <div className={styles["sidebar-header"]} data-tauri-drag-region>
  150. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  151. NextChat
  152. </div>
  153. <div className={styles["sidebar-sub-title"]}>
  154. Build your own AI assistant.
  155. </div>
  156. <div className={styles["sidebar-logo"] + " no-dark"}>
  157. <ChatGptIcon />
  158. </div>
  159. </div>
  160. <div className={styles["sidebar-header-bar"]}>
  161. <IconButton
  162. icon={<MaskIcon />}
  163. text={shouldNarrow ? undefined : Locale.Mask.Name}
  164. className={styles["sidebar-bar-button"]}
  165. onClick={() => {
  166. if (config.dontShowMaskSplashScreen !== true) {
  167. navigate(Path.NewChat, { state: { fromHome: true } });
  168. } else {
  169. navigate(Path.Masks, { state: { fromHome: true } });
  170. }
  171. }}
  172. shadow
  173. />
  174. <IconButton
  175. icon={<PluginIcon />}
  176. text={shouldNarrow ? undefined : Locale.Plugin.Name}
  177. className={styles["sidebar-bar-button"]}
  178. onClick={() => setShowPluginSelector(true)}
  179. shadow
  180. />
  181. </div>
  182. <div
  183. className={styles["sidebar-body"]}
  184. onClick={(e) => {
  185. if (isChat && e.target === e.currentTarget) {
  186. navigate(Path.Home);
  187. }
  188. }}
  189. >
  190. {bodyComponent}
  191. </div>
  192. <div className={styles["sidebar-tail"]}>
  193. <div className={styles["sidebar-actions"]}>
  194. {isChat && (
  195. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  196. <IconButton
  197. icon={<DeleteIcon />}
  198. onClick={async () => {
  199. if (await showConfirm(Locale.Home.DeleteChat)) {
  200. chatStore.deleteSession(chatStore.currentSessionIndex);
  201. }
  202. }}
  203. />
  204. </div>
  205. )}
  206. <div className={styles["sidebar-action"]}>
  207. <Link to={Path.Settings}>
  208. <IconButton icon={<SettingsIcon />} shadow />
  209. </Link>
  210. </div>
  211. <div className={styles["sidebar-action"]}>
  212. <a href={REPO_URL} target="_blank" rel="noopener noreferrer">
  213. <IconButton icon={<GithubIcon />} shadow />
  214. </a>
  215. </div>
  216. </div>
  217. {isChat && (
  218. <div>
  219. <IconButton
  220. icon={<AddIcon />}
  221. text={shouldNarrow ? undefined : Locale.Home.NewChat}
  222. onClick={() => {
  223. if (config.dontShowMaskSplashScreen) {
  224. chatStore.newSession();
  225. navigate(Path.Chat);
  226. } else {
  227. navigate(Path.NewChat);
  228. }
  229. }}
  230. shadow
  231. />
  232. </div>
  233. )}
  234. </div>
  235. <div
  236. className={styles["sidebar-drag"]}
  237. onPointerDown={(e) => onDragStart(e as any)}
  238. >
  239. <DragIcon />
  240. </div>
  241. {showPluginSelector && (
  242. <Selector
  243. items={[
  244. {
  245. title: "👇 Please select the plugin you need to use",
  246. value: "-",
  247. disable: true,
  248. },
  249. ...PLUGINS.map((item) => {
  250. return {
  251. title: item.name,
  252. value: item.path,
  253. };
  254. }),
  255. ]}
  256. onClose={() => setShowPluginSelector(false)}
  257. onSelection={(s) => {
  258. navigate(s[0], { state: { fromHome: true } });
  259. }}
  260. />
  261. )}
  262. </div>
  263. );
  264. }