chat-input.tsx 8.8 KB

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