sidebar.tsx 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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 deepSeekSrc from "../icons/deepSeek.png";
  6. import { AppstoreOutlined, EditOutlined, MenuOutlined } from '@ant-design/icons';
  7. import { useAppConfig, useChatStore, useGlobalStore } from "../store";
  8. import {
  9. DEFAULT_SIDEBAR_WIDTH,
  10. MAX_SIDEBAR_WIDTH,
  11. MIN_SIDEBAR_WIDTH,
  12. NARROW_SIDEBAR_WIDTH,
  13. } from "../constant";
  14. import { useLocation, useNavigate } from "react-router-dom";
  15. import { isIOS, useMobileScreen } from "../utils";
  16. import api from "@/app/api/api";
  17. import { Button, Drawer, Dropdown, Empty, Form, Input, Menu, message, Modal, Rate, Tag } from "antd";
  18. import { downloadFile } from "../utils/index";
  19. import dayjs from "dayjs";
  20. const FormItem = Form.Item;
  21. export function useHotKey() {
  22. const chatStore = useChatStore();
  23. useEffect(() => {
  24. const onKeyDown = (e: KeyboardEvent) => {
  25. if (e.altKey || e.ctrlKey) {
  26. if (e.key === "ArrowUp") {
  27. chatStore.nextSession(-1);
  28. } else if (e.key === "ArrowDown") {
  29. chatStore.nextSession(1);
  30. }
  31. }
  32. };
  33. window.addEventListener("keydown", onKeyDown);
  34. return () => window.removeEventListener("keydown", onKeyDown);
  35. });
  36. }
  37. export function useDragSideBar() {
  38. const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
  39. const config = useAppConfig();
  40. const startX = useRef(0);
  41. const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  42. const lastUpdateTime = useRef(Date.now());
  43. const toggleSideBar = () => {
  44. config.update((config) => {
  45. if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) {
  46. config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH;
  47. } else {
  48. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  49. }
  50. });
  51. };
  52. const onDragStart = (e: MouseEvent) => {
  53. // Remembers the initial width each time the mouse is pressed
  54. startX.current = e.clientX;
  55. startDragWidth.current = config.sidebarWidth;
  56. const dragStartTime = Date.now();
  57. const handleDragMove = (e: MouseEvent) => {
  58. if (Date.now() < lastUpdateTime.current + 20) {
  59. return;
  60. }
  61. lastUpdateTime.current = Date.now();
  62. const d = e.clientX - startX.current;
  63. const nextWidth = limit(startDragWidth.current + d);
  64. config.update((config) => {
  65. if (nextWidth < MIN_SIDEBAR_WIDTH) {
  66. config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
  67. } else {
  68. config.sidebarWidth = nextWidth;
  69. }
  70. });
  71. };
  72. const handleDragEnd = () => {
  73. // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth
  74. window.removeEventListener("pointermove", handleDragMove);
  75. window.removeEventListener("pointerup", handleDragEnd);
  76. // if user click the drag icon, should toggle the sidebar
  77. const shouldFireClick = Date.now() - dragStartTime < 300;
  78. if (shouldFireClick) {
  79. toggleSideBar();
  80. }
  81. };
  82. window.addEventListener("pointermove", handleDragMove);
  83. window.addEventListener("pointerup", handleDragEnd);
  84. };
  85. const isMobileScreen = useMobileScreen();
  86. const shouldNarrow =
  87. !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;
  88. useEffect(() => {
  89. const barWidth = shouldNarrow
  90. ? NARROW_SIDEBAR_WIDTH
  91. : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
  92. const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
  93. document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
  94. }, [config.sidebarWidth, isMobileScreen, shouldNarrow]);
  95. return {
  96. onDragStart,
  97. shouldNarrow,
  98. };
  99. }
  100. export function SideBarContainer(props: {
  101. children: React.ReactNode;
  102. onDragStart: (e: MouseEvent) => void;
  103. shouldNarrow: boolean;
  104. className?: string;
  105. }) {
  106. const isMobileScreen = useMobileScreen();
  107. const isIOSMobile = useMemo(
  108. () => isIOS() && isMobileScreen,
  109. [isMobileScreen],
  110. );
  111. const { children, className, onDragStart, shouldNarrow } = props;
  112. return (
  113. <div
  114. className={`${styles.sidebar} ${className} ${shouldNarrow && styles["narrow-sidebar"]
  115. }`}
  116. style={{
  117. transition: isMobileScreen && isIOSMobile ? "none" : undefined,
  118. background: '#FFFFFF',
  119. overflowY: "auto",
  120. }}
  121. >
  122. {children}
  123. <div
  124. className={styles["sidebar-drag"]}
  125. onPointerDown={(e) => onDragStart(e as any)}
  126. >
  127. <DragIcon />
  128. </div>
  129. </div>
  130. );
  131. }
  132. export function SideBarHeader(props: {
  133. title?: string | React.ReactNode;
  134. subTitle?: string | React.ReactNode;
  135. logo?: React.ReactNode;
  136. children?: React.ReactNode;
  137. }) {
  138. const { title, subTitle, logo, children } = props;
  139. return (
  140. <Fragment>
  141. <div className={styles["sidebar-header"]} data-tauri-drag-region>
  142. <div className={styles["sidebar-title-container"]}>
  143. <div className={styles["sidebar-title"]} data-tauri-drag-region>
  144. {title}
  145. </div>
  146. <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
  147. </div>
  148. <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
  149. </div>
  150. {children}
  151. </Fragment>
  152. );
  153. }
  154. export function SideBarBody(props: {
  155. children: React.ReactNode;
  156. onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
  157. }) {
  158. const { onClick, children } = props;
  159. return (
  160. <div className={styles["sidebar-body"]} onClick={onClick}>
  161. {children}
  162. </div>
  163. );
  164. }
  165. export function SideBarTail(props: {
  166. primaryAction?: React.ReactNode;
  167. secondaryAction?: React.ReactNode;
  168. }) {
  169. const { primaryAction, secondaryAction } = props;
  170. return (
  171. <div className={styles["sidebar-tail"]}>
  172. <div className={styles["sidebar-actions"]}>{primaryAction}</div>
  173. <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
  174. </div>
  175. );
  176. }
  177. interface AppDrawerProps {
  178. isMobileScreen: boolean,
  179. selectedAppId: string,
  180. type: 'all' | 'collect',
  181. open: boolean,
  182. onClose: () => void,
  183. }
  184. const AppDrawer: React.FC<AppDrawerProps> = (props) => {
  185. const {
  186. isMobileScreen,
  187. selectedAppId,
  188. type,
  189. open,
  190. onClose,
  191. } = props;
  192. const navigate = useNavigate();
  193. const [listLoading, setListLoading] = useState(false);
  194. type List = {
  195. name: string,
  196. chatMode: string,
  197. appId: string,
  198. desc: string,
  199. createTime: string,
  200. typeName: string,
  201. isCollect: boolean,
  202. }[];
  203. const [list, setList] = useState<List>([]);
  204. const fetchAppList = async () => {
  205. setListLoading(true);
  206. try {
  207. const res = await api.get(`/deepseek/api/project/app`);
  208. // 确保 res.data 是数组,如果不是则设为空数组
  209. const data = Array.isArray(res.data) ? res.data : [];
  210. if (type === 'all') {
  211. setList(data);
  212. } else {
  213. setList(data.filter((item: any) => item.isCollect));
  214. }
  215. } catch (error) {
  216. console.error(error);
  217. // 出错时设置为空数组,避免渲染错误
  218. setList([]);
  219. } finally {
  220. setListLoading(false);
  221. }
  222. };
  223. // 收藏应用
  224. const collectApp = async (appId: string) => {
  225. try {
  226. await api.post('/deepseek/api/app/collect', {
  227. appId: appId
  228. });
  229. message.success('收藏成功');
  230. await fetchAppList();
  231. } catch (error: any) {
  232. message.error(error.msg);
  233. }
  234. };
  235. // 取消收藏应用
  236. const cancelCollectApp = async (appId: string) => {
  237. try {
  238. await api.delete(`/deepseek/api/app/collect/${appId}`);
  239. message.success('操作成功');
  240. await fetchAppList();
  241. } catch (error: any) {
  242. message.error(error.msg);
  243. }
  244. };
  245. const init = async () => {
  246. await fetchAppList();
  247. }
  248. useEffect(() => {
  249. init();
  250. }, [])
  251. return (
  252. <Drawer
  253. width={isMobileScreen ? '100%' : 400}
  254. title={type === 'all' ? '我的应用' : '我的收藏'}
  255. open={open}
  256. loading={listLoading}
  257. onClose={onClose}
  258. >
  259. {
  260. Array.isArray(list) && list.length > 0 ?
  261. list.map((item, index) => {
  262. return <div
  263. style={{
  264. padding: 20,
  265. border: '1px solid #f0f0f0',
  266. borderRadius: 4,
  267. marginBottom: 20,
  268. cursor: 'pointer',
  269. }}
  270. key={index}
  271. >
  272. <div style={{ display: 'flex', marginBottom: 10 }}>
  273. <AppstoreOutlined style={{ fontSize: 40, color: '#3875f6', marginRight: 20 }} />
  274. <div>
  275. <div style={{ fontSize: 16, fontWeight: 'bold', marginBottom: 5 }}>
  276. {item.name}
  277. </div>
  278. <div style={{ color: '#d4d7de' }}>
  279. ID:{item.appId}
  280. </div>
  281. </div>
  282. </div>
  283. <div style={{ color: '#8f949e', marginBottom: 10 }}>
  284. {item.desc}
  285. </div>
  286. <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
  287. <div style={{ color: '#747a86' }}>
  288. {dayjs(item.createTime).format('YYYY-MM-DD')} 发布
  289. </div>
  290. <div>
  291. <Tag style={{ margin: 0 }} color="blue">
  292. {item.typeName}
  293. </Tag>
  294. </div>
  295. </div>
  296. <div
  297. style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
  298. <div onClick={async () => {
  299. if (item.isCollect) {
  300. await cancelCollectApp(item.appId);
  301. } else {
  302. await collectApp(item.appId);
  303. }
  304. }}>
  305. {
  306. item.isCollect ?
  307. <Rate count={1} value={1} />
  308. :
  309. <Rate count={1} />
  310. }
  311. </div>
  312. <Button type='primary' size="small" onClick={() => {
  313. const search = `?showMenu=false&chatMode=${item.chatMode}&appId=${item.appId}`;
  314. navigate({
  315. pathname: '/knowledgeChat',
  316. search: search,
  317. })
  318. location.reload();
  319. }}>
  320. 使用
  321. </Button>
  322. </div>
  323. </div>
  324. })
  325. :
  326. <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
  327. }
  328. </Drawer>
  329. )
  330. }
  331. export const SideBar = (props: { className?: string }) => {
  332. // useHotKey();
  333. const { onDragStart, shouldNarrow } = useDragSideBar();
  334. const [showPluginSelector, setShowPluginSelector] = useState(false);
  335. const navigate = useNavigate();
  336. const location = useLocation();
  337. const chatStore = useChatStore();
  338. const globalStore = useGlobalStore();
  339. const [menuList, setMenuList] = useState([])
  340. const [modalOpen, setModalOpen] = useState(false)
  341. const [form] = Form.useForm();
  342. const getType = (): 'bigModel' | 'deepSeek' => {
  343. if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
  344. return 'bigModel';
  345. } else if (['/deepseekChat', '/newDeepseekChat'].includes(location.pathname)) {
  346. return 'deepSeek';
  347. } else {
  348. return 'bigModel';
  349. }
  350. }
  351. // 获取聊天列表
  352. const fetchChatList = async (chatMode?: 'ONLINE' | 'LOCAL') => {
  353. try {
  354. const appId = '2924812721300312064';
  355. const url = `/deepseek/api/dialog/list/${appId}`;
  356. const res = await api.get(url);
  357. const list = res.data.map((item: any) => {
  358. return {
  359. ...item,
  360. children: item.children.map((child: any) => {
  361. const items = [
  362. {
  363. key: '1',
  364. label: (
  365. <a onClick={() => {
  366. setModalOpen(true);
  367. form.setFieldsValue({
  368. dialogId: child.key,
  369. dialogName: child.label
  370. });
  371. }}>
  372. 重命名
  373. </a>
  374. ),
  375. },
  376. {
  377. key: '2',
  378. label: (
  379. <a onClick={async () => {
  380. try {
  381. let blob = null;
  382. blob = await api.post(`/deepseek/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
  383. const fileName = `${child.label}.xlsx`;
  384. downloadFile(blob, fileName);
  385. } catch (error) {
  386. console.error(error);
  387. }
  388. }}>
  389. 导出
  390. </a>
  391. ),
  392. },
  393. {
  394. key: '3',
  395. label: (
  396. <a onClick={async () => {
  397. try {
  398. await api.delete(`/deepseek/api/dialog/del/${child.key}`);
  399. await fetchChatList(chatMode);
  400. chatStore.clearSessions();
  401. useChatStore.setState({
  402. message: {
  403. content: '',
  404. role: 'assistant',
  405. }
  406. });
  407. } catch (error) {
  408. console.error(error);
  409. }
  410. }}>
  411. 删除
  412. </a>
  413. ),
  414. },
  415. ];
  416. return {
  417. ...child,
  418. label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
  419. <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
  420. {child.label}
  421. </div>
  422. <div style={{ width: 20 }}>
  423. <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
  424. <EditOutlined onClick={(e) => e.stopPropagation()} />
  425. </Dropdown>
  426. </div>
  427. </div>
  428. }
  429. })
  430. }
  431. })
  432. setMenuList(list);
  433. } catch (error) {
  434. console.error(error)
  435. }
  436. }
  437. useEffect(() => {
  438. if (getType() === 'bigModel') {
  439. if (globalStore.selectedAppId) {
  440. fetchChatList(chatStore.chatMode);
  441. }
  442. }
  443. }, [globalStore.selectedAppId]);
  444. useEffect(() => {
  445. chatStore.clearSessions();
  446. useChatStore.setState({
  447. message: {
  448. content: '',
  449. role: 'assistant',
  450. }
  451. });
  452. }, []);
  453. useEffect(() => {
  454. fetchChatList(chatStore.chatMode);
  455. }, [chatStore.chatMode]);
  456. const isMobileScreen = useMobileScreen();
  457. const [drawerOpen, setDrawerOpen] = useState(false);
  458. const [drawerType, setDrawerType] = useState<'all' | 'collect'>('all');
  459. return (
  460. <>
  461. {
  462. globalStore.showMenu &&
  463. <SideBarContainer
  464. onDragStart={onDragStart}
  465. shouldNarrow={shouldNarrow}
  466. {...props}
  467. >
  468. {
  469. getType() === 'deepSeek' &&
  470. <div>
  471. <img style={{ width: '100%' }} src={deepSeekSrc.src} />
  472. </div>
  473. }
  474. <SideBarHeader
  475. title={getType() === 'bigModel' ?
  476. <div style={{ display: 'flex', alignItems: 'center' }}>
  477. {
  478. isMobileScreen && <div>
  479. <Button
  480. type='text'
  481. icon={<MenuOutlined />}
  482. onClick={() => {
  483. globalStore.setShowMenu(!globalStore.showMenu);
  484. }}
  485. />
  486. </div>
  487. }
  488. 问答历史
  489. </div>
  490. :
  491. ''
  492. }
  493. logo={getType() === 'bigModel' ? <img style={{ height: 40 }} src={faviconSrc.src} /> : ''}
  494. >
  495. <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
  496. <Button
  497. style={{ width: '48%' }}
  498. onClick={() => {
  499. navigate({ pathname: '/' });
  500. }}
  501. disabled
  502. >
  503. 回到首页
  504. </Button>
  505. <Button
  506. style={{ width: '48%' }}
  507. onClick={async () => {
  508. chatStore.clearSessions();
  509. chatStore.updateCurrentSession((value) => {
  510. value.appId = globalStore.selectedAppId;
  511. });
  512. globalStore.setIsChatActive(false);
  513. globalStore.setDocuments([]);
  514. if (isMobileScreen) {
  515. globalStore.setShowMenu(false);
  516. }
  517. navigate({ pathname: '/newDeepseekChat' });
  518. if (getType() === 'bigModel') {
  519. if (chatStore.chatMode === 'LOCAL') {
  520. await fetchChatList(chatStore.chatMode);
  521. } else {
  522. await fetchChatList();
  523. }
  524. } else {
  525. await fetchChatList();
  526. }
  527. }}
  528. >
  529. 新建对话
  530. </Button>
  531. </div>
  532. </SideBarHeader>
  533. <Menu
  534. style={{ border: 'none' }}
  535. onClick={async (info) => {
  536. const key = info.key;
  537. // @ts-ignore
  538. const props = info.item.props;
  539. const { showMenu, chatMode, appId } = props;
  540. if (isMobileScreen) {
  541. globalStore.setShowMenu(false);
  542. }
  543. let url = ``;
  544. url = `/deepseek/api/dialog/detail/${key}`;
  545. const res = await api.get(url);
  546. const list = res.data.map(((item: any) => {
  547. return {
  548. id: item.did,
  549. role: item.type,
  550. date: item.create_time,
  551. content: item.content,
  552. documents: item.documents ? item.documents : undefined,
  553. downloadUrl: item.downloadUrl || undefined,
  554. }
  555. }))
  556. const session = {
  557. appId: res.data.length ? res.data[0].appId : '',
  558. dialogName: res.data.length ? res.data[0].dialog_name : '',
  559. id: res.data.length ? res.data[0].id : '',
  560. messages: list,
  561. }
  562. globalStore.setIsChatActive(true);
  563. globalStore.setDocuments([]);
  564. globalStore.setCurrentSession(session);
  565. chatStore.clearSessions();
  566. chatStore.updateCurrentSession((value) => {
  567. value.appId = session.appId;
  568. value.topic = session.dialogName;
  569. value.id = session.id;
  570. value.messages = list;
  571. });
  572. navigate({ pathname: '/newDeepseekChat' });
  573. }}
  574. mode="inline"
  575. items={menuList}
  576. />
  577. <Modal
  578. title="重命名"
  579. open={modalOpen}
  580. width={300}
  581. maskClosable={false}
  582. onOk={() => {
  583. form.validateFields().then(async (values) => {
  584. setModalOpen(false);
  585. try {
  586. await api.put(`/deepseek/api/dialog/update`, {
  587. id: values.dialogId,
  588. dialogName: values.dialogName
  589. });
  590. await fetchChatList(chatStore.chatMode);
  591. chatStore.updateCurrentSession((value) => {
  592. value.topic = values.dialogName;
  593. });
  594. } catch (error) {
  595. console.error(error);
  596. }
  597. }).catch((error) => {
  598. console.error(error);
  599. });
  600. }}
  601. onCancel={() => {
  602. setModalOpen(false);
  603. }}
  604. >
  605. <Form form={form} layout='inline'>
  606. <FormItem name='dialogId' noStyle />
  607. <FormItem
  608. label='名称'
  609. name='dialogName'
  610. rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
  611. >
  612. <Input
  613. style={{ width: 300 }}
  614. placeholder='请输入'
  615. maxLength={20}
  616. />
  617. </FormItem>
  618. </Form>
  619. </Modal>
  620. </SideBarContainer>
  621. }
  622. {
  623. drawerOpen &&
  624. <AppDrawer
  625. isMobileScreen={isMobileScreen}
  626. selectedAppId={globalStore.selectedAppId}
  627. type={drawerType}
  628. open={drawerOpen}
  629. onClose={() => {
  630. setDrawerOpen(false);
  631. }}
  632. />
  633. }
  634. </>
  635. );
  636. }