chat-input.tsx 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import type { FC } from 'react'
  2. import {
  3. memo,
  4. useRef,
  5. useState,
  6. } from 'react'
  7. import { useContext } from 'use-context-selector'
  8. import Recorder from 'js-audio-recorder'
  9. import { useTranslation } from 'react-i18next'
  10. import Textarea from 'rc-textarea'
  11. import type {
  12. EnableType,
  13. OnSend,
  14. VisionConfig,
  15. } from '../types'
  16. import { TransferMethod } from '../types'
  17. import TooltipPlus from '@/app/components/base/tooltip-plus'
  18. import { ToastContext } from '@/app/components/base/toast'
  19. import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'
  20. import VoiceInput from '@/app/components/base/voice-input'
  21. import { Microphone01 } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'
  22. import { Microphone01 as Microphone01Solid } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
  23. import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'
  24. import { Send03 } from '@/app/components/base/icons/src/vender/solid/communication'
  25. import ChatImageUploader from '@/app/components/base/image-uploader/chat-image-uploader'
  26. import ImageList from '@/app/components/base/image-uploader/image-list'
  27. import {
  28. useClipboardUploader,
  29. useDraggableUploader,
  30. useImageFiles,
  31. } from '@/app/components/base/image-uploader/hooks'
  32. type ChatInputProps = {
  33. visionConfig?: VisionConfig
  34. speechToTextConfig?: EnableType
  35. onSend?: OnSend
  36. }
  37. const ChatInput: FC<ChatInputProps> = ({
  38. visionConfig,
  39. speechToTextConfig,
  40. onSend,
  41. }) => {
  42. const { t } = useTranslation()
  43. const { notify } = useContext(ToastContext)
  44. const [voiceInputShow, setVoiceInputShow] = useState(false)
  45. const {
  46. files,
  47. onUpload,
  48. onRemove,
  49. onReUpload,
  50. onImageLinkLoadError,
  51. onImageLinkLoadSuccess,
  52. onClear,
  53. } = useImageFiles()
  54. const { onPaste } = useClipboardUploader({ onUpload, visionConfig, files })
  55. const { onDragEnter, onDragLeave, onDragOver, onDrop, isDragActive } = useDraggableUploader<HTMLTextAreaElement>({ onUpload, files, visionConfig })
  56. const isUseInputMethod = useRef(false)
  57. const [query, setQuery] = useState('')
  58. const handleContentChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
  59. const value = e.target.value
  60. setQuery(value)
  61. }
  62. const handleSend = () => {
  63. if (onSend) {
  64. if (files.find(item => item.type === TransferMethod.local_file && !item.fileId)) {
  65. notify({ type: 'info', message: t('appDebug.errorMessage.waitForImgUpload') })
  66. return
  67. }
  68. if (!query || !query.trim()) {
  69. notify({ type: 'info', message: t('appAnnotation.errorMessage.queryRequired') })
  70. return
  71. }
  72. onSend(query, files.filter(file => file.progress !== -1).map(fileItem => ({
  73. type: 'image',
  74. transfer_method: fileItem.type,
  75. url: fileItem.url,
  76. upload_file_id: fileItem.fileId,
  77. })))
  78. setQuery('')
  79. onClear()
  80. }
  81. }
  82. const handleKeyUp = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  83. if (e.code === 'Enter') {
  84. e.preventDefault()
  85. // prevent send message when using input method enter
  86. if (!e.shiftKey && !isUseInputMethod.current)
  87. handleSend()
  88. }
  89. }
  90. const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
  91. isUseInputMethod.current = e.nativeEvent.isComposing
  92. if (e.code === 'Enter' && !e.shiftKey) {
  93. setQuery(query.replace(/\n$/, ''))
  94. e.preventDefault()
  95. }
  96. }
  97. const logError = (message: string) => {
  98. notify({ type: 'error', message, duration: 3000 })
  99. }
  100. const handleVoiceInputShow = () => {
  101. (Recorder as any).getPermission().then(() => {
  102. setVoiceInputShow(true)
  103. }, () => {
  104. logError(t('common.voiceInput.notAllow'))
  105. })
  106. }
  107. const media = useBreakpoints()
  108. const isMobile = media === MediaType.mobile
  109. const sendBtn = (
  110. <div
  111. className='group flex items-center justify-center w-8 h-8 rounded-lg hover:bg-[#EBF5FF] cursor-pointer'
  112. onClick={handleSend}
  113. >
  114. <Send03
  115. className={`
  116. w-5 h-5 text-gray-300 group-hover:text-primary-600
  117. ${!!query.trim() && 'text-primary-600'}
  118. `}
  119. />
  120. </div>
  121. )
  122. return (
  123. <div className='relative'>
  124. <div
  125. className={`
  126. p-[5.5px] max-h-[150px] bg-white border-[1.5px] border-gray-200 rounded-xl overflow-y-auto
  127. ${isDragActive && 'border-primary-600'}
  128. `}
  129. >
  130. {
  131. visionConfig?.enabled && (
  132. <>
  133. <div className='absolute bottom-2 left-2 flex items-center'>
  134. <ChatImageUploader
  135. settings={visionConfig}
  136. onUpload={onUpload}
  137. disabled={files.length >= visionConfig.number_limits}
  138. />
  139. <div className='mx-1 w-[1px] h-4 bg-black/5' />
  140. </div>
  141. <div className='pl-[52px]'>
  142. <ImageList
  143. list={files}
  144. onRemove={onRemove}
  145. onReUpload={onReUpload}
  146. onImageLinkLoadSuccess={onImageLinkLoadSuccess}
  147. onImageLinkLoadError={onImageLinkLoadError}
  148. />
  149. </div>
  150. </>
  151. )
  152. }
  153. <Textarea
  154. className={`
  155. block w-full px-2 pr-[118px] py-[7px] leading-5 max-h-none text-sm text-gray-700 outline-none appearance-none resize-none
  156. ${visionConfig?.enabled && 'pl-12'}
  157. `}
  158. value={query}
  159. onChange={handleContentChange}
  160. onKeyUp={handleKeyUp}
  161. onKeyDown={handleKeyDown}
  162. onPaste={onPaste}
  163. onDragEnter={onDragEnter}
  164. onDragLeave={onDragLeave}
  165. onDragOver={onDragOver}
  166. onDrop={onDrop}
  167. autoSize
  168. />
  169. <div className='absolute bottom-[7px] right-2 flex items-center h-8'>
  170. <div className='flex items-center px-1 h-5 rounded-md bg-gray-100 text-xs font-medium text-gray-500'>
  171. {query.trim().length}
  172. </div>
  173. {
  174. query
  175. ? (
  176. <div className='flex justify-center items-center ml-2 w-8 h-8 cursor-pointer hover:bg-gray-100 rounded-lg' onClick={() => setQuery('')}>
  177. <XCircle className='w-4 h-4 text-[#98A2B3]' />
  178. </div>
  179. )
  180. : speechToTextConfig?.enabled
  181. ? (
  182. <div
  183. className='group flex justify-center items-center ml-2 w-8 h-8 hover:bg-primary-50 rounded-lg cursor-pointer'
  184. onClick={handleVoiceInputShow}
  185. >
  186. <Microphone01 className='block w-4 h-4 text-gray-500 group-hover:hidden' />
  187. <Microphone01Solid className='hidden w-4 h-4 text-primary-600 group-hover:block' />
  188. </div>
  189. )
  190. : null
  191. }
  192. <div className='mx-2 w-[1px] h-4 bg-black opacity-5' />
  193. {isMobile
  194. ? sendBtn
  195. : (
  196. <TooltipPlus
  197. popupContent={
  198. <div>
  199. <div>{t('common.operation.send')} Enter</div>
  200. <div>{t('common.operation.lineBreak')} Shift Enter</div>
  201. </div>
  202. }
  203. >
  204. {sendBtn}
  205. </TooltipPlus>
  206. )}
  207. </div>
  208. {
  209. voiceInputShow && (
  210. <VoiceInput
  211. onCancel={() => setVoiceInputShow(false)}
  212. onConverted={text => setQuery(text)}
  213. />
  214. )
  215. }
  216. </div>
  217. </div>
  218. )
  219. }
  220. export default memo(ChatInput)