File size: 24,958 Bytes
058cd84 8e222fd 7c07000 b916b29 7c07000 b916b29 7c07000 b916b29 7c07000 7ba250b b916b29 7c07000 7ba250b cb33b9e 6a6f6eb cb33b9e ae21b62 8e222fd 7ba250b b916b29 058cd84 7043f18 058cd84 4086c42 058cd84 aa396c5 6a6f6eb 8c4ec99 f30b544 058cd84 f30b544 058cd84 f30b544 058cd84 405c9f9 058cd84 7c07000 e441caf 058cd84 7c07000 058cd84 7c07000 058cd84 aa396c5 058cd84 aa396c5 058cd84 aa396c5 058cd84 7c07000 058cd84 7c07000 058cd84 7c07000 058cd84 6a6f6eb f30b544 058cd84 7c07000 aa396c5 7c07000 aa396c5 7c07000 aa396c5 7c07000 aa396c5 ef0f1be aa396c5 058cd84 7c07000 058cd84 414b2e9 7c07000 414b2e9 7c07000 414b2e9 058cd84 6a6f6eb 414b2e9 6a6f6eb 058cd84 830bf29 4086c42 058cd84 cb33b9e 414b2e9 cb33b9e 414b2e9 7043f18 cb33b9e 7043f18 cb33b9e 7043f18 830bf29 ef0f1be 830bf29 4086c42 830bf29 4086c42 414b2e9 830bf29 414b2e9 830bf29 7c07000 414b2e9 cb33b9e 6a6f6eb 414b2e9 6a6f6eb cb33b9e 414b2e9 6a6f6eb 058cd84 830bf29 058cd84 6a6f6eb 058cd84 7043f18 cb33b9e 7043f18 058cd84 7043f18 cb33b9e 7043f18 cb33b9e 7043f18 058cd84 7043f18 7c07000 405c9f9 414b2e9 058cd84 cb33b9e 058cd84 414b2e9 405c9f9 cb33b9e 7c07000 414b2e9 405c9f9 cb33b9e 405c9f9 cb33b9e 7043f18 405c9f9 cb33b9e 405c9f9 7043f18 cb33b9e 7043f18 cb33b9e 7043f18 405c9f9 cb33b9e 414b2e9 405c9f9 cb33b9e 405c9f9 7043f18 cb33b9e 405c9f9 414b2e9 058cd84 414b2e9 058cd84 414b2e9 405c9f9 414b2e9 058cd84 cb33b9e 7043f18 cb33b9e 7043f18 cb33b9e 7043f18 058cd84 8e222fd 7c07000 6a6f6eb e441caf 7c07000 6a6f6eb 7c07000 6a6f6eb 7c07000 6a6f6eb 7c07000 6a6f6eb 7c07000 6a6f6eb 7c07000 6a6f6eb ae21b62 e55650e 84f80c5 e55650e 058cd84 b916b29 700dff9 b916b29 700dff9 b916b29 7ba250b b916b29 7ba250b b916b29 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 |
import { MessageType } from '@/constants/chat';
import { fileIconMap } from '@/constants/common';
import {
useCreateToken,
useFetchConversation,
useFetchConversationList,
useFetchDialog,
useFetchDialogList,
useFetchStats,
useListToken,
useRemoveConversation,
useRemoveDialog,
useRemoveToken,
useSelectConversationList,
useSelectDialogList,
useSelectStats,
useSelectTokenList,
useSetDialog,
useUpdateConversation,
} from '@/hooks/chatHooks';
import {
useSetModalState,
useShowDeleteConfirm,
useTranslate,
} from '@/hooks/commonHooks';
import { useSendMessageWithSse } from '@/hooks/logicHooks';
import { useOneNamespaceEffectsLoading } from '@/hooks/storeHooks';
import {
IAnswer,
IConversation,
IDialog,
IStats,
} from '@/interfaces/database/chat';
import { IChunk } from '@/interfaces/database/knowledge';
import { getFileExtension } from '@/utils';
import { message } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import omit from 'lodash/omit';
import {
ChangeEventHandler,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useDispatch, useSearchParams, useSelector } from 'umi';
import { v4 as uuid } from 'uuid';
import { ChatSearchParams } from './constants';
import {
IClientConversation,
IMessage,
VariableTableDataType,
} from './interface';
import { ChatModelState } from './model';
import { isConversationIdExist } from './utils';
export const useSelectCurrentDialog = () => {
const currentDialog: IDialog = useSelector(
(state: any) => state.chatModel.currentDialog,
);
return currentDialog;
};
export const useFetchDialogOnMount = (
dialogId: string,
visible: boolean,
): IDialog => {
const currentDialog: IDialog = useSelectCurrentDialog();
const fetchDialog = useFetchDialog();
useEffect(() => {
if (dialogId && visible) {
fetchDialog(dialogId);
}
}, [dialogId, fetchDialog, visible]);
return currentDialog;
};
export const useSetCurrentDialog = () => {
const dispatch = useDispatch();
const currentDialog: IDialog = useSelector(
(state: any) => state.chatModel.currentDialog,
);
const setCurrentDialog = useCallback(
(dialogId: string) => {
dispatch({
type: 'chatModel/setCurrentDialog',
payload: { id: dialogId },
});
},
[dispatch],
);
return { currentDialog, setCurrentDialog };
};
export const useResetCurrentDialog = () => {
const dispatch = useDispatch();
const resetCurrentDialog = useCallback(() => {
dispatch({
type: 'chatModel/setCurrentDialog',
payload: {},
});
}, [dispatch]);
return { resetCurrentDialog };
};
export const useSelectPromptConfigParameters = (): VariableTableDataType[] => {
const currentDialog: IDialog = useSelector(
(state: any) => state.chatModel.currentDialog,
);
const finalParameters: VariableTableDataType[] = useMemo(() => {
const parameters = currentDialog?.prompt_config?.parameters ?? [];
if (!currentDialog.id) {
// The newly created chat has a default parameter
return [{ key: uuid(), variable: 'knowledge', optional: false }];
}
return parameters.map((x) => ({
key: uuid(),
variable: x.key,
optional: x.optional,
}));
}, [currentDialog]);
return finalParameters;
};
export const useDeleteDialog = () => {
const showDeleteConfirm = useShowDeleteConfirm();
const removeDocument = useRemoveDialog();
const onRemoveDialog = (dialogIds: Array<string>) => {
showDeleteConfirm({ onOk: () => removeDocument(dialogIds) });
};
return { onRemoveDialog };
};
export const useGetChatSearchParams = () => {
const [currentQueryParameters] = useSearchParams();
return {
dialogId: currentQueryParameters.get(ChatSearchParams.DialogId) || '',
conversationId:
currentQueryParameters.get(ChatSearchParams.ConversationId) || '',
};
};
export const useSetCurrentConversation = () => {
const dispatch = useDispatch();
const setCurrentConversation = useCallback(
(currentConversation: IClientConversation) => {
dispatch({
type: 'chatModel/setCurrentConversation',
payload: currentConversation,
});
},
[dispatch],
);
return setCurrentConversation;
};
export const useClickDialogCard = () => {
const [currentQueryParameters, setSearchParams] = useSearchParams();
const newQueryParameters: URLSearchParams = useMemo(() => {
return new URLSearchParams();
}, []);
const handleClickDialog = useCallback(
(dialogId: string) => {
newQueryParameters.set(ChatSearchParams.DialogId, dialogId);
// newQueryParameters.set(
// ChatSearchParams.ConversationId,
// EmptyConversationId,
// );
setSearchParams(newQueryParameters);
},
[newQueryParameters, setSearchParams],
);
return { handleClickDialog };
};
export const useSelectFirstDialogOnMount = () => {
const fetchDialogList = useFetchDialogList();
const dialogList = useSelectDialogList();
const { handleClickDialog } = useClickDialogCard();
const fetchList = useCallback(async () => {
const data = await fetchDialogList();
if (data.retcode === 0 && data.data.length > 0) {
handleClickDialog(data.data[0].id);
}
}, [fetchDialogList, handleClickDialog]);
useEffect(() => {
fetchList();
}, [fetchList]);
return dialogList;
};
export const useHandleItemHover = () => {
const [activated, setActivated] = useState<string>('');
const handleItemEnter = (id: string) => {
setActivated(id);
};
const handleItemLeave = () => {
setActivated('');
};
return {
activated,
handleItemEnter,
handleItemLeave,
};
};
export const useEditDialog = () => {
const [dialog, setDialog] = useState<IDialog>({} as IDialog);
const fetchDialog = useFetchDialog();
const submitDialog = useSetDialog();
const loading = useOneNamespaceEffectsLoading('chatModel', ['setDialog']);
const {
visible: dialogEditVisible,
hideModal: hideDialogEditModal,
showModal: showDialogEditModal,
} = useSetModalState();
const onDialogEditOk = useCallback(
async (dialog: IDialog) => {
const ret = await submitDialog(dialog);
if (ret === 0) {
hideDialogEditModal();
}
},
[submitDialog, hideDialogEditModal],
);
const handleShowDialogEditModal = useCallback(
async (dialogId?: string) => {
if (dialogId) {
const ret = await fetchDialog(dialogId, false);
if (ret.retcode === 0) {
setDialog(ret.data);
}
}
showDialogEditModal();
},
[showDialogEditModal, fetchDialog],
);
const clearDialog = useCallback(() => {
setDialog({} as IDialog);
}, []);
return {
dialogSettingLoading: loading,
initialDialog: dialog,
onDialogEditOk,
dialogEditVisible,
hideDialogEditModal,
showDialogEditModal: handleShowDialogEditModal,
clearDialog,
};
};
//#region conversation
export const useFetchConversationListOnMount = () => {
const conversationList = useSelectConversationList();
const { dialogId } = useGetChatSearchParams();
const fetchConversationList = useFetchConversationList();
useEffect(() => {
fetchConversationList(dialogId);
}, [fetchConversationList, dialogId]);
return conversationList;
};
export const useSelectDerivedConversationList = () => {
const [list, setList] = useState<Array<IConversation>>([]);
let chatModel: ChatModelState = useSelector((state: any) => state.chatModel);
const { conversationList, currentDialog } = chatModel;
const { dialogId } = useGetChatSearchParams();
const prologue = currentDialog?.prompt_config?.prologue ?? '';
const addTemporaryConversation = useCallback(() => {
setList((pre) => {
if (dialogId) {
const nextList = [
{
id: '',
name: 'New conversation',
dialog_id: dialogId,
message: [
{
content: prologue,
role: MessageType.Assistant,
},
],
} as IConversation,
...conversationList,
];
return nextList;
}
return pre;
});
}, [conversationList, dialogId, prologue]);
useEffect(() => {
addTemporaryConversation();
}, [addTemporaryConversation]);
return { list, addTemporaryConversation };
};
export const useClickConversationCard = () => {
const [currentQueryParameters, setSearchParams] = useSearchParams();
const newQueryParameters: URLSearchParams = useMemo(
() => new URLSearchParams(currentQueryParameters.toString()),
[currentQueryParameters],
);
const handleClickConversation = useCallback(
(conversationId: string) => {
newQueryParameters.set(ChatSearchParams.ConversationId, conversationId);
setSearchParams(newQueryParameters);
},
[newQueryParameters, setSearchParams],
);
return { handleClickConversation };
};
export const useSetConversation = () => {
const { dialogId } = useGetChatSearchParams();
const updateConversation = useUpdateConversation();
const setConversation = useCallback(
(message: string) => {
return updateConversation({
dialog_id: dialogId,
name: message,
message: [
{
role: MessageType.Assistant,
content: message,
},
],
});
},
[updateConversation, dialogId],
);
return { setConversation };
};
export const useSelectCurrentConversation = () => {
const [currentConversation, setCurrentConversation] =
useState<IClientConversation>({} as IClientConversation);
const conversation: IClientConversation = useSelector(
(state: any) => state.chatModel.currentConversation,
);
const dialog = useSelectCurrentDialog();
const { conversationId, dialogId } = useGetChatSearchParams();
const addNewestConversation = useCallback(
(message: string, answer: string = '') => {
setCurrentConversation((pre) => {
return {
...pre,
message: [
...pre.message,
{
role: MessageType.User,
content: message,
id: uuid(),
} as IMessage,
{
role: MessageType.Assistant,
content: answer,
id: uuid(),
reference: [],
} as IMessage,
],
};
});
},
[],
);
const addNewestAnswer = useCallback((answer: IAnswer) => {
setCurrentConversation((pre) => {
const latestMessage = pre.message?.at(-1);
if (latestMessage) {
return {
...pre,
message: [
...pre.message.slice(0, -1),
{
...latestMessage,
content: answer.answer,
reference: answer.reference,
} as IMessage,
],
};
}
return pre;
});
}, []);
const removeLatestMessage = useCallback(() => {
console.info('removeLatestMessage');
setCurrentConversation((pre) => {
const nextMessages = pre.message?.slice(0, -2) ?? [];
return {
...pre,
message: nextMessages,
};
});
}, []);
const addPrologue = useCallback(() => {
if (dialogId !== '' && conversationId === '') {
const prologue = dialog.prompt_config?.prologue;
const nextMessage = {
role: MessageType.Assistant,
content: prologue,
id: uuid(),
} as IMessage;
setCurrentConversation({
id: '',
dialog_id: dialogId,
reference: [],
message: [nextMessage],
} as any);
}
}, [conversationId, dialog, dialogId]);
useEffect(() => {
addPrologue();
}, [addPrologue]);
useEffect(() => {
if (conversationId) {
setCurrentConversation(conversation);
}
}, [conversation, conversationId]);
return {
currentConversation,
addNewestConversation,
removeLatestMessage,
addNewestAnswer,
};
};
export const useScrollToBottom = (currentConversation: IClientConversation) => {
const ref = useRef<HTMLDivElement>(null);
const scrollToBottom = useCallback(() => {
console.info('useScrollToBottom');
if (currentConversation.id) {
ref.current?.scrollIntoView({ behavior: 'instant' });
}
}, [currentConversation]);
useEffect(() => {
scrollToBottom();
}, [scrollToBottom]);
return ref;
};
export const useFetchConversationOnMount = () => {
const { conversationId } = useGetChatSearchParams();
const fetchConversation = useFetchConversation();
const {
currentConversation,
addNewestConversation,
removeLatestMessage,
addNewestAnswer,
} = useSelectCurrentConversation();
const ref = useScrollToBottom(currentConversation);
const fetchConversationOnMount = useCallback(() => {
if (isConversationIdExist(conversationId)) {
fetchConversation(conversationId);
}
}, [fetchConversation, conversationId]);
useEffect(() => {
fetchConversationOnMount();
}, [fetchConversationOnMount]);
return {
currentConversation,
addNewestConversation,
ref,
removeLatestMessage,
addNewestAnswer,
};
};
export const useHandleMessageInputChange = () => {
const [value, setValue] = useState('');
const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
const value = e.target.value;
const nextValue = value.replaceAll('\\n', '\n').replaceAll('\\t', '\t');
setValue(nextValue);
};
return {
handleInputChange,
value,
setValue,
};
};
export const useSendMessage = (
conversation: IClientConversation,
addNewestConversation: (message: string, answer?: string) => void,
removeLatestMessage: () => void,
addNewestAnswer: (answer: IAnswer) => void,
) => {
const { setConversation } = useSetConversation();
const { conversationId } = useGetChatSearchParams();
const { handleInputChange, value, setValue } = useHandleMessageInputChange();
const fetchConversation = useFetchConversation();
const { handleClickConversation } = useClickConversationCard();
const { send, answer, done } = useSendMessageWithSse();
const sendMessage = useCallback(
async (message: string, id?: string) => {
const res: Response = await send({
conversation_id: id ?? conversationId,
messages: [
...(conversation?.message ?? []).map((x: IMessage) => omit(x, 'id')),
{
role: MessageType.User,
content: message,
},
],
});
if (res.status === 200) {
if (id) {
console.info('111');
// new conversation
handleClickConversation(id);
} else {
console.info('222');
// fetchConversation(conversationId);
}
} else {
console.info('333');
// cancel loading
setValue(message);
console.info('removeLatestMessage111');
removeLatestMessage();
}
console.info('false');
},
[
conversation?.message,
conversationId,
// fetchConversation,
handleClickConversation,
removeLatestMessage,
setValue,
send,
],
);
const handleSendMessage = useCallback(
async (message: string) => {
if (conversationId !== '') {
sendMessage(message);
} else {
const data = await setConversation(message);
if (data.retcode === 0) {
const id = data.data.id;
sendMessage(message, id);
}
}
},
[conversationId, setConversation, sendMessage],
);
useEffect(() => {
if (answer.answer) {
addNewestAnswer(answer);
console.info('true?');
console.info('send msg:', answer.answer);
}
}, [answer, addNewestAnswer]);
const handlePressEnter = useCallback(() => {
if (done) {
setValue('');
handleSendMessage(value.trim());
}
addNewestConversation(value);
}, [addNewestConversation, handleSendMessage, done, setValue, value]);
return {
handlePressEnter,
handleInputChange,
value,
loading: !done,
};
};
export const useGetFileIcon = () => {
// const req = require.context('@/assets/svg/file-icon');
// const ret = req.keys().map(req);
// console.info(ret);
// useEffect(() => {}, []);
const getFileIcon = (filename: string) => {
const ext: string = getFileExtension(filename);
const iconPath = fileIconMap[ext as keyof typeof fileIconMap];
// const x = require(`@/assets/svg/file-icon/${iconPath}`);
return `@/assets/svg/file-icon/${iconPath}`;
};
return getFileIcon;
};
export const useDeleteConversation = () => {
const { dialogId } = useGetChatSearchParams();
const { handleClickConversation } = useClickConversationCard();
const showDeleteConfirm = useShowDeleteConfirm();
const removeConversation = useRemoveConversation();
const deleteConversation = (conversationIds: Array<string>) => async () => {
const ret = await removeConversation(conversationIds, dialogId);
if (ret === 0) {
handleClickConversation('');
}
return ret;
};
const onRemoveConversation = (conversationIds: Array<string>) => {
showDeleteConfirm({ onOk: deleteConversation(conversationIds) });
};
return { onRemoveConversation };
};
export const useRenameConversation = () => {
const [conversation, setConversation] = useState<IClientConversation>(
{} as IClientConversation,
);
const fetchConversation = useFetchConversation();
const {
visible: conversationRenameVisible,
hideModal: hideConversationRenameModal,
showModal: showConversationRenameModal,
} = useSetModalState();
const updateConversation = useUpdateConversation();
const onConversationRenameOk = useCallback(
async (name: string) => {
const ret = await updateConversation({
...conversation,
conversation_id: conversation.id,
name,
});
if (ret.retcode === 0) {
hideConversationRenameModal();
}
},
[updateConversation, conversation, hideConversationRenameModal],
);
const loading = useOneNamespaceEffectsLoading('chatModel', [
'setConversation',
]);
const handleShowConversationRenameModal = useCallback(
async (conversationId: string) => {
const ret = await fetchConversation(conversationId, false);
if (ret.retcode === 0) {
setConversation(ret.data);
}
showConversationRenameModal();
},
[showConversationRenameModal, fetchConversation],
);
return {
conversationRenameLoading: loading,
initialConversationName: conversation.name,
onConversationRenameOk,
conversationRenameVisible,
hideConversationRenameModal,
showConversationRenameModal: handleShowConversationRenameModal,
};
};
export const useClickDrawer = () => {
const { visible, showModal, hideModal } = useSetModalState();
const [selectedChunk, setSelectedChunk] = useState<IChunk>({} as IChunk);
const [documentId, setDocumentId] = useState<string>('');
const clickDocumentButton = useCallback(
(documentId: string, chunk: IChunk) => {
showModal();
setSelectedChunk(chunk);
setDocumentId(documentId);
},
[showModal],
);
return {
clickDocumentButton,
visible,
showModal,
hideModal,
selectedChunk,
documentId,
};
};
export const useSelectDialogListLoading = () => {
return useOneNamespaceEffectsLoading('chatModel', ['listDialog']);
};
export const useSelectConversationListLoading = () => {
return useOneNamespaceEffectsLoading('chatModel', ['listConversation']);
};
export const useSelectConversationLoading = () => {
return useOneNamespaceEffectsLoading('chatModel', ['getConversation']);
};
export const useGetSendButtonDisabled = () => {
const { dialogId, conversationId } = useGetChatSearchParams();
return dialogId === '' && conversationId === '';
};
//#endregion
//#region API provided for external calls
type RangeValue = [Dayjs | null, Dayjs | null] | null;
const getDay = (date: Dayjs) => date.format('YYYY-MM-DD');
export const useFetchStatsOnMount = (visible: boolean) => {
const fetchStats = useFetchStats();
const [pickerValue, setPickerValue] = useState<RangeValue>([
dayjs(),
dayjs().subtract(7, 'day'),
]);
useEffect(() => {
if (visible && Array.isArray(pickerValue) && pickerValue[0]) {
fetchStats({
fromDate: getDay(pickerValue[0]),
toDate: getDay(pickerValue[1] ?? dayjs()),
});
}
}, [fetchStats, pickerValue, visible]);
return {
pickerValue,
setPickerValue,
};
};
export const useOperateApiKey = (visible: boolean, dialogId: string) => {
const removeToken = useRemoveToken();
const createToken = useCreateToken(dialogId);
const listToken = useListToken();
const tokenList = useSelectTokenList();
const creatingLoading = useOneNamespaceEffectsLoading('chatModel', [
'createToken',
]);
const listLoading = useOneNamespaceEffectsLoading('chatModel', ['list']);
const showDeleteConfirm = useShowDeleteConfirm();
const onRemoveToken = (token: string, tenantId: string) => {
showDeleteConfirm({
onOk: () => removeToken({ dialogId, tokens: [token], tenantId }),
});
};
useEffect(() => {
if (visible && dialogId) {
listToken(dialogId);
}
}, [listToken, dialogId, visible]);
return {
removeToken: onRemoveToken,
createToken,
tokenList,
creatingLoading,
listLoading,
};
};
type ChartStatsType = {
[k in keyof IStats]: Array<{ xAxis: string; yAxis: number }>;
};
export const useSelectChartStatsList = (): ChartStatsType => {
const stats: IStats = useSelectStats();
// const stats = {
// pv: [
// ['2024-06-01', 1],
// ['2024-07-24', 3],
// ['2024-09-01', 10],
// ],
// uv: [
// ['2024-02-01', 0],
// ['2024-03-01', 99],
// ['2024-05-01', 3],
// ],
// speed: [
// ['2024-09-01', 2],
// ['2024-09-01', 3],
// ],
// tokens: [
// ['2024-09-01', 1],
// ['2024-09-01', 3],
// ],
// round: [
// ['2024-09-01', 0],
// ['2024-09-01', 3],
// ],
// thumb_up: [
// ['2024-09-01', 3],
// ['2024-09-01', 9],
// ],
// };
return Object.keys(stats).reduce((pre, cur) => {
const item = stats[cur as keyof IStats];
if (item.length > 0) {
pre[cur as keyof IStats] = item.map((x) => ({
xAxis: x[0] as string,
yAxis: x[1] as number,
}));
}
return pre;
}, {} as ChartStatsType);
};
export const useShowTokenEmptyError = () => {
const [messageApi, contextHolder] = message.useMessage();
const { t } = useTranslate('chat');
const showTokenEmptyError = useCallback(() => {
messageApi.error(t('tokenError'));
}, [messageApi, t]);
return { showTokenEmptyError, contextHolder };
};
const getUrlWithToken = (token: string) => {
const { protocol, host } = window.location;
return `${protocol}//${host}/chat/share?shared_id=${token}`;
};
const useFetchTokenListBeforeOtherStep = (dialogId: string) => {
const { showTokenEmptyError, contextHolder } = useShowTokenEmptyError();
const listToken = useListToken();
const tokenList = useSelectTokenList();
const token =
Array.isArray(tokenList) && tokenList.length > 0 ? tokenList[0].token : '';
const handleOperate = useCallback(async () => {
const data = await listToken(dialogId);
const list = data.data;
if (data.retcode === 0 && Array.isArray(list) && list.length > 0) {
return list[0]?.token;
} else {
showTokenEmptyError();
return false;
}
}, [dialogId, listToken, showTokenEmptyError]);
return {
token,
contextHolder,
handleOperate,
};
};
export const useShowEmbedModal = (dialogId: string) => {
const {
visible: embedVisible,
hideModal: hideEmbedModal,
showModal: showEmbedModal,
} = useSetModalState();
const { handleOperate, token, contextHolder } =
useFetchTokenListBeforeOtherStep(dialogId);
const handleShowEmbedModal = useCallback(async () => {
const succeed = await handleOperate();
if (succeed) {
showEmbedModal();
}
}, [handleOperate, showEmbedModal]);
return {
showEmbedModal: handleShowEmbedModal,
hideEmbedModal,
embedVisible,
embedToken: token,
errorContextHolder: contextHolder,
};
};
export const usePreviewChat = (dialogId: string) => {
const { handleOperate, contextHolder } =
useFetchTokenListBeforeOtherStep(dialogId);
const open = useCallback((t: string) => {
window.open(getUrlWithToken(t), '_blank');
}, []);
const handlePreview = useCallback(async () => {
const token = await handleOperate();
if (token) {
open(token);
}
}, [handleOperate, open]);
return {
handlePreview,
contextHolder,
};
};
//#endregion
|