sidebar.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. import React, { useEffect, useRef, useMemo, useState, Fragment } from "react";
  2. import styles from "./home.module.scss";
  3. import DragIcon from "../icons/drag.svg";
  4. import faviconSrc from "../icons/favicon.png";
  5. import { EditOutlined } from '@ant-design/icons';
  6. import { useAppConfig, useChatStore, useGlobalStore } from "../store";
  7. import {
  8. DEFAULT_SIDEBAR_WIDTH,
  9. MAX_SIDEBAR_WIDTH,
  10. MIN_SIDEBAR_WIDTH,
  11. NARROW_SIDEBAR_WIDTH,
  12. } from "../constant";
  13. import { useLocation, useNavigate } from "react-router-dom";
  14. import { isIOS, useMobileScreen } from "../utils";
  15. import api from "@/app/api/api";
  16. import { Button, Dropdown, Form, Input, Menu, Modal } from "antd";
  17. import { downloadFile } from "../utils/index";
  18. const FormItem = Form.Item;
  19. export function useHotKey() {
  20. const chatStore = useChatStore();
  21. useEffect(() => {
  22. const onKeyDown = (e: KeyboardEvent) => {
  23. if (e.altKey || e.ctrlKey) {
  24. if (e.key === "ArrowUp") {
  25. chatStore.nextSession(-1);
  26. } else if (e.key === "ArrowDown") {
  27. chatStore.nextSession(1);
  28. }
  29. }
  30. };
  31. window.addEventListener("keydown", onKeyDown);
  32. return () => window.removeEventListener("keydown", onKeyDown);
  33. });
  34. }
  35. export function useDragSideBar() {
  36. const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
  37. const config = useAppConfig();
  38. const startX = useRef(0);
  39. const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  40. const lastUpdateTime = useRef(Date.now());
  41. const toggleSideBar = () => {
  42. config.update((config) => {
  43. if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) {
  44. config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH;
  45. } else {
  46. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  47. }
  48. });
  49. };
  50. const onDragStart = (e: MouseEvent) => {
  51. // Remembers the initial width each time the mouse is pressed
  52. startX.current = e.clientX;
  53. startDragWidth.current = config.sidebarWidth;
  54. const dragStartTime = Date.now();
  55. const handleDragMove = (e: MouseEvent) => {
  56. if (Date.now() < lastUpdateTime.current + 20) {
  57. return;
  58. }
  59. lastUpdateTime.current = Date.now();
  60. const d = e.clientX - startX.current;
  61. const nextWidth = limit(startDragWidth.current + d);
  62. config.update((config) => {
  63. if (nextWidth < MIN_SIDEBAR_WIDTH) {
  64. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  65. } else {
  66. config.sidebarWidth = nextWidth;
  67. }
  68. });
  69. };
  70. const handleDragEnd = () => {
  71. // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth
  72. window.removeEventListener("pointermove", handleDragMove);
  73. window.removeEventListener("pointerup", handleDragEnd);
  74. // if user click the drag icon, should toggle the sidebar
  75. const shouldFireClick = Date.now() - dragStartTime < 300;
  76. if (shouldFireClick) {
  77. toggleSideBar();
  78. }
  79. };
  80. window.addEventListener("pointermove", handleDragMove);
  81. window.addEventListener("pointerup", handleDragEnd);
  82. };
  83. const isMobileScreen = useMobileScreen();
  84. const shouldNarrow =
  85. !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;
  86. useEffect(() => {
  87. const barWidth = shouldNarrow
  88. ? NARROW_SIDEBAR_WIDTH
  89. : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  90. const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
  91. document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
  92. }, [config.sidebarWidth, isMobileScreen, shouldNarrow]);
  93. return {
  94. onDragStart,
  95. shouldNarrow,
  96. };
  97. }
  98. export function SideBarContainer(props: {
  99. children: React.ReactNode;
  100. onDragStart: (e: MouseEvent) => void;
  101. shouldNarrow: boolean;
  102. className?: string;
  103. }) {
  104. const isMobileScreen = useMobileScreen();
  105. const isIOSMobile = useMemo(
  106. () => isIOS() && isMobileScreen,
  107. [isMobileScreen],
  108. );
  109. const { children, className, onDragStart, shouldNarrow } = props;
  110. return (
  111. <div
  112. className={`${styles.sidebar} ${className} ${shouldNarrow && styles["narrow-sidebar"]
  113. }`}
  114. style={{
  115. transition: isMobileScreen && isIOSMobile ? "none" : undefined,
  116. background: '#FFFFFF',
  117. overflowY: "auto",
  118. }}
  119. >
  120. {children}
  121. <div
  122. className={styles["sidebar-drag"]}
  123. onPointerDown={(e) => onDragStart(e as any)}
  124. >
  125. <DragIcon />
  126. </div>
  127. </div>
  128. );
  129. }
  130. export function SideBarHeader(props: {
  131. title?: string | React.ReactNode;
  132. subTitle?: string | React.ReactNode;
  133. logo?: React.ReactNode;
  134. children?: React.ReactNode;
  135. }) {
  136. const { title, subTitle, logo, children } = props;
  137. return (
  138. <Fragment>
  139. <div className={styles["sidebar-header"]} data-tauri-drag-region>
  140. <div className={styles["sidebar-title-container"]}>
  141. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  142. {title}
  143. </div>
  144. <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
  145. </div>
  146. <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
  147. </div>
  148. {children}
  149. </Fragment>
  150. );
  151. }
  152. export function SideBarBody(props: {
  153. children: React.ReactNode;
  154. onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  155. }) {
  156. const { onClick, children } = props;
  157. return (
  158. <div className={styles["sidebar-body"]} onClick={onClick}>
  159. {children}
  160. </div>
  161. );
  162. }
  163. export function SideBarTail(props: {
  164. primaryAction?: React.ReactNode;
  165. secondaryAction?: React.ReactNode;
  166. }) {
  167. const { primaryAction, secondaryAction } = props;
  168. return (
  169. <div className={styles["sidebar-tail"]}>
  170. <div className={styles["sidebar-actions"]}>{primaryAction}</div>
  171. <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
  172. </div>
  173. );
  174. }
  175. export const SideBar = (props: { className?: string }) => {
  176. // useHotKey();
  177. const { onDragStart, shouldNarrow } = useDragSideBar();
  178. const [showPluginSelector, setShowPluginSelector] = useState(false);
  179. const navigate = useNavigate();
  180. const location = useLocation();
  181. const chatStore = useChatStore();
  182. const globalStore = useGlobalStore();
  183. const [menuList, setMenuList] = useState([])
  184. const [modalOpen, setModalOpen] = useState(false)
  185. const [form] = Form.useForm();
  186. // 获取聊天列表
  187. const fetchChatList = async () => {
  188. try {
  189. let appId = '';
  190. if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
  191. appId = globalStore.selectedAppId;
  192. } else if (['/deepseekChat', '/newDeepseekChat'].includes(location.pathname)) {
  193. appId = '1881269958412521255';
  194. }
  195. const res = await api.get(`/bigmodel/api/dialog/list/${appId}`);
  196. const list = res.data.map((item: any) => {
  197. return {
  198. ...item,
  199. children: item.children.map((child: any) => {
  200. const items = [
  201. {
  202. key: '1',
  203. label: (
  204. <a onClick={() => {
  205. setModalOpen(true);
  206. form.setFieldsValue({
  207. dialogId: child.key,
  208. dialogName: child.label
  209. });
  210. }}>
  211. 重命名
  212. </a>
  213. ),
  214. },
  215. {
  216. key: '2',
  217. label: (
  218. <a onClick={async () => {
  219. try {
  220. const blob = await api.post(`/bigmodel/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
  221. const fileName = `${child.label}.xlsx`;
  222. downloadFile(blob, fileName);
  223. } catch (error) {
  224. console.error(error);
  225. }
  226. }}>
  227. 导出
  228. </a>
  229. ),
  230. },
  231. {
  232. key: '3',
  233. label: (
  234. <a onClick={async () => {
  235. try {
  236. await api.delete(`/bigmodel/api/dialog/del/${child.key}`);
  237. await fetchChatList()
  238. // 删除不需要清理消息
  239. // chatStore.clearSessions();
  240. // chatStore.updateCurrentSession((value) => {
  241. // value.appId = globalStore.selectedAppId;
  242. // });
  243. } catch (error) {
  244. console.error(error);
  245. }
  246. }}>
  247. 删除
  248. </a>
  249. ),
  250. },
  251. ];
  252. return {
  253. ...child,
  254. label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
  255. <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
  256. {child.label}
  257. </div>
  258. <div style={{ width: 20 }}>
  259. <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
  260. <EditOutlined onClick={(e) => e.stopPropagation()} />
  261. </Dropdown>
  262. </div>
  263. </div>
  264. }
  265. })
  266. }
  267. })
  268. setMenuList(list);
  269. } catch (error) {
  270. console.error(error)
  271. }
  272. }
  273. useEffect(() => {
  274. fetchChatList();
  275. }, [globalStore.selectedAppId]);
  276. useEffect(() => {
  277. chatStore.clearSessions();
  278. }, []);
  279. return (
  280. <SideBarContainer
  281. onDragStart={onDragStart}
  282. shouldNarrow={shouldNarrow}
  283. {...props}
  284. >
  285. <SideBarHeader
  286. title="问答历史"
  287. logo={<img style={{ height: 40, cursor: 'pointer' }} src={faviconSrc.src} />}
  288. >
  289. <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
  290. <Button
  291. style={{ width: '48%' }}
  292. onClick={() => {
  293. navigate({ pathname: '/' });
  294. }}
  295. >
  296. 回到首页
  297. </Button>
  298. <Button
  299. style={{ width: '48%' }}
  300. type="primary"
  301. onClick={async () => {
  302. chatStore.clearSessions();
  303. chatStore.updateCurrentSession((value) => {
  304. value.appId = globalStore.selectedAppId;
  305. });
  306. if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
  307. navigate({ pathname: '/newChat' });
  308. } else if (['/deepseekChat', '/newDeepseekChat'].includes(location.pathname)) {
  309. navigate({ pathname: '/newDeepseekChat' });
  310. }
  311. await fetchChatList()
  312. }}
  313. >
  314. 新建对话
  315. </Button>
  316. </div>
  317. </SideBarHeader>
  318. <Menu
  319. style={{ border: 'none' }}
  320. onClick={async ({ key }) => {
  321. const res = await api.get(`/bigmodel/api/dialog/detail/${key}`);
  322. const list = res.data.map(((item: any) => {
  323. return {
  324. content: item.content,
  325. date: item.create_time,
  326. id: item.did,
  327. role: item.type,
  328. }
  329. }))
  330. const session = {
  331. appId: res.data.length ? res.data[0].appId : '',
  332. dialogName: res.data.length ? res.data[0].dialog_name : '',
  333. id: res.data.length ? res.data[0].id : '',
  334. messages: list,
  335. }
  336. globalStore.setCurrentSession(session);
  337. chatStore.clearSessions();
  338. chatStore.updateCurrentSession((value) => {
  339. value.appId = session.appId;
  340. value.topic = session.dialogName;
  341. value.id = session.id;
  342. value.messages = list;
  343. });
  344. if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
  345. navigate({ pathname: '/newChat' });
  346. } else if (['/deepseekChat', '/newDeepseekChat'].includes(location.pathname)) {
  347. navigate({ pathname: '/newDeepseekChat' });
  348. }
  349. }}
  350. mode="inline"
  351. items={menuList}
  352. />
  353. <Modal
  354. title="重命名"
  355. open={modalOpen}
  356. width={300}
  357. maskClosable={false}
  358. onOk={() => {
  359. form.validateFields().then(async (values) => {
  360. setModalOpen(false);
  361. try {
  362. await api.put('/bigmodel/api/dialog/update', {
  363. id: values.dialogId,
  364. dialogName: values.dialogName
  365. });
  366. await fetchChatList()
  367. chatStore.updateCurrentSession((value) => {
  368. value.topic = values.dialogName;
  369. });
  370. } catch (error) {
  371. console.error(error);
  372. }
  373. }).catch((error) => {
  374. console.error(error);
  375. });
  376. }}
  377. onCancel={() => {
  378. setModalOpen(false);
  379. }}
  380. >
  381. <Form form={form} layout='inline'>
  382. <FormItem name='dialogId' noStyle />
  383. <FormItem
  384. label='名称'
  385. name='dialogName'
  386. rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
  387. >
  388. <Input
  389. style={{ width: 300 }}
  390. placeholder='请输入'
  391. maxLength={20}
  392. />
  393. </FormItem>
  394. </Form>
  395. </Modal>
  396. </SideBarContainer>
  397. );
  398. }