sidebar.tsx 16 KB

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