chat-input.tsx 7.2 KB

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