您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. import { useTranslate } from '@/hooks/common-hooks';
  2. import {
  3. useDeleteDocument,
  4. useFetchDocumentInfosByIds,
  5. useRemoveNextDocument,
  6. useUploadAndParseDocument,
  7. } from '@/hooks/document-hooks';
  8. import { getExtension } from '@/utils/document-util';
  9. import { formatBytes } from '@/utils/file-util';
  10. import {
  11. CloseCircleOutlined,
  12. InfoCircleOutlined,
  13. LoadingOutlined,
  14. } from '@ant-design/icons';
  15. import type { GetProp, UploadFile } from 'antd';
  16. import {
  17. Button,
  18. Card,
  19. Flex,
  20. Input,
  21. List,
  22. Space,
  23. Spin,
  24. Typography,
  25. Upload,
  26. UploadProps,
  27. } from 'antd';
  28. import classNames from 'classnames';
  29. import get from 'lodash/get';
  30. import { Paperclip } from 'lucide-react';
  31. import {
  32. ChangeEventHandler,
  33. memo,
  34. useCallback,
  35. useEffect,
  36. useRef,
  37. useState,
  38. KeyboardEventHandler,
  39. } from 'react';
  40. import FileIcon from '../file-icon';
  41. import styles from './index.less';
  42. type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
  43. const { Text } = Typography;
  44. const getFileId = (file: UploadFile) => get(file, 'response.data.0');
  45. const getFileIds = (fileList: UploadFile[]) => {
  46. const ids = fileList.reduce((pre, cur) => {
  47. return pre.concat(get(cur, 'response.data', []));
  48. }, []);
  49. return ids;
  50. };
  51. const isUploadSuccess = (file: UploadFile) => {
  52. const code = get(file, 'response.code');
  53. return typeof code === 'number' && code === 0;
  54. };
  55. interface IProps {
  56. disabled: boolean;
  57. value: string;
  58. sendDisabled: boolean;
  59. sendLoading: boolean;
  60. onPressEnter(documentIds: string[]): void;
  61. onInputChange: ChangeEventHandler<HTMLInputElement>;
  62. conversationId: string;
  63. uploadMethod?: string;
  64. isShared?: boolean;
  65. showUploadIcon?: boolean;
  66. createConversationBeforeUploadDocument?(message: string): Promise<any>;
  67. }
  68. const getBase64 = (file: FileType): Promise<string> =>
  69. new Promise((resolve, reject) => {
  70. const reader = new FileReader();
  71. reader.readAsDataURL(file as any);
  72. reader.onload = () => resolve(reader.result as string);
  73. reader.onerror = (error) => reject(error);
  74. });
  75. const MessageInput = ({
  76. isShared = false,
  77. disabled,
  78. value,
  79. onPressEnter,
  80. sendDisabled,
  81. sendLoading,
  82. onInputChange,
  83. conversationId,
  84. showUploadIcon = true,
  85. createConversationBeforeUploadDocument,
  86. uploadMethod = 'upload_and_parse',
  87. }: IProps) => {
  88. const { t } = useTranslate('chat');
  89. const { removeDocument } = useRemoveNextDocument();
  90. const { deleteDocument } = useDeleteDocument();
  91. const { data: documentInfos, setDocumentIds } = useFetchDocumentInfosByIds();
  92. const { uploadAndParseDocument } = useUploadAndParseDocument(uploadMethod);
  93. const conversationIdRef = useRef(conversationId);
  94. const [fileList, setFileList] = useState<UploadFile[]>([]);
  95. const handlePreview = async (file: UploadFile) => {
  96. if (!file.url && !file.preview) {
  97. file.preview = await getBase64(file.originFileObj as FileType);
  98. }
  99. };
  100. const handleChange: UploadProps['onChange'] = async ({
  101. // fileList: newFileList,
  102. file,
  103. }) => {
  104. let nextConversationId: string = conversationId;
  105. if (createConversationBeforeUploadDocument) {
  106. const creatingRet = await createConversationBeforeUploadDocument(
  107. file.name,
  108. );
  109. if (creatingRet?.code === 0) {
  110. nextConversationId = creatingRet.data.id;
  111. }
  112. }
  113. setFileList((list) => {
  114. list.push({
  115. ...file,
  116. status: 'uploading',
  117. originFileObj: file as any,
  118. });
  119. return [...list];
  120. });
  121. const ret = await uploadAndParseDocument({
  122. conversationId: nextConversationId,
  123. fileList: [file],
  124. });
  125. setFileList((list) => {
  126. const nextList = list.filter((x) => x.uid !== file.uid);
  127. nextList.push({
  128. ...file,
  129. originFileObj: file as any,
  130. response: ret,
  131. percent: 100,
  132. status: ret?.code === 0 ? 'done' : 'error',
  133. });
  134. return nextList;
  135. });
  136. };
  137. const isUploadingFile = fileList.some((x) => x.status === 'uploading');
  138. const handlePressEnter = useCallback(async () => {
  139. if (isUploadingFile) return;
  140. const ids = getFileIds(fileList.filter((x) => isUploadSuccess(x)));
  141. onPressEnter(ids);
  142. setFileList([]);
  143. }, [fileList, onPressEnter, isUploadingFile]);
  144. const handleInputKeyDown: KeyboardEventHandler<HTMLTextAreaElement> = (e) => {
  145. if (e.key === 'Enter' && !e.nativeEvent.shiftKey) {
  146. e.preventDefault();
  147. handlePressEnter();
  148. }
  149. };
  150. const handleRemove = useCallback(
  151. async (file: UploadFile) => {
  152. const ids = get(file, 'response.data', []);
  153. // Upload Successfully
  154. if (Array.isArray(ids) && ids.length) {
  155. if (isShared) {
  156. await deleteDocument(ids);
  157. } else {
  158. await removeDocument(ids[0]);
  159. }
  160. setFileList((preList) => {
  161. return preList.filter((x) => getFileId(x) !== ids[0]);
  162. });
  163. } else {
  164. // Upload failed
  165. setFileList((preList) => {
  166. return preList.filter((x) => x.uid !== file.uid);
  167. });
  168. }
  169. },
  170. [removeDocument, deleteDocument, isShared],
  171. );
  172. const getDocumentInfoById = useCallback(
  173. (id: string) => {
  174. return documentInfos.find((x) => x.id === id);
  175. },
  176. [documentInfos],
  177. );
  178. useEffect(() => {
  179. const ids = getFileIds(fileList);
  180. setDocumentIds(ids);
  181. }, [fileList, setDocumentIds]);
  182. useEffect(() => {
  183. if (
  184. conversationIdRef.current &&
  185. conversationId !== conversationIdRef.current
  186. ) {
  187. setFileList([]);
  188. }
  189. conversationIdRef.current = conversationId;
  190. }, [conversationId, setFileList]);
  191. return (
  192. <Flex gap={20} vertical className={styles.messageInputWrapper}>
  193. <Flex align="center" gap={8}>
  194. <Input.TextArea
  195. size="large"
  196. placeholder={t('sendPlaceholder')}
  197. value={value}
  198. disabled={disabled}
  199. className={classNames({ [styles.inputWrapper]: fileList.length === 0 })}
  200. onKeyDown={handleInputKeyDown}
  201. onChange={onInputChange}
  202. autoSize={{ minRows: 1, maxRows: 6 }}
  203. />
  204. <Space>
  205. {showUploadIcon && (
  206. <Upload
  207. onPreview={handlePreview}
  208. onChange={handleChange}
  209. multiple={false}
  210. onRemove={handleRemove}
  211. showUploadList={false}
  212. beforeUpload={() => {
  213. return false;
  214. }}
  215. >
  216. <Button
  217. type={'text'}
  218. disabled={disabled}
  219. icon={<Paperclip />}
  220. ></Button>
  221. </Upload>
  222. )}
  223. <Button
  224. type="primary"
  225. onClick={handlePressEnter}
  226. loading={sendLoading}
  227. disabled={sendDisabled || isUploadingFile}
  228. >
  229. {t('send')}
  230. </Button>
  231. </Space>
  232. </Flex>
  233. {fileList.length > 0 && (
  234. <List
  235. grid={{
  236. gutter: 16,
  237. xs: 1,
  238. sm: 1,
  239. md: 1,
  240. lg: 1,
  241. xl: 2,
  242. xxl: 4,
  243. }}
  244. dataSource={fileList}
  245. className={styles.listWrapper}
  246. renderItem={(item) => {
  247. const id = getFileId(item);
  248. const documentInfo = getDocumentInfoById(id);
  249. const fileExtension = getExtension(documentInfo?.name ?? '');
  250. const fileName = item.originFileObj?.name ?? '';
  251. return (
  252. <List.Item>
  253. <Card className={styles.documentCard}>
  254. <Flex gap={10} align="center">
  255. {item.status === 'uploading' ? (
  256. <Spin
  257. indicator={
  258. <LoadingOutlined style={{ fontSize: 24 }} spin />
  259. }
  260. />
  261. ) : item.status === 'error' ? (
  262. <InfoCircleOutlined size={30}></InfoCircleOutlined>
  263. ) : (
  264. <FileIcon id={id} name={fileName}></FileIcon>
  265. )}
  266. <Flex vertical style={{ width: '90%' }}>
  267. <Text
  268. ellipsis={{ tooltip: fileName }}
  269. className={styles.nameText}
  270. >
  271. <b> {fileName}</b>
  272. </Text>
  273. {item.status === 'error' ? (
  274. t('uploadFailed')
  275. ) : (
  276. <>
  277. {item.percent !== 100 ? (
  278. t('uploading')
  279. ) : !item.response ? (
  280. t('parsing')
  281. ) : (
  282. <Space>
  283. <span>{fileExtension?.toUpperCase()},</span>
  284. <span>
  285. {formatBytes(
  286. getDocumentInfoById(id)?.size ?? 0,
  287. )}
  288. </span>
  289. </Space>
  290. )}
  291. </>
  292. )}
  293. </Flex>
  294. </Flex>
  295. {item.status !== 'uploading' && (
  296. <span className={styles.deleteIcon}>
  297. <CloseCircleOutlined onClick={() => handleRemove(item)} />
  298. </span>
  299. )}
  300. </Card>
  301. </List.Item>
  302. );
  303. }}
  304. />
  305. )}
  306. </Flex>
  307. );
  308. };
  309. export default memo(MessageInput);