sidebar.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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 { 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 config = useAppConfig();
  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. const res = await api.get(`/bigmodel/api/dialog/list/${globalStore.selectedAppId}`);
  190. const list = res.data.map((item: any) => {
  191. return {
  192. ...item,
  193. children: item.children.map((child: any) => {
  194. const items = [
  195. {
  196. key: '1',
  197. label: (
  198. <a onClick={() => {
  199. setModalOpen(true);
  200. form.setFieldsValue({
  201. dialogId: child.key,
  202. dialogName: child.label
  203. });
  204. }}>
  205. 重命名
  206. </a>
  207. ),
  208. },
  209. {
  210. key: '2',
  211. label: (
  212. <a onClick={async () => {
  213. try {
  214. const blob = await api.post(`/bigmodel/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
  215. const fileName = `${child.label}.xlsx`;
  216. downloadFile(blob, fileName);
  217. } catch (error) {
  218. console.error(error);
  219. }
  220. }}>
  221. 导出
  222. </a>
  223. ),
  224. },
  225. {
  226. key: '3',
  227. label: (
  228. <a onClick={async () => {
  229. try {
  230. await api.delete(`/bigmodel/api/dialog/del/${child.key}`);
  231. await fetchChatList()
  232. // 删除不需要清理消息
  233. // chatStore.clearSessions();
  234. // chatStore.updateCurrentSession((value) => {
  235. // value.appId = globalStore.selectedAppId;
  236. // });
  237. } catch (error) {
  238. console.error(error);
  239. }
  240. }}>
  241. 删除
  242. </a>
  243. ),
  244. },
  245. ];
  246. return {
  247. ...child,
  248. label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
  249. <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
  250. {child.label}
  251. </div>
  252. <div style={{ width: 20 }}>
  253. <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
  254. <EditOutlined onClick={(e) => e.stopPropagation()} />
  255. </Dropdown>
  256. </div>
  257. </div>
  258. }
  259. })
  260. }
  261. })
  262. setMenuList(list);
  263. } catch (error) {
  264. console.error(error)
  265. }
  266. }
  267. useEffect(() => {
  268. fetchChatList();
  269. }, [globalStore.selectedAppId]);
  270. useEffect(() => {
  271. chatStore.clearSessions();
  272. }, []);
  273. return (
  274. <SideBarContainer
  275. onDragStart={onDragStart}
  276. shouldNarrow={shouldNarrow}
  277. {...props}
  278. >
  279. <SideBarHeader
  280. title="问答历史"
  281. logo={<img style={{ height: 40 }} src={faviconSrc.src} />}
  282. >
  283. <Button
  284. type="primary"
  285. style={{ marginBottom: 10 }}
  286. onClick={async () => {
  287. chatStore.clearSessions();
  288. chatStore.updateCurrentSession((value) => {
  289. value.appId = globalStore.selectedAppId;
  290. });
  291. navigate({ pathname: '/newChat' });
  292. await fetchChatList()
  293. }}
  294. >
  295. 新建对话
  296. </Button>
  297. </SideBarHeader>
  298. <Menu
  299. style={{ border: 'none' }}
  300. onClick={async ({ key }) => {
  301. const res = await api.get(`/bigmodel/api/dialog/detail/${key}`);
  302. const list = res.data.map(((item: any) => {
  303. return {
  304. content: item.content,
  305. date: item.create_time,
  306. id: item.did,
  307. role: item.type,
  308. }
  309. }))
  310. const session = {
  311. appId: res.data.length ? res.data[0].appId : '',
  312. dialogName: res.data.length ? res.data[0].dialog_name : '',
  313. id: res.data.length ? res.data[0].id : '',
  314. messages: list,
  315. }
  316. globalStore.setCurrentSession(session);
  317. chatStore.clearSessions();
  318. chatStore.updateCurrentSession((value) => {
  319. value.appId = session.appId;
  320. value.topic = session.dialogName;
  321. value.id = session.id;
  322. value.messages = list;
  323. });
  324. navigate({ pathname: '/newChat' }, { state: { fromHome: true } });
  325. }}
  326. mode="inline"
  327. items={menuList}
  328. />
  329. <Modal
  330. title="重命名"
  331. open={modalOpen}
  332. width={300}
  333. maskClosable={false}
  334. onOk={() => {
  335. form.validateFields().then(async (values) => {
  336. setModalOpen(false);
  337. try {
  338. await api.put('/bigmodel/api/dialog/update', {
  339. id: values.dialogId,
  340. dialogName: values.dialogName
  341. });
  342. await fetchChatList()
  343. chatStore.updateCurrentSession((value) => {
  344. value.topic = values.dialogName;
  345. });
  346. } catch (error) {
  347. console.error(error);
  348. }
  349. }).catch((error) => {
  350. console.error(error);
  351. });
  352. }}
  353. onCancel={() => {
  354. setModalOpen(false);
  355. }}
  356. >
  357. <Form form={form} layout='inline'>
  358. <FormItem name='dialogId' noStyle />
  359. <FormItem
  360. label='名称'
  361. name='dialogName'
  362. rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
  363. >
  364. <Input
  365. style={{ width: 300 }}
  366. placeholder='请输入'
  367. maxLength={20}
  368. />
  369. </FormItem>
  370. </Form>
  371. </Modal>
  372. </SideBarContainer>
  373. );
  374. }