sidebar.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  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 faviconSrc from "../icons/favicon.png";
  14. import { EditOutlined } from '@ant-design/icons';
  15. import Locale from "../locales";
  16. import { useAppConfig, useChatStore } from "../store";
  17. import {
  18. DEFAULT_SIDEBAR_WIDTH,
  19. MAX_SIDEBAR_WIDTH,
  20. MIN_SIDEBAR_WIDTH,
  21. NARROW_SIDEBAR_WIDTH,
  22. Path,
  23. PLUGINS,
  24. REPO_URL,
  25. } from "../constant";
  26. import { Link, useNavigate } from "react-router-dom";
  27. import { isIOS, useMobileScreen } from "../utils";
  28. import dynamic from "next/dynamic";
  29. import api from "@/app/api/api";
  30. import { Button, Dropdown, Menu } from "antd";
  31. const ChatList = dynamic(async () => (await import("./chat-list")).ChatList, {
  32. loading: () => null,
  33. });
  34. export 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. export 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 SideBarContainer(props: {
  114. children: React.ReactNode;
  115. onDragStart: (e: MouseEvent) => void;
  116. shouldNarrow: boolean;
  117. className?: string;
  118. }) {
  119. const isMobileScreen = useMobileScreen();
  120. const isIOSMobile = useMemo(
  121. () => isIOS() && isMobileScreen,
  122. [isMobileScreen],
  123. );
  124. const { children, className, onDragStart, shouldNarrow } = props;
  125. return (
  126. <div
  127. className={`${styles.sidebar} ${className} ${shouldNarrow && styles["narrow-sidebar"]
  128. }`}
  129. style={{
  130. // #3016 disable transition on ios mobile screen
  131. transition: isMobileScreen && isIOSMobile ? "none" : undefined,
  132. background: '#FFFFFF'
  133. }}
  134. >
  135. {children}
  136. <div
  137. className={styles["sidebar-drag"]}
  138. onPointerDown={(e) => onDragStart(e as any)}
  139. >
  140. <DragIcon />
  141. </div>
  142. </div>
  143. );
  144. }
  145. export function SideBarHeader(props: {
  146. title?: string | React.ReactNode;
  147. subTitle?: string | React.ReactNode;
  148. logo?: React.ReactNode;
  149. children?: React.ReactNode;
  150. }) {
  151. const { title, subTitle, logo, children } = props;
  152. return (
  153. <Fragment>
  154. <div className={styles["sidebar-header"]} data-tauri-drag-region>
  155. <div className={styles["sidebar-title-container"]}>
  156. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  157. {title}
  158. </div>
  159. <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
  160. </div>
  161. <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
  162. </div>
  163. {children}
  164. </Fragment>
  165. );
  166. }
  167. export function SideBarBody(props: {
  168. children: React.ReactNode;
  169. onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  170. }) {
  171. const { onClick, children } = props;
  172. return (
  173. <div className={styles["sidebar-body"]} onClick={onClick}>
  174. {children}
  175. </div>
  176. );
  177. }
  178. export function SideBarTail(props: {
  179. primaryAction?: React.ReactNode;
  180. secondaryAction?: React.ReactNode;
  181. }) {
  182. const { primaryAction, secondaryAction } = props;
  183. return (
  184. <div className={styles["sidebar-tail"]}>
  185. <div className={styles["sidebar-actions"]}>{primaryAction}</div>
  186. <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
  187. </div>
  188. );
  189. }
  190. export function SideBar(props: { className?: string }) {
  191. useHotKey();
  192. const { onDragStart, shouldNarrow } = useDragSideBar();
  193. const [showPluginSelector, setShowPluginSelector] = useState(false);
  194. const navigate = useNavigate();
  195. const config = useAppConfig();
  196. const chatStore = useChatStore();
  197. const [menuList, setMenuList] = useState([])
  198. // 获取聊天列表
  199. const fetchChatList = async () => {
  200. try {
  201. const res = await api.get('/bigmodel/api/dialog/list');
  202. const list = res.data.map((item: any) => {
  203. return {
  204. ...item,
  205. children: item.children.map((child: any) => {
  206. const items = [
  207. {
  208. key: '1',
  209. label: '重命名',
  210. },
  211. {
  212. key: '2',
  213. label: '导出',
  214. },
  215. {
  216. key: '3',
  217. label: '删除',
  218. },
  219. ];
  220. return {
  221. ...child,
  222. label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
  223. <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
  224. {child.label}
  225. </div>
  226. <div style={{ width: 20 }}>
  227. <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
  228. <EditOutlined />
  229. </Dropdown>
  230. </div>
  231. </div>
  232. }
  233. })
  234. }
  235. })
  236. setMenuList(list);
  237. } catch (error) {
  238. console.error(error)
  239. }
  240. }
  241. useEffect(() => {
  242. fetchChatList();
  243. }, []);
  244. return (
  245. <SideBarContainer
  246. onDragStart={onDragStart}
  247. shouldNarrow={shouldNarrow}
  248. {...props}
  249. >
  250. <SideBarHeader
  251. title="问答历史"
  252. logo={<img style={{ marginTop: '10%', marginRight: '10px', height: 42 }} src={faviconSrc.src} />}
  253. >
  254. {/* <div className={styles["sidebar-header-bar"]}>
  255. <IconButton
  256. icon={<MaskIcon />}
  257. text={shouldNarrow ? undefined : Locale.Mask.Name}
  258. className={styles["sidebar-bar-button"]}
  259. onClick={() => {
  260. if (config.dontShowMaskSplashScreen !== true) {
  261. navigate(Path.NewChat, { state: { fromHome: true } });
  262. } else {
  263. navigate(Path.Masks, { state: { fromHome: true } });
  264. }
  265. }}
  266. shadow
  267. />
  268. <IconButton
  269. icon={<DiscoveryIcon />}
  270. text={shouldNarrow ? undefined : Locale.Discovery.Name}
  271. className={styles["sidebar-bar-button"]}
  272. onClick={() => setShowPluginSelector(true)}
  273. shadow
  274. />
  275. </div> */}
  276. <Button
  277. type="primary"
  278. style={{ marginBottom: 20 }}
  279. onClick={() => {
  280. chatStore.newSession();
  281. navigate(Path.Chat);
  282. }}
  283. >
  284. 新建对话
  285. </Button>
  286. {/* {showPluginSelector && (
  287. <Selector
  288. items={[
  289. {
  290. title: "👇 Please select the plugin you need to use",
  291. value: "-",
  292. disable: true,
  293. },
  294. ...PLUGINS.map((item) => {
  295. return {
  296. title: item.name,
  297. value: item.path,
  298. };
  299. }),
  300. ]}
  301. onClose={() => setShowPluginSelector(false)}
  302. onSelection={(s) => {
  303. navigate(s[0], { state: { fromHome: true } });
  304. }}
  305. />
  306. )} */}
  307. </SideBarHeader>
  308. {/* <SideBarBody
  309. onClick={(e) => {
  310. if (e.target === e.currentTarget) {
  311. navigate(Path.Home);
  312. }
  313. }}
  314. >
  315. <ChatList narrow={shouldNarrow} />
  316. </SideBarBody> */}
  317. {/* <SideBarTail
  318. primaryAction={
  319. <>
  320. <div className={styles["sidebar-action"] + " " + styles.mobile}>
  321. <IconButton
  322. icon={<DeleteIcon />}
  323. onClick={async () => {
  324. if (await showConfirm(Locale.Home.DeleteChat)) {
  325. chatStore.deleteSession(chatStore.currentSessionIndex);
  326. }
  327. }}
  328. />
  329. </div>
  330. <div className={styles["sidebar-action"]}>
  331. <Link to={Path.Settings}>
  332. <IconButton
  333. aria={Locale.Settings.Title}
  334. icon={<SettingsIcon />}
  335. shadow
  336. />
  337. </Link>
  338. </div>
  339. <div className={styles["sidebar-action"]}>
  340. <a href={REPO_URL} target="_blank" rel="noopener noreferrer">
  341. <IconButton
  342. aria={Locale.Export.MessageFromChatGPT}
  343. icon={<GithubIcon />}
  344. shadow
  345. />
  346. </a>
  347. </div>
  348. </>
  349. }
  350. secondaryAction={
  351. <IconButton
  352. icon={<AddIcon />}
  353. text={shouldNarrow ? undefined : Locale.Home.NewChat}
  354. onClick={() => {
  355. if (config.dontShowMaskSplashScreen) {
  356. chatStore.newSession();
  357. navigate(Path.Chat);
  358. } else {
  359. navigate(Path.NewChat);
  360. }
  361. }}
  362. shadow
  363. />
  364. }
  365. /> */}
  366. <Menu
  367. style={{ border: 'none' }}
  368. // onClick={onClick}
  369. mode="inline"
  370. items={menuList}
  371. />
  372. </SideBarContainer>
  373. );
  374. }