chat-input.tsx 8.5 KB

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