perf scroll components (#2676)

* perf: add scroll list && virtualist (#2665)

* perf: chatHistorySlider add virtualList

* perf: dataCard add scroll

* fix: ts

* perf: scroll list components

* perf: hook refresh

---------

Co-authored-by: papapatrick <109422393+Patrickill@users.noreply.github.com>
This commit is contained in:
Archer
2024-09-11 19:53:49 +08:00
committed by GitHub
parent 5101c7a6dc
commit 6331f4b845
17 changed files with 413 additions and 335 deletions

View File

@@ -1,13 +1,17 @@
import { useRef, useState, useCallback, useMemo, useEffect } from 'react'; import { useRef, useState, useCallback, useMemo } from 'react';
import { IconButton, Flex, Box, Input } from '@chakra-ui/react'; import { IconButton, Flex, Box, Input, BoxProps } from '@chakra-ui/react';
import { ArrowBackIcon, ArrowForwardIcon } from '@chakra-ui/icons'; import { ArrowBackIcon, ArrowForwardIcon } from '@chakra-ui/icons';
import { useMutation } from '@tanstack/react-query';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { throttle } from 'lodash';
import { useToast } from './useToast'; import { useToast } from './useToast';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
import {
const thresholdVal = 100; useBoolean,
useLockFn,
useMemoizedFn,
useRequest,
useScroll,
useThrottleEffect
} from 'ahooks';
type PagingData<T> = { type PagingData<T> = {
pageNum: number; pageNum: number;
@@ -23,7 +27,7 @@ export function usePagination<ResT = any>({
defaultRequest = true, defaultRequest = true,
type = 'button', type = 'button',
onChange, onChange,
elementRef refreshDeps
}: { }: {
api: (data: any) => Promise<PagingData<ResT>>; api: (data: any) => Promise<PagingData<ResT>>;
pageSize?: number; pageSize?: number;
@@ -31,37 +35,50 @@ export function usePagination<ResT = any>({
defaultRequest?: boolean; defaultRequest?: boolean;
type?: 'button' | 'scroll'; type?: 'button' | 'scroll';
onChange?: (pageNum: number) => void; onChange?: (pageNum: number) => void;
elementRef?: React.RefObject<HTMLDivElement>; refreshDeps?: any[];
}) { }) {
const { toast } = useToast(); const { toast } = useToast();
const { t } = useTranslation(); const { t } = useTranslation();
const [pageNum, setPageNum] = useState(1); const [pageNum, setPageNum] = useState(1);
const pageNumRef = useRef(pageNum);
pageNumRef.current = pageNum; const ScrollContainerRef = useRef<HTMLDivElement>(null);
const noMore = useRef(false);
const [isLoading, { setTrue, setFalse }] = useBoolean(false);
const [total, setTotal] = useState(0); const [total, setTotal] = useState(0);
const totalRef = useRef(total);
totalRef.current = total;
const [data, setData] = useState<ResT[]>([]); const [data, setData] = useState<ResT[]>([]);
const dataLengthRef = useRef(data.length);
dataLengthRef.current = data.length;
const maxPage = useMemo(() => Math.ceil(total / pageSize) || 1, [pageSize, total]); const maxPage = useMemo(() => Math.ceil(total / pageSize) || 1, [pageSize, total]);
const { mutate, isLoading } = useMutation({ const fetchData = useLockFn(async (num: number = pageNum) => {
mutationFn: async (num: number = pageNum) => { if (noMore.current && num !== 1) return;
setTrue();
try { try {
const res: PagingData<ResT> = await api({ const res: PagingData<ResT> = await api({
pageNum: num, pageNum: num,
pageSize, pageSize,
...params ...params
}); });
setPageNum(num);
// Check total and set
res.total !== undefined && setTotal(res.total); res.total !== undefined && setTotal(res.total);
if (res.total !== undefined && res.total <= data.length + res.data.length) {
noMore.current = true;
}
setPageNum(num);
if (type === 'scroll') { if (type === 'scroll') {
setData((prevData) => [...prevData, ...res.data]); setData((prevData) => (num === 1 ? res.data : [...prevData, ...res.data]));
} else { } else {
setData(res.data); setData(res.data);
} }
onChange && onChange(num);
onChange?.(num);
} catch (error: any) { } catch (error: any) {
toast({ toast({
title: getErrText(error, t('common:core.chat.error.data_error')), title: getErrText(error, t('common:core.chat.error.data_error')),
@@ -69,8 +86,8 @@ export function usePagination<ResT = any>({
}); });
console.log(error); console.log(error);
} }
return null;
} setFalse();
}); });
const Pagination = useCallback(() => { const Pagination = useCallback(() => {
@@ -82,7 +99,7 @@ export function usePagination<ResT = any>({
aria-label={'left'} aria-label={'left'}
size={'smSquare'} size={'smSquare'}
isLoading={isLoading} isLoading={isLoading}
onClick={() => mutate(pageNum - 1)} onClick={() => fetchData(pageNum - 1)}
/> />
<Flex mx={2} alignItems={'center'}> <Flex mx={2} alignItems={'center'}>
<Input <Input
@@ -97,11 +114,11 @@ export function usePagination<ResT = any>({
const val = +e.target.value; const val = +e.target.value;
if (val === pageNum) return; if (val === pageNum) return;
if (val >= maxPage) { if (val >= maxPage) {
mutate(maxPage); fetchData(maxPage);
} else if (val < 1) { } else if (val < 1) {
mutate(1); fetchData(1);
} else { } else {
mutate(+e.target.value); fetchData(+e.target.value);
} }
}} }}
onKeyDown={(e) => { onKeyDown={(e) => {
@@ -110,11 +127,11 @@ export function usePagination<ResT = any>({
if (val && e.key === 'Enter') { if (val && e.key === 'Enter') {
if (val === pageNum) return; if (val === pageNum) return;
if (val >= maxPage) { if (val >= maxPage) {
mutate(maxPage); fetchData(maxPage);
} else if (val < 1) { } else if (val < 1) {
mutate(1); fetchData(1);
} else { } else {
mutate(val); fetchData(val);
} }
} }
}} }}
@@ -130,22 +147,35 @@ export function usePagination<ResT = any>({
isLoading={isLoading} isLoading={isLoading}
w={'28px'} w={'28px'}
h={'28px'} h={'28px'}
onClick={() => mutate(pageNum + 1)} onClick={() => fetchData(pageNum + 1)}
/> />
</Flex> </Flex>
); );
}, [isLoading, maxPage, mutate, pageNum]); }, [isLoading, maxPage, fetchData, pageNum]);
const ScrollData = useCallback( // Reload data
({ children, ...props }: { children: React.ReactNode }) => { const { runAsync: refresh } = useRequest(
const loadText = useMemo(() => { async () => {
setData([]);
defaultRequest && fetchData(1);
},
{
manual: false,
refreshDeps,
throttleWait: 100
}
);
const ScrollData = useMemoizedFn(
({ children, ...props }: { children: React.ReactNode } & BoxProps) => {
const loadText = (() => {
if (isLoading) return t('common:common.is_requesting'); if (isLoading) return t('common:common.is_requesting');
if (total <= data.length) return t('common:common.request_end'); if (total <= data.length) return t('common:common.request_end');
return t('common:common.request_more'); return t('common:common.request_more');
}, []); })();
return ( return (
<Box {...props} ref={elementRef} overflow={'overlay'}> <Box {...props} ref={ScrollContainerRef} overflow={'overlay'}>
{children} {children}
<Box <Box
mt={2} mt={2}
@@ -155,51 +185,29 @@ export function usePagination<ResT = any>({
cursor={loadText === t('common:common.request_more') ? 'pointer' : 'default'} cursor={loadText === t('common:common.request_more') ? 'pointer' : 'default'}
onClick={() => { onClick={() => {
if (loadText !== t('common:common.request_more')) return; if (loadText !== t('common:common.request_more')) return;
mutate(pageNum + 1); fetchData(pageNum + 1);
}} }}
> >
{loadText} {loadText}
</Box> </Box>
</Box> </Box>
); );
}, }
[data.length, isLoading, mutate, pageNum, total]
); );
useEffect(() => { // Scroll check
if (!elementRef?.current || type !== 'scroll') return; const scroll = useScroll(ScrollContainerRef);
useThrottleEffect(
const scrolling = throttle((e: Event) => { () => {
const element = e.target as HTMLDivElement; if (!ScrollContainerRef?.current || type !== 'scroll' || total === 0) return;
if (!element) return; const { scrollTop, scrollHeight, clientHeight } = ScrollContainerRef.current;
// 当前滚动位置 if (scrollTop + clientHeight >= scrollHeight - 100) {
const scrollTop = element.scrollTop; fetchData(pageNum + 1);
// 可视高度
const clientHeight = element.clientHeight;
// 内容总高度
const scrollHeight = element.scrollHeight;
// 判断是否滚动到底部
if (
scrollTop + clientHeight + thresholdVal >= scrollHeight &&
dataLengthRef.current < totalRef.current
) {
mutate(pageNumRef.current + 1);
} }
}, 100); },
[scroll],
const handleScroll = (e: Event) => { { wait: 50 }
scrolling(e); );
};
elementRef.current.addEventListener('scroll', handleScroll);
return () => {
elementRef.current?.removeEventListener('scroll', handleScroll);
};
}, [elementRef, mutate, pageNum, type, total, data.length]);
useEffect(() => {
defaultRequest && mutate(1);
}, []);
return { return {
pageNum, pageNum,
@@ -210,6 +218,7 @@ export function usePagination<ResT = any>({
isLoading, isLoading,
Pagination, Pagination,
ScrollData, ScrollData,
getData: mutate getData: fetchData,
refresh
}; };
} }

View File

@@ -1,4 +1,4 @@
import React, { useRef, useState, useEffect } from 'react'; import React, { useRef, useState } from 'react';
import { Box, BoxProps } from '@chakra-ui/react'; import { Box, BoxProps } from '@chakra-ui/react';
import { useToast } from './useToast'; import { useToast } from './useToast';
import { getErrText } from '@fastgpt/global/common/error/utils'; import { getErrText } from '@fastgpt/global/common/error/utils';
@@ -9,11 +9,14 @@ import {
useMemoizedFn, useMemoizedFn,
useScroll, useScroll,
useVirtualList, useVirtualList,
useRequest useRequest,
useThrottleEffect
} from 'ahooks'; } from 'ahooks';
import MyBox from '../components/common/MyBox'; import MyBox from '../components/common/MyBox';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
type ItemHeight<T> = (index: number, data: T) => number;
export type ScrollListType = ({ export type ScrollListType = ({
children, children,
EmptyChildren, EmptyChildren,
@@ -31,8 +34,6 @@ export function useScrollPagination<
>( >(
api: (data: TParams) => Promise<TData>, api: (data: TParams) => Promise<TData>,
{ {
debounceWait,
throttleWait,
refreshDeps, refreshDeps,
itemHeight = 50, itemHeight = 50,
overscan = 10, overscan = 10,
@@ -40,11 +41,9 @@ export function useScrollPagination<
pageSize = 10, pageSize = 10,
defaultParams = {} defaultParams = {}
}: { }: {
debounceWait?: number;
throttleWait?: number;
refreshDeps?: any[]; refreshDeps?: any[];
itemHeight: number; itemHeight: number | ItemHeight<TData['list'][0]>;
overscan?: number; overscan?: number;
pageSize?: number; pageSize?: number;
@@ -123,43 +122,56 @@ export function useScrollPagination<
isLoading?: boolean; isLoading?: boolean;
} & BoxProps) => { } & BoxProps) => {
return ( return (
<>
<MyBox isLoading={isLoading} ref={containerRef} overflow={'overlay'} {...props}> <MyBox isLoading={isLoading} ref={containerRef} overflow={'overlay'} {...props}>
<Box ref={wrapperRef}>{children}</Box> <Box ref={wrapperRef}>
{children}
{noMore.current && list.length > 0 && ( {noMore.current && list.length > 0 && (
<Box py={4} textAlign={'center'} color={'myGray.600'} fontSize={'xs'}> <Box py={4} textAlign={'center'} color={'myGray.600'} fontSize={'xs'}>
{t('common:common.No more data')} {t('common:common.No more data')}
</Box> </Box>
)} )}
</Box>
{list.length === 0 && !isLoading && EmptyChildren && <>{EmptyChildren}</>} {list.length === 0 && !isLoading && EmptyChildren && <>{EmptyChildren}</>}
</MyBox> </MyBox>
</>
); );
} }
); );
useRequest(() => loadData(1), { // Reload data
refreshDeps, useRequest(
debounceWait: data.length === 0 ? 0 : debounceWait, async () => {
throttleWait console.log('reload', 11111);
}); loadData(1);
},
{
manual: false,
refreshDeps
}
);
// Check if scroll to bottom
const scroll = useScroll(containerRef); const scroll = useScroll(containerRef);
useEffect(() => { useThrottleEffect(
() => {
if (!containerRef.current || list.length === 0) return; if (!containerRef.current || list.length === 0) return;
const { scrollTop, scrollHeight, clientHeight } = containerRef.current; const { scrollTop, scrollHeight, clientHeight } = containerRef.current;
console.log('=======', 111111);
if (scrollTop + clientHeight >= scrollHeight - 100) { if (scrollTop + clientHeight >= scrollHeight - 100) {
loadData(current + 1); loadData(current + 1);
} }
}, [scroll]); },
[scroll],
{
wait: 50
}
);
return { return {
containerRef, containerRef,
list, scrollDataList: list,
total, total,
data, totalData: data,
setData, setData,
isLoading, isLoading,
ScrollList, ScrollList,

View File

@@ -198,7 +198,7 @@ const LexiconConfigModal = ({ appId, onClose }: { appId: string; onClose: () =>
}); });
const { const {
list, scrollDataList,
setData, setData,
ScrollList, ScrollList,
isLoading: isRequesting, isLoading: isRequesting,
@@ -206,7 +206,7 @@ const LexiconConfigModal = ({ appId, onClose }: { appId: string; onClose: () =>
scroll2Top scroll2Top
} = useScrollPagination(getChatInputGuideList, { } = useScrollPagination(getChatInputGuideList, {
refreshDeps: [searchKey], refreshDeps: [searchKey],
debounceWait: 300, // debounceWait: 300,
itemHeight: 48, itemHeight: 48,
overscan: 20, overscan: 20,
@@ -389,7 +389,7 @@ const LexiconConfigModal = ({ appId, onClose }: { appId: string; onClose: () =>
</Flex> </Flex>
{/* new data input */} {/* new data input */}
{newData !== undefined && ( {newData !== undefined && (
<Box mt={5} ml={list.length > 0 ? 7 : 0}> <Box mt={5} ml={scrollDataList.length > 0 ? 7 : 0}>
<MyInput <MyInput
autoFocus autoFocus
rightIcon={<MyIcon name={'save'} w={'14px'} cursor={'pointer'} />} rightIcon={<MyIcon name={'save'} w={'14px'} cursor={'pointer'} />}
@@ -412,7 +412,7 @@ const LexiconConfigModal = ({ appId, onClose }: { appId: string; onClose: () =>
fontSize={'sm'} fontSize={'sm'}
EmptyChildren={<EmptyTip text={chatT('chat_input_guide_lexicon_is_empty')} />} EmptyChildren={<EmptyTip text={chatT('chat_input_guide_lexicon_is_empty')} />}
> >
{list.map((data, index) => { {scrollDataList.map((data, index) => {
const item = data.data; const item = data.data;
const selected = selectedRows.includes(item._id); const selected = selectedRows.includes(item._id);

View File

@@ -1,18 +1,27 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { jsonRes } from '@fastgpt/service/common/response';
import { connectToDatabase } from '@/service/mongo'; import { connectToDatabase } from '@/service/mongo';
import { MongoChat } from '@fastgpt/service/core/chat/chatSchema'; import { MongoChat } from '@fastgpt/service/core/chat/chatSchema';
import type { ChatHistoryItemType } from '@fastgpt/global/core/chat/type.d';
import { ChatSourceEnum } from '@fastgpt/global/core/chat/constants'; import { ChatSourceEnum } from '@fastgpt/global/core/chat/constants';
import { GetHistoriesProps } from '@/global/core/chat/api';
import { authOutLink } from '@/service/support/permission/auth/outLink'; import { authOutLink } from '@/service/support/permission/auth/outLink';
import { authCert } from '@fastgpt/service/support/permission/auth/common'; import { authCert } from '@fastgpt/service/support/permission/auth/common';
import { authTeamSpaceToken } from '@/service/support/permission/auth/team'; import { authTeamSpaceToken } from '@/service/support/permission/auth/team';
import { NextAPI } from '@/service/middleware/entry';
import { ApiRequestProps, ApiResponseType } from '@fastgpt/service/type/next';
import { PaginationProps, PaginationResponse } from '@fastgpt/web/common/fetch/type';
import { GetHistoriesProps } from '@/global/core/chat/api';
export type getHistoriesQuery = {};
export default async function handler(req: NextApiRequest, res: NextApiResponse) { export type getHistoriesBody = PaginationProps<GetHistoriesProps>;
export type getHistoriesResponse = {};
async function handler(
req: ApiRequestProps<getHistoriesBody, getHistoriesQuery>,
res: ApiResponseType<any>
): Promise<PaginationResponse<getHistoriesResponse>> {
try { try {
await connectToDatabase(); await connectToDatabase();
const { appId, shareId, outLinkUid, teamId, teamToken } = req.body as GetHistoriesProps; const { appId, shareId, outLinkUid, teamId, teamToken, current, pageSize } =
req.body as getHistoriesBody;
const limit = shareId && outLinkUid ? 20 : 30; const limit = shareId && outLinkUid ? 20 : 30;
@@ -50,24 +59,28 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
return Promise.reject('Params are error'); return Promise.reject('Params are error');
})(); })();
const data = await MongoChat.find(match, 'chatId title top customTitle appId updateTime') const [data, total] = await Promise.all([
await MongoChat.find(match, 'chatId title top customTitle appId updateTime')
.sort({ top: -1, updateTime: -1 }) .sort({ top: -1, updateTime: -1 })
.limit(limit); .skip((current - 1) * pageSize)
.limit(pageSize),
MongoChat.countDocuments(match)
]);
jsonRes<ChatHistoryItemType[]>(res, { return {
data: data.map((item) => ({ list: data.map((item) => ({
chatId: item.chatId, chatId: item.chatId,
updateTime: item.updateTime, updateTime: item.updateTime,
appId: item.appId, appId: item.appId,
customTitle: item.customTitle, customTitle: item.customTitle,
title: item.title, title: item.title,
top: item.top top: item.top
})) })),
}); total
};
} catch (err) { } catch (err) {
jsonRes(res, { return Promise.reject(err);
code: 500,
error: err
});
} }
} }
export default NextAPI(handler);

View File

@@ -41,11 +41,11 @@ const PublishHistoriesSlider = ({
const [selectedHistoryId, setSelectedHistoryId] = useState<string>(); const [selectedHistoryId, setSelectedHistoryId] = useState<string>();
const { list, ScrollList, isLoading } = useScrollPagination(getPublishList, { const { scrollDataList, ScrollList, isLoading } = useScrollPagination(getPublishList, {
itemHeight: 49, itemHeight: 49,
overscan: 20, overscan: 20,
pageSize: 30, pageSize: 20,
defaultParams: { defaultParams: {
appId appId
} }
@@ -132,7 +132,7 @@ const PublishHistoriesSlider = ({
{appT('current_settings')} {appT('current_settings')}
</Button> </Button>
<ScrollList isLoading={showLoading} flex={'1 0 0'} px={5}> <ScrollList isLoading={showLoading} flex={'1 0 0'} px={5}>
{list.map((data, index) => { {scrollDataList.map((data, index) => {
const item = data.data; const item = data.data;
return ( return (
@@ -159,7 +159,7 @@ const PublishHistoriesSlider = ({
borderColor={'primary.600'} borderColor={'primary.600'}
borderRadius={'50%'} borderRadius={'50%'}
position={'relative'} position={'relative'}
{...(index !== list.length - 1 && { {...(index !== scrollDataList.length - 1 && {
_after: { _after: {
content: '""', content: '""',
height: '40px', height: '40px',

View File

@@ -180,7 +180,9 @@ const TeamCloud = () => {
const { loadAndGetTeamMembers } = useUserStore(); const { loadAndGetTeamMembers } = useUserStore();
const { feConfigs } = useSystemStore(); const { feConfigs } = useSystemStore();
const { list, ScrollList, isLoading, fetchData } = useScrollPagination(getWorkflowVersionList, { const { scrollDataList, ScrollList, isLoading, fetchData } = useScrollPagination(
getWorkflowVersionList,
{
itemHeight: 40, itemHeight: 40,
overscan: 20, overscan: 20,
@@ -188,7 +190,8 @@ const TeamCloud = () => {
defaultParams: { defaultParams: {
appId: appDetail._id appId: appDetail._id
} }
}); }
);
const { data: members = [] } = useRequest2(loadAndGetTeamMembers, { const { data: members = [] } = useRequest2(loadAndGetTeamMembers, {
manual: !feConfigs.isPlus manual: !feConfigs.isPlus
}); });
@@ -228,9 +231,9 @@ const TeamCloud = () => {
return ( return (
<ScrollList isLoading={isLoading || isLoadingVersion} flex={'1 0 0'} px={5}> <ScrollList isLoading={isLoading || isLoadingVersion} flex={'1 0 0'} px={5}>
{list.map((data, index) => { {scrollDataList.map((data, index) => {
const item = data.data; const item = data.data;
const firstPublishedIndex = list.findIndex((data) => data.data.isPublish); const firstPublishedIndex = scrollDataList.findIndex((data) => data.data.isPublish);
const tmb = members.find((member) => member.tmbId === item.tmbId); const tmb = members.find((member) => member.tmbId === item.tmbId);
return ( return (

View File

@@ -9,8 +9,6 @@ import MyIcon from '@fastgpt/web/components/common/Icon';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { useConfirm } from '@fastgpt/web/hooks/useConfirm'; import { useConfirm } from '@fastgpt/web/hooks/useConfirm';
import { useUserStore } from '@/web/support/user/useUserStore'; import { useUserStore } from '@/web/support/user/useUserStore';
import { AppListItemType } from '@fastgpt/global/core/app/type';
import { useI18n } from '@/web/context/I18n';
import MyMenu from '@fastgpt/web/components/common/MyMenu'; import MyMenu from '@fastgpt/web/components/common/MyMenu';
import { useContextSelector } from 'use-context-selector'; import { useContextSelector } from 'use-context-selector';
import { ChatContext } from '@/web/core/chat/context/chatContext'; import { ChatContext } from '@/web/core/chat/context/chatContext';
@@ -52,19 +50,19 @@ const ChatHistorySlider = ({
const { userInfo } = useUserStore(); const { userInfo } = useUserStore();
const { const {
histories,
onChangeChatId, onChangeChatId,
chatId: activeChatId, chatId: activeChatId,
isLoading isLoading,
ScrollList,
historyList,
histories
} = useContextSelector(ChatContext, (v) => v); } = useContextSelector(ChatContext, (v) => v);
const concatHistory = useMemo(() => { const concatHistory = useMemo(() => {
const formatHistories: HistoryItemType[] = histories.map((item) => ({ const formatHistories: HistoryItemType[] = historyList.map((data) => {
id: item.chatId, const item = data.data;
title: item.title, return { id: item.chatId, title: item.title, customTitle: item.customTitle, top: item.top };
customTitle: item.customTitle, });
top: item.top
}));
const newChat: HistoryItemType = { const newChat: HistoryItemType = {
id: activeChatId, id: activeChatId,
title: t('common:core.chat.New Chat') title: t('common:core.chat.New Chat')
@@ -72,7 +70,7 @@ const ChatHistorySlider = ({
const activeChat = histories.find((item) => item.chatId === activeChatId); const activeChat = histories.find((item) => item.chatId === activeChatId);
return !activeChat ? [newChat].concat(formatHistories) : formatHistories; return !activeChat ? [newChat].concat(formatHistories) : formatHistories;
}, [activeChatId, histories, t]); }, [activeChatId, histories, historyList, t]);
// custom title edit // custom title edit
const { onOpenModal, EditModal: EditTitleModal } = useEditTitle({ const { onOpenModal, EditModal: EditTitleModal } = useEditTitle({
@@ -175,20 +173,19 @@ const ChatHistorySlider = ({
)} )}
</Flex> </Flex>
<Box flex={'1 0 0'} h={0} px={[2, 5]} overflow={'overlay'}> <ScrollList flex={'1 0 0'} h={0} px={[2, 5]} overflow={'overlay'}>
{/* chat history */} {/* chat history */}
<> <>
{concatHistory.map((item, i) => ( {concatHistory.map((item, i) => (
<Flex <Flex
position={'relative'} position={'relative'}
key={item.id || `${i}`} key={item.id}
alignItems={'center'} alignItems={'center'}
py={2.5}
px={4} px={4}
h={'44px'}
cursor={'pointer'} cursor={'pointer'}
userSelect={'none'} userSelect={'none'}
borderRadius={'md'} borderRadius={'md'}
mb={2}
fontSize={'sm'} fontSize={'sm'}
_hover={{ _hover={{
bg: 'myGray.50', bg: 'myGray.50',
@@ -207,6 +204,9 @@ const ChatHistorySlider = ({
onChangeChatId(item.id); onChangeChatId(item.id);
} }
})} })}
{...(i !== concatHistory.length - 1 && {
mb: '8px'
})}
> >
<MyIcon <MyIcon
name={item.id === activeChatId ? 'core/chat/chatFill' : 'core/chat/chatLight'} name={item.id === activeChatId ? 'core/chat/chatFill' : 'core/chat/chatLight'}
@@ -283,7 +283,7 @@ const ChatHistorySlider = ({
</Flex> </Flex>
))} ))}
</> </>
</Box> </ScrollList>
{/* exec */} {/* exec */}
{!isPc && isUserChatPage && ( {!isPc && isUserChatPage && (

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useState } from 'react'; import React, { useCallback, useMemo, useState } from 'react';
import NextHead from '@/components/common/NextHead'; import NextHead from '@/components/common/NextHead';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { delChatRecordById, getChatHistories, getInitChatInfo } from '@/web/core/chat/api'; import { delChatRecordById, getChatHistories, getInitChatInfo } from '@/web/core/chat/api';
@@ -53,14 +53,17 @@ const Chat = ({
const { setLastChatAppId } = useChatStore(); const { setLastChatAppId } = useChatStore();
const { const {
loadHistories, setHistories: setRecordHistories,
loadHistories: loadRecordHistories,
histories: recordHistories,
onUpdateHistory, onUpdateHistory,
onClearHistories, onClearHistories,
onDelHistory, onDelHistory,
isOpenSlider, isOpenSlider,
onCloseSlider, onCloseSlider,
forbidLoadChat, forbidLoadChat,
onChangeChatId onChangeChatId,
onUpdateHistoryTitle
} = useContextSelector(ChatContext, (v) => v); } = useContextSelector(ChatContext, (v) => v);
const { const {
ChatBoxRef, ChatBoxRef,
@@ -148,8 +151,7 @@ const Chat = ({
if (completionChatId !== chatId && controller.signal.reason !== 'leave') { if (completionChatId !== chatId && controller.signal.reason !== 'leave') {
onChangeChatId(completionChatId, true); onChangeChatId(completionChatId, true);
} }
loadHistories(); onUpdateHistoryTitle({ chatId: completionChatId, newTitle });
// update chat window // update chat window
setChatData((state) => ({ setChatData((state) => ({
...state, ...state,
@@ -158,7 +160,7 @@ const Chat = ({
return { responseText, responseData, isNewChat: forbidLoadChat.current }; return { responseText, responseData, isNewChat: forbidLoadChat.current };
}, },
[appId, chatId, forbidLoadChat, loadHistories, onChangeChatId] [chatId, appId, onUpdateHistoryTitle, forbidLoadChat, onChangeChatId]
); );
return ( return (
@@ -283,14 +285,6 @@ const Render = (props: Props) => {
} }
); );
const { data: histories = [], runAsync: loadHistories } = useRequest2(
() => (appId ? getChatHistories({ appId }) : Promise.resolve([])),
{
manual: false,
refreshDeps: [appId]
}
);
// 初始化聊天框 // 初始化聊天框
useMount(async () => { useMount(async () => {
// pc: redirect to latest model chat // pc: redirect to latest model chat
@@ -324,8 +318,9 @@ const Render = (props: Props) => {
} }
}); });
const providerParams = useMemo(() => ({ appId }), [appId]);
return ( return (
<ChatContextProvider histories={histories} loadHistories={loadHistories}> <ChatContextProvider params={providerParams}>
<Chat {...props} myApps={myApps} /> <Chat {...props} myApps={myApps} />
</ChatContextProvider> </ChatContextProvider>
); );

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useRef, useState } from 'react'; import React, { useCallback, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import { Box, Flex, Drawer, DrawerOverlay, DrawerContent } from '@chakra-ui/react'; import { Box, Flex, Drawer, DrawerOverlay, DrawerContent } from '@chakra-ui/react';
import { streamFetch } from '@/web/common/api/fetch'; import { streamFetch } from '@/web/common/api/fetch';
@@ -75,6 +75,7 @@ const OutLink = ({ appName, appIntro, appAvatar }: Props) => {
const outLinkUid: string = authToken || localUId; const outLinkUid: string = authToken || localUId;
const { const {
onUpdateHistoryTitle,
loadHistories, loadHistories,
onUpdateHistory, onUpdateHistory,
onClearHistories, onClearHistories,
@@ -140,7 +141,7 @@ const OutLink = ({ appName, appIntro, appAvatar }: Props) => {
if (completionChatId !== chatId) { if (completionChatId !== chatId) {
onChangeChatId(completionChatId, true); onChangeChatId(completionChatId, true);
} }
loadHistories(); onUpdateHistoryTitle({ chatId: completionChatId, newTitle });
// update chat window // update chat window
setChatData((state) => ({ setChatData((state) => ({
@@ -168,9 +169,9 @@ const OutLink = ({ appName, appIntro, appAvatar }: Props) => {
shareId, shareId,
chatData.app.type, chatData.app.type,
outLinkUid, outLinkUid,
onUpdateHistoryTitle,
forbidLoadChat, forbidLoadChat,
onChangeChatId, onChangeChatId
loadHistories
] ]
); );
@@ -354,16 +355,12 @@ const Render = (props: Props) => {
const { localUId } = useShareChatStore(); const { localUId } = useShareChatStore();
const outLinkUid: string = authToken || localUId; const outLinkUid: string = authToken || localUId;
const { data: histories = [], runAsync: loadHistories } = useRequest2( const contextParams = useMemo(() => {
() => (shareId && outLinkUid ? getChatHistories({ shareId, outLinkUid }) : Promise.resolve([])), return { shareId, outLinkUid };
{ }, [shareId, outLinkUid]);
manual: false,
refreshDeps: [shareId, outLinkUid]
}
);
return ( return (
<ChatContextProvider histories={histories} loadHistories={loadHistories}> <ChatContextProvider params={contextParams}>
<OutLink {...props} />; <OutLink {...props} />;
</ChatContextProvider> </ChatContextProvider>
); );

View File

@@ -1,4 +1,4 @@
import React, { useCallback, useEffect, useState } from 'react'; import React, { useCallback, useEffect, useMemo, useState } from 'react';
import NextHead from '@/components/common/NextHead'; import NextHead from '@/components/common/NextHead';
import { delChatRecordById, getChatHistories, getTeamChatInfo } from '@/web/core/chat/api'; import { delChatRecordById, getChatHistories, getTeamChatInfo } from '@/web/core/chat/api';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
@@ -58,6 +58,7 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData); const [chatData, setChatData] = useState<InitChatResponse>(defaultChatData);
const { const {
onUpdateHistoryTitle,
loadHistories, loadHistories,
onUpdateHistory, onUpdateHistory,
onClearHistories, onClearHistories,
@@ -114,7 +115,7 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
if (completionChatId !== chatId) { if (completionChatId !== chatId) {
onChangeChatId(completionChatId, true); onChangeChatId(completionChatId, true);
} }
loadHistories(); onUpdateHistoryTitle({ chatId: completionChatId, newTitle });
// update chat window // update chat window
setChatData((state) => ({ setChatData((state) => ({
@@ -125,15 +126,15 @@ const Chat = ({ myApps }: { myApps: AppListItemType[] }) => {
return { responseText, responseData, isNewChat: forbidLoadChat.current }; return { responseText, responseData, isNewChat: forbidLoadChat.current };
}, },
[ [
chatData.app.type,
chatId, chatId,
customVariables, customVariables,
appId, appId,
teamId, teamId,
teamToken, teamToken,
chatData.app.type,
onUpdateHistoryTitle,
forbidLoadChat, forbidLoadChat,
onChangeChatId, onChangeChatId
loadHistories
] ]
); );
@@ -302,19 +303,6 @@ const Render = (props: Props) => {
} }
); );
const { data: histories = [], runAsync: loadHistories } = useRequest2(
async () => {
if (teamId && appId && teamToken) {
return getChatHistories({ teamId, appId, teamToken: teamToken });
}
return [];
},
{
manual: false,
refreshDeps: [appId, teamId, teamToken]
}
);
// 初始化聊天框 // 初始化聊天框
useEffect(() => { useEffect(() => {
(async () => { (async () => {
@@ -330,8 +318,12 @@ const Render = (props: Props) => {
})(); })();
}, [appId, loadMyApps, myApps, router, t, toast]); }, [appId, loadMyApps, myApps, router, t, toast]);
const contextParams = useMemo(() => {
return { teamId, appId, teamToken };
}, [teamId, appId, teamToken]);
return ( return (
<ChatContextProvider histories={histories} loadHistories={loadHistories}> <ChatContextProvider params={contextParams}>
<Chat {...props} myApps={myApps} /> <Chat {...props} myApps={myApps} />
</ChatContextProvider> </ChatContextProvider>
); );

View File

@@ -120,11 +120,9 @@ const CollectionPageContextProvider = ({ children }: { children: ReactNode }) =>
searchText, searchText,
filterTags filterTags
}, },
defaultRequest: false // defaultRequest: false,
refreshDeps: [parentId, searchText, filterTags]
}); });
useEffect(() => {
getData(1);
}, [parentId]);
const contextValue: CollectionPageContextType = { const contextValue: CollectionPageContextType = {
openWebSyncConfirm: openWebSyncConfirm(onUpdateDatasetWebsiteConfig), openWebSyncConfirm: openWebSyncConfirm(onUpdateDatasetWebsiteConfig),

View File

@@ -60,15 +60,6 @@ const Header = ({}: {}) => {
const { searchText, setSearchText, total, getData, pageNum, onOpenWebsiteModal } = const { searchText, setSearchText, total, getData, pageNum, onOpenWebsiteModal } =
useContextSelector(CollectionPageContext, (v) => v); useContextSelector(CollectionPageContext, (v) => v);
// change search
const debounceRefetch = useCallback(
debounce(() => {
getData(1);
lastSearch.current = searchText;
}, 300),
[]
);
const { data: paths = [] } = useQuery(['getDatasetCollectionPathById', parentId], () => const { data: paths = [] } = useQuery(['getDatasetCollectionPathById', parentId], () =>
getDatasetCollectionPathById(parentId) getDatasetCollectionPathById(parentId)
); );
@@ -189,17 +180,6 @@ const Header = ({}: {}) => {
} }
onChange={(e) => { onChange={(e) => {
setSearchText(e.target.value); setSearchText(e.target.value);
debounceRefetch();
}}
onBlur={() => {
if (searchText === lastSearch.current) return;
getData(1);
}}
onKeyDown={(e) => {
if (searchText === lastSearch.current) return;
if (e.key === 'Enter') {
getData(1);
}
}} }}
/> />
)} )}

View File

@@ -5,15 +5,13 @@ import MyBox from '@fastgpt/web/components/common/MyBox';
import { useContextSelector } from 'use-context-selector'; import { useContextSelector } from 'use-context-selector';
import { DatasetPageContext } from '@/web/core/dataset/context/datasetPageContext'; import { DatasetPageContext } from '@/web/core/dataset/context/datasetPageContext';
import { useTranslation } from 'next-i18next'; import { useTranslation } from 'next-i18next';
import { useCallback, useState } from 'react';
import { CollectionPageContext } from './Context'; import { CollectionPageContext } from './Context';
import { debounce, isEqual } from 'lodash'; import { isEqual } from 'lodash';
import TagManageModal from './TagManageModal'; import TagManageModal from './TagManageModal';
import { DatasetTagType } from '@fastgpt/global/core/dataset/type'; import { DatasetTagType } from '@fastgpt/global/core/dataset/type';
const HeaderTagPopOver = () => { const HeaderTagPopOver = () => {
const { t } = useTranslation(); const { t } = useTranslation();
const [checkedTags, setCheckedTags] = useState<string[]>([]);
const { const {
searchDatasetTagsResult, searchDatasetTagsResult,
@@ -29,12 +27,8 @@ const HeaderTagPopOver = () => {
CollectionPageContext, CollectionPageContext,
(v) => v (v) => v
); );
const debounceRefetch = useCallback(
debounce(() => { const checkedTags = filterTags;
getData(1);
}, 300),
[]
);
const { const {
isOpen: isTagManageModalOpen, isOpen: isTagManageModalOpen,
@@ -46,16 +40,13 @@ const HeaderTagPopOver = () => {
let currentCheckedTags = []; let currentCheckedTags = [];
if (checkedTags.includes(tag._id)) { if (checkedTags.includes(tag._id)) {
currentCheckedTags = checkedTags.filter((t) => t !== tag._id); currentCheckedTags = checkedTags.filter((t) => t !== tag._id);
setCheckedTags(currentCheckedTags);
setCheckedDatasetTag(checkedDatasetTag.filter((t) => t._id !== tag._id)); setCheckedDatasetTag(checkedDatasetTag.filter((t) => t._id !== tag._id));
} else { } else {
currentCheckedTags = [...checkedTags, tag._id]; currentCheckedTags = [...checkedTags, tag._id];
setCheckedTags([...checkedTags, tag._id]);
setCheckedDatasetTag([...checkedDatasetTag, tag]); setCheckedDatasetTag([...checkedDatasetTag, tag]);
} }
if (isEqual(currentCheckedTags, filterTags)) return; if (isEqual(currentCheckedTags, filterTags)) return;
setFilterTags(currentCheckedTags); setFilterTags(currentCheckedTags);
debounceRefetch();
}; };
return ( return (
@@ -181,9 +172,7 @@ const HeaderTagPopOver = () => {
variant={'unstyled'} variant={'unstyled'}
onClick={() => { onClick={() => {
setSearchTagKey(''); setSearchTagKey('');
setCheckedTags([]);
setFilterTags([]); setFilterTags([]);
debounceRefetch();
onClose(); onClose();
}} }}
> >
@@ -211,7 +200,7 @@ const HeaderTagPopOver = () => {
<TagManageModal <TagManageModal
onClose={() => { onClose={() => {
onCloseTagManageModal(); onCloseTagManageModal();
debounceRefetch(); getData(1);
}} }}
/> />
)} )}

View File

@@ -121,14 +121,15 @@ const TagManageModal = ({ onClose }: { onClose: () => void }) => {
// Tags list // Tags list
const { const {
list, scrollDataList: renderTags,
totalData: collectionTags,
ScrollList, ScrollList,
isLoading: isRequesting, isLoading: isRequesting,
fetchData, fetchData,
total: tagsTotal total: tagsTotal
} = useScrollPagination(getDatasetCollectionTags, { } = useScrollPagination(getDatasetCollectionTags, {
refreshDeps: [''], refreshDeps: [''],
debounceWait: 300, // debounceWait: 300,
itemHeight: 56, itemHeight: 56,
overscan: 10, overscan: 10,
@@ -142,12 +143,12 @@ const TagManageModal = ({ onClose }: { onClose: () => void }) => {
// Collections list // Collections list
const { const {
list: collectionsList, scrollDataList: collectionsList,
ScrollList: ScrollListCollections, ScrollList: ScrollListCollections,
isLoading: collectionsListLoading isLoading: collectionsListLoading
} = useScrollPagination(getScrollCollectionList, { } = useScrollPagination(getScrollCollectionList, {
refreshDeps: [searchText], refreshDeps: [searchText],
debounceWait: 300, // debounceWait: 300,
itemHeight: 37, itemHeight: 37,
overscan: 10, overscan: 10,
@@ -221,7 +222,7 @@ const TagManageModal = ({ onClose }: { onClose: () => void }) => {
ref={tagInputRef} ref={tagInputRef}
w={'200px'} w={'200px'}
onBlur={() => { onBlur={() => {
if (newTag && !list.map((item) => item.data.tag).includes(newTag)) { if (newTag && !collectionTags.map((item) => item.tag).includes(newTag)) {
onCreateCollectionTag(newTag); onCreateCollectionTag(newTag);
} }
setNewTag(undefined); setNewTag(undefined);
@@ -236,7 +237,7 @@ const TagManageModal = ({ onClose }: { onClose: () => void }) => {
fontSize={'sm'} fontSize={'sm'}
EmptyChildren={<EmptyTip text={t('dataset:dataset.no_tags')} />} EmptyChildren={<EmptyTip text={t('dataset:dataset.no_tags')} />}
> >
{list.map((listItem) => { {renderTags.map((listItem) => {
const item = listItem.data; const item = listItem.data;
const tagUsage = tagUsages?.find((tagUsage) => tagUsage.tagId === item._id); const tagUsage = tagUsages?.find((tagUsage) => tagUsage.tagId === item._id);
const collections = tagUsage?.collections || []; const collections = tagUsage?.collections || [];
@@ -292,7 +293,9 @@ const TagManageModal = ({ onClose }: { onClose: () => void }) => {
onBlur={() => { onBlur={() => {
if ( if (
currentEditTagContent && currentEditTagContent &&
!list.map((item) => item.data.tag).includes(currentEditTagContent) !collectionTags
.map((item) => item.tag)
.includes(currentEditTagContent)
) { ) {
onUpdateCollectionTag({ onUpdateCollectionTag({
tag: currentEditTagContent, tag: currentEditTagContent,

View File

@@ -29,11 +29,10 @@ import TagsPopOver from './CollectionCard/TagsPopOver';
import { useSystemStore } from '@/web/common/system/useSystemStore'; import { useSystemStore } from '@/web/common/system/useSystemStore';
import MyDivider from '@fastgpt/web/components/common/MyDivider'; import MyDivider from '@fastgpt/web/components/common/MyDivider';
import Markdown from '@/components/Markdown'; import Markdown from '@/components/Markdown';
import { DatasetDataListItemType } from '@/global/core/dataset/type';
const DataCard = () => { const DataCard = () => {
const BoxRef = useRef<HTMLDivElement>(null);
const theme = useTheme(); const theme = useTheme();
const lastSearch = useRef('');
const router = useRouter(); const router = useRouter();
const { isPc } = useSystem(); const { isPc } = useSystem();
const { collectionId = '', datasetId } = router.query as { const { collectionId = '', datasetId } = router.query as {
@@ -51,44 +50,30 @@ const DataCard = () => {
type: 'delete' type: 'delete'
}); });
const { const scrollParams = useMemo(
data: datasetDataList, () => ({
Pagination,
total,
getData,
pageNum,
pageSize,
isLoading: isRequesting
} = usePagination({
api: getDatasetDataList,
pageSize: 24,
defaultRequest: false,
params: {
collectionId, collectionId,
searchText searchText
}, }),
onChange() { [collectionId, searchText]
if (BoxRef.current) { );
BoxRef.current.scrollTop = 0; const {
} data: datasetDataList,
} ScrollData,
total,
isLoading,
refresh,
setData: setDatasetDataList
} = usePagination<DatasetDataListItemType>({
api: getDatasetDataList,
pageSize: 10,
type: 'scroll',
params: scrollParams,
refreshDeps: [searchText, collectionId]
}); });
const [editDataId, setEditDataId] = useState<string>(); const [editDataId, setEditDataId] = useState<string>();
// get first page data
useRequest2(
async () => {
getData(1);
lastSearch.current = searchText;
},
{
manual: false,
debounceWait: 300,
refreshDeps: [searchText]
}
);
// get file info // get file info
const { data: collection } = useQuery( const { data: collection } = useQuery(
['getDatasetCollectionById', collectionId], ['getDatasetCollectionById', collectionId],
@@ -106,17 +91,9 @@ const DataCard = () => {
const canWrite = useMemo(() => datasetDetail.permission.hasWritePer, [datasetDetail]); const canWrite = useMemo(() => datasetDetail.permission.hasWritePer, [datasetDetail]);
const { loading } = useRequest2(putDatasetDataById, {
onSuccess() {
getData(pageNum);
}
});
const isLoading = isRequesting || loading;
return ( return (
<MyBox isLoading={isLoading} position={'relative'} py={[1, 0]} h={'100%'}> <MyBox position={'relative'} py={[1, 0]} h={'100%'}>
<Flex ref={BoxRef} flexDirection={'column'} h={'100%'}> <Flex flexDirection={'column'} h={'100%'}>
{/* Header */} {/* Header */}
<Flex alignItems={'center'} px={6}> <Flex alignItems={'center'} px={6}>
<Flex className="textEllipsis" flex={'1 0 0'} mr={[3, 5]} alignItems={'center'}> <Flex className="textEllipsis" flex={'1 0 0'} mr={[3, 5]} alignItems={'center'}>
@@ -185,7 +162,7 @@ const DataCard = () => {
/> />
</Flex> </Flex>
{/* data */} {/* data */}
<Box flex={'1 0 0'} overflow={'auto'} px={5} pb={5}> <ScrollData flex={'1 0 0'} px={5} pb={5}>
<Flex flexDir={'column'} gap={2}> <Flex flexDir={'column'} gap={2}>
{datasetDataList.map((item, index) => ( {datasetDataList.map((item, index) => (
<Card <Card
@@ -203,7 +180,6 @@ const DataCard = () => {
boxShadow: 'lg', boxShadow: 'lg',
'& .header': { visibility: 'visible' }, '& .header': { visibility: 'visible' },
'& .footer': { visibility: 'visible' }, '& .footer': { visibility: 'visible' },
'& .forbid-switch': { display: 'flex' },
bg: index % 2 === 1 ? 'myGray.200' : 'blue.100' bg: index % 2 === 1 ? 'myGray.200' : 'blue.100'
}} }}
onClick={(e) => { onClick={(e) => {
@@ -298,13 +274,18 @@ const DataCard = () => {
icon={<MyIcon name={'common/trash'} w={'14px'} color={'myGray.600'} />} icon={<MyIcon name={'common/trash'} w={'14px'} color={'myGray.600'} />}
variant={'whiteDanger'} variant={'whiteDanger'}
size={'xsSquare'} size={'xsSquare'}
aria-label={'delete'}
onClick={(e) => { onClick={(e) => {
e.stopPropagation(); e.stopPropagation();
openConfirm(async () => { openConfirm(async () => {
try { try {
await delOneDatasetDataById(item._id); await delOneDatasetDataById(item._id);
getData(pageNum); setDatasetDataList((prev) => {
return prev.filter((data) => data._id !== item._id);
});
toast({
title: t('common:common.Delete Success'),
status: 'success'
});
} catch (error) { } catch (error) {
toast({ toast({
title: getErrText(error), title: getErrText(error),
@@ -313,19 +294,17 @@ const DataCard = () => {
} }
})(); })();
}} }}
aria-label={''}
/> />
)} )}
</Flex> </Flex>
</Card> </Card>
))} ))}
</Flex> </Flex>
{total > pageSize && ( </ScrollData>
<Flex mt={2} justifyContent={'center'}> {total === 0 && !isLoading && (
<Pagination /> <EmptyTip text={t('common:core.dataset.data.Empty Tip')}></EmptyTip>
</Flex>
)} )}
{total === 0 && <EmptyTip text={t('common:core.dataset.data.Empty Tip')}></EmptyTip>}
</Box>
</Flex> </Flex>
{editDataId !== undefined && collection && ( {editDataId !== undefined && collection && (
@@ -333,7 +312,23 @@ const DataCard = () => {
collectionId={collection._id} collectionId={collection._id}
dataId={editDataId} dataId={editDataId}
onClose={() => setEditDataId(undefined)} onClose={() => setEditDataId(undefined)}
onSuccess={() => getData(pageNum)} onSuccess={(data) => {
if (editDataId === '') {
refresh();
return;
}
setDatasetDataList((prev) => {
return prev.map((item) => {
if (item._id === editDataId) {
return {
...item,
...data
};
}
return item;
});
});
}}
/> />
)} )}
<ConfirmModal /> <ConfirmModal />

View File

@@ -20,6 +20,7 @@ import type {
import { UpdateChatFeedbackProps } from '@fastgpt/global/core/chat/api'; import { UpdateChatFeedbackProps } from '@fastgpt/global/core/chat/api';
import { AuthTeamTagTokenProps } from '@fastgpt/global/support/user/team/tag'; import { AuthTeamTagTokenProps } from '@fastgpt/global/support/user/team/tag';
import { AppListItemType } from '@fastgpt/global/core/app/type'; import { AppListItemType } from '@fastgpt/global/core/app/type';
import { PaginationProps, PaginationResponse } from '@fastgpt/web/common/fetch/type';
/** /**
* 获取初始化聊天内容 * 获取初始化聊天内容
@@ -33,8 +34,8 @@ export const getTeamChatInfo = (data: InitTeamChatProps) =>
/** /**
* get current window history(appid or shareId) * get current window history(appid or shareId)
*/ */
export const getChatHistories = (data: GetHistoriesProps) => export const getChatHistories = (data: PaginationProps<GetHistoriesProps>) =>
POST<ChatHistoryItemType[]>('/core/chat/getHistories', data); POST<PaginationResponse<ChatHistoryItemType>>('/core/chat/getHistories', data);
/** /**
* get detail responseData by dataId appId chatId * get detail responseData by dataId appId chatId
*/ */

View File

@@ -2,18 +2,23 @@ import { useRequest2 } from '@fastgpt/web/hooks/useRequest';
import { useRouter } from 'next/router'; import { useRouter } from 'next/router';
import React, { ReactNode, useCallback, useEffect, useRef } from 'react'; import React, { ReactNode, useCallback, useEffect, useRef } from 'react';
import { createContext } from 'use-context-selector'; import { createContext } from 'use-context-selector';
import { delClearChatHistories, delChatHistoryById, putChatHistory } from '../api'; import {
delClearChatHistories,
delChatHistoryById,
putChatHistory,
getChatHistories
} from '../api';
import { ChatHistoryItemType } from '@fastgpt/global/core/chat/type'; import { ChatHistoryItemType } from '@fastgpt/global/core/chat/type';
import { ClearHistoriesProps, DelHistoryProps, UpdateHistoryProps } from '@/global/core/chat/api'; import { ClearHistoriesProps, DelHistoryProps, UpdateHistoryProps } from '@/global/core/chat/api';
import { useDisclosure } from '@chakra-ui/react'; import { BoxProps, useDisclosure } from '@chakra-ui/react';
import { useChatStore } from './storeChat'; import { useChatStore } from './storeChat';
import { getNanoid } from '@fastgpt/global/common/string/tools'; import { getNanoid } from '@fastgpt/global/common/string/tools';
import { useScrollPagination } from '@fastgpt/web/hooks/useScrollPagination';
type ChatContextValueType = { type ChatContextValueType = {
histories: ChatHistoryItemType[]; params: Record<string, string | number>;
loadHistories: () => Promise<ChatHistoryItemType[]>;
}; };
type ChatContextType = ChatContextValueType & { type ChatContextType = {
chatId: string; chatId: string;
onUpdateHistory: (data: UpdateHistoryProps) => void; onUpdateHistory: (data: UpdateHistoryProps) => void;
onDelHistory: (data: DelHistoryProps) => Promise<undefined>; onDelHistory: (data: DelHistoryProps) => Promise<undefined>;
@@ -21,17 +26,45 @@ type ChatContextType = ChatContextValueType & {
isOpenSlider: boolean; isOpenSlider: boolean;
onCloseSlider: () => void; onCloseSlider: () => void;
onOpenSlider: () => void; onOpenSlider: () => void;
setHistories: React.Dispatch<React.SetStateAction<ChatHistoryItemType[]>>;
forbidLoadChat: React.MutableRefObject<boolean>; forbidLoadChat: React.MutableRefObject<boolean>;
onChangeChatId: (chatId?: string, forbid?: boolean) => void; onChangeChatId: (chatId?: string, forbid?: boolean) => void;
loadHistories: () => void;
ScrollList: ({
children,
EmptyChildren,
isLoading,
...props
}: {
children: React.ReactNode;
EmptyChildren?: React.ReactNode;
isLoading?: boolean;
} & BoxProps) => ReactNode;
onChangeAppId: (appId: string) => void; onChangeAppId: (appId: string) => void;
isLoading: boolean; isLoading: boolean;
historyList: {
index: number;
data: ChatHistoryItemType;
}[];
histories: ChatHistoryItemType[];
onUpdateHistoryTitle: ({ chatId, newTitle }: { chatId: string; newTitle: string }) => void;
}; };
export const ChatContext = createContext<ChatContextType>({ export const ChatContext = createContext<ChatContextType>({
chatId: '', chatId: '',
// forbidLoadChat: undefined, // forbidLoadChat: undefined,
historyList: [],
histories: [], histories: [],
loadHistories: function (): Promise<ChatHistoryItemType[]> { onUpdateHistoryTitle: function (): void {
throw new Error('Function not implemented.');
},
ScrollList: function (): ReactNode {
throw new Error('Function not implemented.');
},
loadHistories: function (): void {
throw new Error('Function not implemented.');
},
setHistories: function (): void {
throw new Error('Function not implemented.'); throw new Error('Function not implemented.');
}, },
onUpdateHistory: function (data: UpdateHistoryProps): void { onUpdateHistory: function (data: UpdateHistoryProps): void {
@@ -62,8 +95,7 @@ export const ChatContext = createContext<ChatContextType>({
const ChatContextProvider = ({ const ChatContextProvider = ({
children, children,
histories, params
loadHistories
}: ChatContextValueType & { children: ReactNode }) => { }: ChatContextValueType & { children: ReactNode }) => {
const router = useRouter(); const router = useRouter();
const { chatId = '' } = router.query as { chatId: string }; const { chatId = '' } = router.query as { chatId: string };
@@ -72,6 +104,21 @@ const ChatContextProvider = ({
const { isOpen: isOpenSlider, onClose: onCloseSlider, onOpen: onOpenSlider } = useDisclosure(); const { isOpen: isOpenSlider, onClose: onCloseSlider, onOpen: onOpenSlider } = useDisclosure();
const {
scrollDataList: historyList,
ScrollList,
isLoading: isPaginationLoading,
setData: setHistories,
fetchData: loadHistories,
totalData: histories
} = useScrollPagination(getChatHistories, {
overscan: 30,
pageSize: 30,
itemHeight: 52,
defaultParams: params,
refreshDeps: [params]
});
const { setLastChatId } = useChatStore(); const { setLastChatId } = useChatStore();
const onChangeChatId = useCallback( const onChangeChatId = useCallback(
(changeChatId = getNanoid(), forbid = false) => { (changeChatId = getNanoid(), forbid = false) => {
@@ -85,10 +132,13 @@ const ChatContextProvider = ({
} }
}); });
} }
onCloseSlider(); onCloseSlider();
}, },
[chatId, onCloseSlider, router, setLastChatId] [chatId, onCloseSlider, router, setLastChatId]
); );
// Refresh lastChatId
useEffect(() => { useEffect(() => {
setLastChatId(chatId); setLastChatId(chatId);
}, [chatId, setLastChatId]); }, [chatId, setLastChatId]);
@@ -108,33 +158,68 @@ const ChatContextProvider = ({
); );
const { runAsync: onUpdateHistory, loading: isUpdatingHistory } = useRequest2(putChatHistory, { const { runAsync: onUpdateHistory, loading: isUpdatingHistory } = useRequest2(putChatHistory, {
onSuccess() { onSuccess(data, params) {
loadHistories(); const { chatId, top, customTitle } = params[0];
setHistories((histories) => {
const updatedHistories = histories.map((history) => {
if (history.chatId === chatId) {
return {
...history,
customTitle: customTitle || history.customTitle,
top: top !== undefined ? top : history.top
};
}
return history;
});
return top !== undefined
? updatedHistories.sort((a, b) => (b.top ? 1 : 0) - (a.top ? 1 : 0))
: updatedHistories;
});
}, },
errorToast: undefined errorToast: undefined
}); });
const { runAsync: onDelHistory, loading: isDeletingHistory } = useRequest2(delChatHistoryById, { const { runAsync: onDelHistory, loading: isDeletingHistory } = useRequest2(delChatHistoryById, {
onSuccess() { onSuccess(data, params) {
loadHistories(); const { chatId } = params[0];
setHistories((old) => old.filter((i) => i.chatId !== chatId));
} }
}); });
const { runAsync: onClearHistories, loading: isClearingHistory } = useRequest2( const { runAsync: onClearHistories, loading: isClearingHistory } = useRequest2(
delClearChatHistories, delClearChatHistories,
{ {
onSuccess() { onSuccess() {
loadHistories(); setHistories([]);
}, },
onFinally() { onFinally() {
onChangeChatId(''); onChangeChatId('');
} }
} }
); );
const isLoading = isUpdatingHistory || isDeletingHistory || isClearingHistory;
const onUpdateHistoryTitle = useCallback(
({ chatId, newTitle }: { chatId: string; newTitle: string }) => {
// Chat history exists
if (histories.find((item) => item.chatId === chatId)) {
setHistories((state) =>
state.map((item) => (item.chatId === chatId ? { ...item, title: newTitle } : item))
);
} else {
// Chat history not exists
loadHistories();
}
},
[histories, loadHistories, setHistories]
);
const isLoading =
isUpdatingHistory || isDeletingHistory || isClearingHistory || isPaginationLoading;
const contextValue = { const contextValue = {
chatId, chatId,
histories,
loadHistories,
onUpdateHistory, onUpdateHistory,
onDelHistory, onDelHistory,
onClearHistories, onClearHistories,
@@ -144,7 +229,13 @@ const ChatContextProvider = ({
forbidLoadChat, forbidLoadChat,
onChangeChatId, onChangeChatId,
onChangeAppId, onChangeAppId,
isLoading isLoading,
historyList,
setHistories,
ScrollList,
loadHistories,
histories,
onUpdateHistoryTitle
}; };
return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>; return <ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>;
}; };