| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678 |
- import React, { useEffect, useRef, useMemo, useState, Fragment } from "react";
- import styles from "./home.module.scss";
- import DragIcon from "../icons/drag.svg";
- import faviconSrc from "../icons/favicon.png";
- import deepSeekSrc from "../icons/deepSeek.png";
- import { AppstoreOutlined, EditOutlined, MenuOutlined } from '@ant-design/icons';
- import { useAppConfig, useChatStore, useGlobalStore } from "../store";
- import {
- DEFAULT_SIDEBAR_WIDTH,
- MAX_SIDEBAR_WIDTH,
- MIN_SIDEBAR_WIDTH,
- NARROW_SIDEBAR_WIDTH,
- } from "../constant";
- import { useLocation, useNavigate } from "react-router-dom";
- import { isIOS, useMobileScreen } from "../utils";
- import api from "@/app/api/api";
- import { Button, Drawer, Dropdown, Empty, Form, Input, Menu, message, Modal, Rate, Tag } from "antd";
- import { downloadFile } from "../utils/index";
- import dayjs from "dayjs";
- const FormItem = Form.Item;
- export function useHotKey() {
- const chatStore = useChatStore();
- useEffect(() => {
- const onKeyDown = (e: KeyboardEvent) => {
- if (e.altKey || e.ctrlKey) {
- if (e.key === "ArrowUp") {
- chatStore.nextSession(-1);
- } else if (e.key === "ArrowDown") {
- chatStore.nextSession(1);
- }
- }
- };
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- });
- }
- export function useDragSideBar() {
- const limit = (x: number) => Math.min(MAX_SIDEBAR_WIDTH, x);
- const config = useAppConfig();
- const startX = useRef(0);
- const startDragWidth = useRef(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
- const lastUpdateTime = useRef(Date.now());
- const toggleSideBar = () => {
- config.update((config) => {
- if (config.sidebarWidth < MIN_SIDEBAR_WIDTH) {
- config.sidebarWidth = DEFAULT_SIDEBAR_WIDTH;
- } else {
- config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
- }
- });
- };
- const onDragStart = (e: MouseEvent) => {
- // Remembers the initial width each time the mouse is pressed
- startX.current = e.clientX;
- startDragWidth.current = config.sidebarWidth;
- const dragStartTime = Date.now();
- const handleDragMove = (e: MouseEvent) => {
- if (Date.now() < lastUpdateTime.current + 20) {
- return;
- }
- lastUpdateTime.current = Date.now();
- const d = e.clientX - startX.current;
- const nextWidth = limit(startDragWidth.current + d);
- config.update((config) => {
- if (nextWidth < MIN_SIDEBAR_WIDTH) {
- config.sidebarWidth = NARROW_SIDEBAR_WIDTH;
- } else {
- config.sidebarWidth = nextWidth;
- }
- });
- };
- const handleDragEnd = () => {
- // In useRef the data is non-responsive, so `config.sidebarWidth` can't get the dynamic sidebarWidth
- window.removeEventListener("pointermove", handleDragMove);
- window.removeEventListener("pointerup", handleDragEnd);
- // if user click the drag icon, should toggle the sidebar
- const shouldFireClick = Date.now() - dragStartTime < 300;
- if (shouldFireClick) {
- toggleSideBar();
- }
- };
- window.addEventListener("pointermove", handleDragMove);
- window.addEventListener("pointerup", handleDragEnd);
- };
- const isMobileScreen = useMobileScreen();
- const shouldNarrow =
- !isMobileScreen && config.sidebarWidth < MIN_SIDEBAR_WIDTH;
- useEffect(() => {
- const barWidth = shouldNarrow
- ? NARROW_SIDEBAR_WIDTH
- : limit(config.sidebarWidth ?? DEFAULT_SIDEBAR_WIDTH);
- const sideBarWidth = isMobileScreen ? "100vw" : `${barWidth}px`;
- document.documentElement.style.setProperty("--sidebar-width", sideBarWidth);
- }, [config.sidebarWidth, isMobileScreen, shouldNarrow]);
- return {
- onDragStart,
- shouldNarrow,
- };
- }
- export function SideBarContainer(props: {
- children: React.ReactNode;
- onDragStart: (e: MouseEvent) => void;
- shouldNarrow: boolean;
- className?: string;
- }) {
- const isMobileScreen = useMobileScreen();
- const isIOSMobile = useMemo(
- () => isIOS() && isMobileScreen,
- [isMobileScreen],
- );
- const { children, className, onDragStart, shouldNarrow } = props;
- return (
- <div
- className={`${styles.sidebar} ${className} ${shouldNarrow && styles["narrow-sidebar"]
- }`}
- style={{
- transition: isMobileScreen && isIOSMobile ? "none" : undefined,
- background: '#FFFFFF',
- overflowY: "auto",
- }}
- >
- {children}
- <div
- className={styles["sidebar-drag"]}
- onPointerDown={(e) => onDragStart(e as any)}
- >
- <DragIcon />
- </div>
- </div>
- );
- }
- export function SideBarHeader(props: {
- title?: string | React.ReactNode;
- subTitle?: string | React.ReactNode;
- logo?: React.ReactNode;
- children?: React.ReactNode;
- }) {
- const { title, subTitle, logo, children } = props;
- return (
- <Fragment>
- <div className={styles["sidebar-header"]} data-tauri-drag-region>
- <div className={styles["sidebar-title-container"]}>
- <div className={styles["sidebar-title"]} data-tauri-drag-region>
- {title}
- </div>
- <div className={styles["sidebar-sub-title"]}>{subTitle}</div>
- </div>
- <div className={styles["sidebar-logo"] + " no-dark"}>{logo}</div>
- </div>
- {children}
- </Fragment>
- );
- }
- export function SideBarBody(props: {
- children: React.ReactNode;
- onClick?: (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => void;
- }) {
- const { onClick, children } = props;
- return (
- <div className={styles["sidebar-body"]} onClick={onClick}>
- {children}
- </div>
- );
- }
- export function SideBarTail(props: {
- primaryAction?: React.ReactNode;
- secondaryAction?: React.ReactNode;
- }) {
- const { primaryAction, secondaryAction } = props;
- return (
- <div className={styles["sidebar-tail"]}>
- <div className={styles["sidebar-actions"]}>{primaryAction}</div>
- <div className={styles["sidebar-actions"]}>{secondaryAction}</div>
- </div>
- );
- }
- interface AppDrawerProps {
- isMobileScreen: boolean,
- selectedAppId: string,
- type: 'all' | 'collect',
- open: boolean,
- onClose: () => void,
- }
- const AppDrawer: React.FC<AppDrawerProps> = (props) => {
- const {
- isMobileScreen,
- selectedAppId,
- type,
- open,
- onClose,
- } = props;
- const navigate = useNavigate();
- const [listLoading, setListLoading] = useState(false);
- type List = {
- name: string,
- chatMode: string,
- appId: string,
- desc: string,
- createTime: string,
- typeName: string,
- isCollect: boolean,
- }[];
- const [list, setList] = useState<List>([]);
- const fetchAppList = async () => {
- setListLoading(true);
- try {
- const res = await api.get(`/deepseek/api/project/app`);
- // 确保 res.data 是数组,如果不是则设为空数组
- const data = Array.isArray(res.data) ? res.data : [];
- if (type === 'all') {
- setList(data);
- } else {
- setList(data.filter((item: any) => item.isCollect));
- }
- } catch (error) {
- console.error(error);
- // 出错时设置为空数组,避免渲染错误
- setList([]);
- } finally {
- setListLoading(false);
- }
- };
- // 收藏应用
- const collectApp = async (appId: string) => {
- try {
- await api.post('/deepseek/api/app/collect', {
- appId: appId
- });
- message.success('收藏成功');
- await fetchAppList();
- } catch (error: any) {
- message.error(error.msg);
- }
- };
- // 取消收藏应用
- const cancelCollectApp = async (appId: string) => {
- try {
- await api.delete(`/deepseek/api/app/collect/${appId}`);
- message.success('操作成功');
- await fetchAppList();
- } catch (error: any) {
- message.error(error.msg);
- }
- };
- const init = async () => {
- await fetchAppList();
- }
- useEffect(() => {
- init();
- }, [])
- return (
- <Drawer
- width={isMobileScreen ? '100%' : 400}
- title={type === 'all' ? '我的应用' : '我的收藏'}
- open={open}
- loading={listLoading}
- onClose={onClose}
- >
- {
- Array.isArray(list) && list.length > 0 ?
- list.map((item, index) => {
- return <div
- style={{
- padding: 20,
- border: '1px solid #f0f0f0',
- borderRadius: 4,
- marginBottom: 20,
- cursor: 'pointer',
- }}
- key={index}
- >
- <div style={{ display: 'flex', marginBottom: 10 }}>
- <AppstoreOutlined style={{ fontSize: 40, color: '#3875f6', marginRight: 20 }} />
- <div>
- <div style={{ fontSize: 16, fontWeight: 'bold', marginBottom: 5 }}>
- {item.name}
- </div>
- <div style={{ color: '#d4d7de' }}>
- ID:{item.appId}
- </div>
- </div>
- </div>
- <div style={{ color: '#8f949e', marginBottom: 10 }}>
- {item.desc}
- </div>
- <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10 }}>
- <div style={{ color: '#747a86' }}>
- {dayjs(item.createTime).format('YYYY-MM-DD')} 发布
- </div>
- <div>
- <Tag style={{ margin: 0 }} color="blue">
- {item.typeName}
- </Tag>
- </div>
- </div>
- <div
- style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div onClick={async () => {
- if (item.isCollect) {
- await cancelCollectApp(item.appId);
- } else {
- await collectApp(item.appId);
- }
- }}>
- {
- item.isCollect ?
- <Rate count={1} value={1} />
- :
- <Rate count={1} />
- }
- </div>
- <Button type='primary' size="small" onClick={() => {
- const search = `?showMenu=false&chatMode=${item.chatMode}&appId=${item.appId}`;
- navigate({
- pathname: '/knowledgeChat',
- search: search,
- })
- location.reload();
- }}>
- 使用
- </Button>
- </div>
- </div>
- })
- :
- <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
- }
- </Drawer>
- )
- }
- export const SideBar = (props: { className?: string }) => {
- // useHotKey();
- const { onDragStart, shouldNarrow } = useDragSideBar();
- const [showPluginSelector, setShowPluginSelector] = useState(false);
- const navigate = useNavigate();
- const location = useLocation();
- const chatStore = useChatStore();
- const globalStore = useGlobalStore();
- const [menuList, setMenuList] = useState([])
- const [modalOpen, setModalOpen] = useState(false)
- const [form] = Form.useForm();
- const getType = (): 'bigModel' | 'deepSeek' => {
- if (['/knowledgeChat', '/newChat'].includes(location.pathname)) {
- return 'bigModel';
- } else if (['/deepseekChat', '/newDeepseekChat'].includes(location.pathname)) {
- return 'deepSeek';
- } else {
- return 'bigModel';
- }
- }
- // 获取聊天列表
- const fetchChatList = async (chatMode?: 'ONLINE' | 'LOCAL') => {
- try {
- const appId = '2924812721300312064';
- const url = `/deepseek/api/dialog/list/${appId}`;
- const res = await api.get(url);
- const list = res.data.map((item: any) => {
- return {
- ...item,
- children: item.children.map((child: any) => {
- const items = [
- {
- key: '1',
- label: (
- <a onClick={() => {
- setModalOpen(true);
- form.setFieldsValue({
- dialogId: child.key,
- dialogName: child.label
- });
- }}>
- 重命名
- </a>
- ),
- },
- {
- key: '2',
- label: (
- <a onClick={async () => {
- try {
- let blob = null;
- blob = await api.post(`/deepseek/api/dialog/export/${child.key}`, {}, { responseType: 'blob' });
- const fileName = `${child.label}.xlsx`;
- downloadFile(blob, fileName);
- } catch (error) {
- console.error(error);
- }
- }}>
- 导出
- </a>
- ),
- },
- {
- key: '3',
- label: (
- <a onClick={async () => {
- try {
- await api.delete(`/deepseek/api/dialog/del/${child.key}`);
- await fetchChatList(chatMode);
- chatStore.clearSessions();
- useChatStore.setState({
- message: {
- content: '',
- role: 'assistant',
- }
- });
- } catch (error) {
- console.error(error);
- }
- }}>
- 删除
- </a>
- ),
- },
- ];
- return {
- ...child,
- label: <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
- <div style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', marginRight: 10 }}>
- {child.label}
- </div>
- <div style={{ width: 20 }}>
- <Dropdown menu={{ items }} trigger={['click']} placement="bottomRight">
- <EditOutlined onClick={(e) => e.stopPropagation()} />
- </Dropdown>
- </div>
- </div>
- }
- })
- }
- })
- setMenuList(list);
- } catch (error) {
- console.error(error)
- }
- }
- useEffect(() => {
- if (getType() === 'bigModel') {
- if (globalStore.selectedAppId) {
- fetchChatList(chatStore.chatMode);
- }
- }
- }, [globalStore.selectedAppId]);
- useEffect(() => {
- chatStore.clearSessions();
- useChatStore.setState({
- message: {
- content: '',
- role: 'assistant',
- }
- });
- }, []);
- useEffect(() => {
- fetchChatList(chatStore.chatMode);
- }, [chatStore.chatMode]);
- const isMobileScreen = useMobileScreen();
- const [drawerOpen, setDrawerOpen] = useState(false);
- const [drawerType, setDrawerType] = useState<'all' | 'collect'>('all');
- return (
- <>
- {
- globalStore.showMenu &&
- <SideBarContainer
- onDragStart={onDragStart}
- shouldNarrow={shouldNarrow}
- {...props}
- >
- {
- getType() === 'deepSeek' &&
- <div>
- <img style={{ width: '100%' }} src={deepSeekSrc.src} />
- </div>
- }
- <SideBarHeader
- title={getType() === 'bigModel' ?
- <div style={{ display: 'flex', alignItems: 'center' }}>
- {
- isMobileScreen && <div>
- <Button
- type='text'
- icon={<MenuOutlined />}
- onClick={() => {
- globalStore.setShowMenu(!globalStore.showMenu);
- }}
- />
- </div>
- }
- 问答历史
- </div>
- :
- ''
- }
- logo={getType() === 'bigModel' ? <img style={{ height: 40 }} src={faviconSrc.src} /> : ''}
- >
- <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
- <Button
- style={{ width: '48%' }}
- onClick={() => {
- navigate({ pathname: '/' });
- }}
- disabled
- >
- 回到首页
- </Button>
- <Button
- style={{ width: '48%' }}
- onClick={async () => {
- chatStore.clearSessions();
- chatStore.updateCurrentSession((value) => {
- value.appId = globalStore.selectedAppId;
- });
- globalStore.setIsChatActive(false);
- globalStore.setDocuments([]);
- if (isMobileScreen) {
- globalStore.setShowMenu(false);
- }
- navigate({ pathname: '/newDeepseekChat' });
- if (getType() === 'bigModel') {
- if (chatStore.chatMode === 'LOCAL') {
- await fetchChatList(chatStore.chatMode);
- } else {
- await fetchChatList();
- }
- } else {
- await fetchChatList();
- }
- }}
- >
- 新建对话
- </Button>
- </div>
- </SideBarHeader>
- <Menu
- style={{ border: 'none' }}
- onClick={async (info) => {
- const key = info.key;
- // @ts-ignore
- const props = info.item.props;
- const { showMenu, chatMode, appId } = props;
- if (isMobileScreen) {
- globalStore.setShowMenu(false);
- }
- let url = ``;
- url = `/deepseek/api/dialog/detail/${key}`;
- const res = await api.get(url);
- const list = res.data.map(((item: any) => {
- return {
- id: item.did,
- role: item.type,
- date: item.create_time,
- content: item.content,
- documents: item.documents ? item.documents : undefined,
- downloadUrl: item.downloadUrl || undefined,
- }
- }))
- const session = {
- appId: res.data.length ? res.data[0].appId : '',
- dialogName: res.data.length ? res.data[0].dialog_name : '',
- id: res.data.length ? res.data[0].id : '',
- messages: list,
- }
- globalStore.setIsChatActive(true);
- globalStore.setDocuments([]);
- globalStore.setCurrentSession(session);
- chatStore.clearSessions();
- chatStore.updateCurrentSession((value) => {
- value.appId = session.appId;
- value.topic = session.dialogName;
- value.id = session.id;
- value.messages = list;
- });
- navigate({ pathname: '/newDeepseekChat' });
- }}
- mode="inline"
- items={menuList}
- />
- <Modal
- title="重命名"
- open={modalOpen}
- width={300}
- maskClosable={false}
- onOk={() => {
- form.validateFields().then(async (values) => {
- setModalOpen(false);
- try {
- await api.put(`/deepseek/api/dialog/update`, {
- id: values.dialogId,
- dialogName: values.dialogName
- });
- await fetchChatList(chatStore.chatMode);
- chatStore.updateCurrentSession((value) => {
- value.topic = values.dialogName;
- });
- } catch (error) {
- console.error(error);
- }
- }).catch((error) => {
- console.error(error);
- });
- }}
- onCancel={() => {
- setModalOpen(false);
- }}
- >
- <Form form={form} layout='inline'>
- <FormItem name='dialogId' noStyle />
- <FormItem
- label='名称'
- name='dialogName'
- rules={[{ required: true, message: '名称不能为空', whitespace: true }]}
- >
- <Input
- style={{ width: 300 }}
- placeholder='请输入'
- maxLength={20}
- />
- </FormItem>
- </Form>
- </Modal>
- </SideBarContainer>
- }
- {
- drawerOpen &&
- <AppDrawer
- isMobileScreen={isMobileScreen}
- selectedAppId={globalStore.selectedAppId}
- type={drawerType}
- open={drawerOpen}
- onClose={() => {
- setDrawerOpen(false);
- }}
- />
- }
- </>
- );
- }
|