Commit c4992685 by liimin

refactor(chat): 优化聊天组件性能和功能

- 移除未使用的 Practice 组件
- 重构 InitQuestions 组件,使用 useMemo 优化性能
- 优化 Feedback 按钮逻辑,添加异常处理
- 调整 ChatInputArea 样式和功能
- 移除 Footer 组件中的冗余代码
- 优化 Chat 组件的滚动逻辑,使用 requestAnimationFrame 和 MutationObserver
1 parent f127c9e5
No preview for this file type
...@@ -2,11 +2,11 @@ ...@@ -2,11 +2,11 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-06-25 15:35:52 * @LastEditTime: 2025-06-26 16:34:29
* @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat-with-history\chat-wrapper.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import { useCallback, useEffect, useMemo, useState, FC, useRef } from 'react' import { useCallback, useEffect, useMemo, useState, FC, useRef, use } from 'react'
import Chat from '../chat' import Chat from '../chat'
import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types' import type { ChatConfig, ChatItem, ChatItemInTree, OnSend } from '../types'
import { useChat } from '../chat/hooks' import { useChat } from '../chat/hooks'
...@@ -57,7 +57,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -57,7 +57,7 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
appConfig, appConfig,
{ {
inputs: (currentConversationId ? currentConversationInputs : newConversationInputs) as any, inputs: (currentConversationId ? currentConversationInputs : newConversationInputs) as any,
inputsForm:[] //InputsForm, inputsForm: [], //InputsForm,
}, },
appPrevChatTree, appPrevChatTree,
taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId), taskId => stopChatMessageResponding('', taskId, isInstalledApp, appId),
...@@ -104,7 +104,6 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest ...@@ -104,7 +104,6 @@ const ChatWrapper: FC<Props> = ({ avatar, aiAvatar, doClear, presuppositionQuest
hasAutoSended.current = true hasAutoSended.current = true
} }
}, []) }, [])
useEffect(() => { useEffect(() => {
setIsResponding(respondingState) setIsResponding(respondingState)
}, [respondingState, setIsResponding]) }, [respondingState, setIsResponding])
......
import type { FC } from 'react' import type { FC } from 'react'
import { memo, useMemo } from 'react' import { memo } from 'react'
import type { ChatItem } from '../../types' import type { ChatItem } from '../../types'
import { Markdown } from '@/app/components/base/markdown' import { Markdown } from '@/app/components/base/markdown'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
...@@ -7,13 +7,31 @@ import cn from '@/utils/classnames' ...@@ -7,13 +7,31 @@ import cn from '@/utils/classnames'
type BasicContentProps = { type BasicContentProps = {
item: ChatItem item: ChatItem
} }
const BasicContent: FC<BasicContentProps> = ({ item }) => { const BasicContent: FC<BasicContentProps> = ({
const { annotation, content } = item item,
const Mark = useMemo(() => { }) => {
return <Markdown className={cn(item.isError && '!text-[#F04438]')} content={content} /> const {
}, [content]) annotation,
if (annotation?.logAnnotation) return <Markdown content={annotation?.logAnnotation.content || ''} /> content,
return Mark } = item
if (annotation?.logAnnotation)
return <Markdown content={annotation?.logAnnotation.content || ''} />
return (
<Markdown
className={cn(
item.isError && '!text-[#F04438]',
)}
content={content}
/>
)
} }
export default memo(BasicContent) const MemoizedBasicContent = memo(BasicContent, (prev, next) => {
return (
prev.item.content === next.item.content &&
prev.item.annotation?.logAnnotation?.content === next.item.annotation?.logAnnotation?.content
)
})
export default MemoizedBasicContent
...@@ -140,4 +140,11 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re ...@@ -140,4 +140,11 @@ const Answer: FC<AnswerProps> = ({ item, question, index, config, answerIcon, re
) )
} }
export default memo(Answer) const AnswerMemo = memo(Answer,(prevProps: AnswerProps, nextProps: AnswerProps) => {
return (
prevProps.item.content === nextProps.item.content &&
prevProps.isLast === nextProps.isLast &&
prevProps.responding === nextProps.responding
)
})
export default AnswerMemo
import type { FC, ReactNode } from 'react' import type { FC, ReactNode } from 'react'
import { memo } from 'react' import { memo, useMemo } from 'react'
import type { ChatItem } from '../../types' import type { ChatConfig, ChatItem } from '../../types'
import BasicContent from './basic-content' import BasicContent from './basic-content'
import SuggestedQuestions from './suggested-questions' import SuggestedQuestions from './suggested-questions'
// import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item"; // import { EditTitle } from "@/app/components/app/annotation/edit-annotation-modal/edit-item";
import AnswerIcon from '@/app/components/base/answer-icon' import AnswerIcon from '@/app/components/base/answer-icon'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
type InitQuestionsProps = { type InitQuestionsProps = {
item: ChatItem config: ChatConfig
answerIcon: ReactNode answerIcon: ReactNode
chatAnswerContainerInner?: string chatAnswerContainerInner?: string
} }
const InitQuestions: FC<InitQuestionsProps> = ({ item, answerIcon, chatAnswerContainerInner }) => { const InitQuestions: FC<InitQuestionsProps> = ({ config, answerIcon, chatAnswerContainerInner }) => {
const { content, suggestedQuestions } = item const questions = useMemo(() => {
const { suggested_questions, initial_message } = config
const suggestedQuestions = suggested_questions
?.filter(q => !!q && q.trim())
.sort(() => Math.random() - 0.5)
.slice(0, 3)
const initQuestions: ChatItem = {
content: initial_message || '',
suggestedQuestions,
isAnswer: true,
id: 'initial_message',
}
return initQuestions
}, [config.initial_message])
return ( return (
<div className="mb-2 flex last:mb-0"> <div className="mb-2 flex last:mb-0">
<div className="relative h-10 w-10 shrink-0"> <div className="relative h-10 w-10 shrink-0">{answerIcon || <AnswerIcon imageUrl={''} />}</div>
{answerIcon || <AnswerIcon imageUrl={''} />}
</div>
<div className="chat-answer-container group ml-4 w-0 grow pb-2"> <div className="chat-answer-container group ml-4 w-0 grow pb-2">
<div className={cn('group relative pr-14', chatAnswerContainerInner)}> <div className={cn('group relative pr-14', chatAnswerContainerInner)}>
<div className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary')}> <div className={cn('body-lg-regular relative inline-block max-w-full rounded-2xl bg-chat-bubble-bg px-4 py-3 text-text-primary')}>
{content && <BasicContent item={item} />} {<BasicContent item={questions} />}
{suggestedQuestions && <SuggestedQuestions item={item} />} {<SuggestedQuestions item={questions} />}
</div> </div>
</div> </div>
</div> </div>
...@@ -30,4 +41,8 @@ const InitQuestions: FC<InitQuestionsProps> = ({ item, answerIcon, chatAnswerCon ...@@ -30,4 +41,8 @@ const InitQuestions: FC<InitQuestionsProps> = ({ item, answerIcon, chatAnswerCon
) )
} }
export default memo(InitQuestions) const MemoInitQuestions = memo(InitQuestions, (prev, next) => {
return prev.config.initial_message === next.config.initial_message && prev.config.suggested_questions?.length === next.config.suggested_questions?.length
})
export default MemoInitQuestions
import type { FC } from 'react' import type { FC } from 'react'
import { memo, useMemo, useState } from 'react' import { memo, useCallback, useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { RiClipboardLine, RiEditLine, RiResetLeftLine, RiThumbDownLine, RiThumbUpLine } from '@remixicon/react' import { RiClipboardLine, RiEditLine, RiResetLeftLine, RiThumbDownLine, RiThumbUpLine } from '@remixicon/react'
import type { ChatItem } from '../../types' import type { ChatItem } from '../../types'
import { useChatContext } from '../context' import { useChatContext } from '../context'
import copy from 'copy-to-clipboard' import copy from 'copy-to-clipboard'
import Toast from '@/app/components/base/toast' import Toast from '@/app/components/base/toast'
// import EditReplyModal from "@/app/components/app/annotation/edit-annotation-modal";
import Log from '@/app/components/base/chat/chat/log' import Log from '@/app/components/base/chat/chat/log'
import ActionButton, { ActionButtonState } from '@/app/components/base/action-button' import ActionButton, { ActionButtonState } from '@/app/components/base/action-button'
import NewAudioButton from '@/app/components/base/new-audio-button' import NewAudioButton from '@/app/components/base/new-audio-button'
...@@ -23,32 +22,74 @@ type OperationProps = { ...@@ -23,32 +22,74 @@ type OperationProps = {
hasWorkflowProcess: boolean hasWorkflowProcess: boolean
noChatInput?: boolean noChatInput?: boolean
} }
const Operation: FC<OperationProps> = ({ item, isLast, question, index, showPromptLog, maxSize, contentWidth, hasWorkflowProcess, noChatInput }) => { const Operation: FC<OperationProps> = ({ item, isLast, question, index, showPromptLog, maxSize, contentWidth, hasWorkflowProcess, noChatInput }) => {
const { t } = useTranslation() const { t } = useTranslation()
const { config, onAnnotationAdded, onAnnotationEdited, onAnnotationRemoved, onFeedback, onRegenerate } = useChatContext() const { config, onAnnotationAdded, onAnnotationEdited, onAnnotationRemoved, onFeedback, onRegenerate } = useChatContext()
const [isShowReplyModal, setIsShowReplyModal] = useState(false) const [isShowReplyModal, setIsShowReplyModal] = useState(false)
const [showLike, setShowLike] = useState(false) const [showLike, setShowLike] = useState(false)
const { id, isOpeningStatement, content: messageContent, annotation, feedback, adminFeedback, agent_thoughts } = item const { id, isOpeningStatement, content: messageContent, annotation, feedback, adminFeedback, agent_thoughts } = item
const [localFeedback, setLocalFeedback] = useState(config?.supportAnnotation ? adminFeedback : feedback) const [localFeedback, setLocalFeedback] = useState(config?.supportAnnotation ? adminFeedback : feedback)
// 计算内容
const content = useMemo(() => { const content = useMemo(() => {
if (agent_thoughts?.length) return agent_thoughts.reduce((acc, cur) => acc + cur.thought, '') if (agent_thoughts?.length) return agent_thoughts.reduce((acc, cur) => acc + cur.thought, '')
return messageContent return messageContent
}, [agent_thoughts, messageContent]) }, [agent_thoughts, messageContent])
// 判断反馈按钮是否启用
const feedbackEnabled = useMemo(() => config?.supportFeedback && !localFeedback?.rating && onFeedback && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement])
// 判断是否已点赞
const feedbackActive = useMemo(() => config?.supportFeedback && localFeedback?.rating && onFeedback && !isOpeningStatement, [config?.supportFeedback, localFeedback?.rating, onFeedback, isOpeningStatement])
// 处理反馈
const handleFeedback = async (rating: 'like' | 'dislike' | null) => { const handleFeedback = async (rating: 'like' | 'dislike' | null) => {
if (!config?.supportFeedback || !onFeedback || showLike) return if (!config?.supportFeedback || !onFeedback || showLike) return
try {
setShowLike(true) setShowLike(true)
await onFeedback?.(id, { rating }) await onFeedback(id, { rating })
setShowLike(false)
setLocalFeedback({ rating }) setLocalFeedback({ rating })
Toast.notify({ Toast.notify({ type: 'success', message: '成功' })
type: 'success', } catch (error) {
message: '成功', Toast.notify({ type: 'error', message: '反馈失败,请稍后再试' })
}) console.error('Feedback error:', error)
} finally {
setShowLike(false)
} }
}
// 反馈按钮组件
const FeedbackButtons = () => (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
<ActionButton onClick={() => handleFeedback('like')}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
<ActionButton onClick={() => handleFeedback('dislike')}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
</div>
)
// 已点赞按钮组件
const ActiveFeedbackButton = () => (
<div className="ml-1 flex items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm">
{localFeedback?.rating === 'like' && (
<ActionButton state={ActionButtonState.Active} onClick={() => handleFeedback(null)}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
)}
{localFeedback?.rating === 'dislike' && (
<ActionButton state={ActionButtonState.Destructive} onClick={() => handleFeedback(null)}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
)}
</div>
)
// 计算操作区域宽度
const operationWidth = useMemo(() => { const operationWidth = useMemo(() => {
let width = 0 let width = 0
if (!isOpeningStatement) width += 26 if (!isOpeningStatement) width += 26
...@@ -60,27 +101,23 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -60,27 +101,23 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
return width return width
}, [isOpeningStatement, showPromptLog, config?.text_to_speech?.enabled, config?.supportAnnotation, config?.annotation_reply?.enabled, config?.supportFeedback, localFeedback?.rating, onFeedback]) }, [isOpeningStatement, showPromptLog, config?.text_to_speech?.enabled, config?.supportAnnotation, config?.annotation_reply?.enabled, config?.supportFeedback, localFeedback?.rating, onFeedback])
// 判断位置是否靠左
const positionRight = useMemo(() => operationWidth < maxSize, [operationWidth, maxSize]) const positionRight = useMemo(() => operationWidth < maxSize, [operationWidth, maxSize])
return ( const OperationButtons = memo(() => {
<> const handleCopy = useCallback(() => {
<div className={cn('absolute flex justify-end gap-1', hasWorkflowProcess && '-bottom-4 right-2', !positionRight && '-bottom-4 right-2', !hasWorkflowProcess && positionRight && '!top-[9px]')} style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
{showPromptLog && !isOpeningStatement && (
<div className="hidden group-hover:block">
<Log logItem={item} />
</div>
)}
{!isOpeningStatement && (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
{config?.text_to_speech?.enabled && <NewAudioButton id={id} value={content} voice={config?.text_to_speech?.voice} />}
<ActionButton
onClick={() => {
copy(content) copy(content)
Toast.notify({ Toast.notify({
type: 'success', type: 'success',
message: '复制成功', message: '复制成功',
}) })
}}> }, [content])
return useMemo(
() => (
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex">
{config?.text_to_speech?.enabled && <NewAudioButton id={id} value={content} voice={config?.text_to_speech?.voice} />}
<ActionButton onClick={handleCopy}>
<RiClipboardLine className="h-4 w-4" /> <RiClipboardLine className="h-4 w-4" />
</ActionButton> </ActionButton>
{!noChatInput && isLast && ( {!noChatInput && isLast && (
...@@ -94,36 +131,31 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -94,36 +131,31 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
</ActionButton> </ActionButton>
)} )}
</div> </div>
)} ),
{!isOpeningStatement && config?.supportFeedback && !localFeedback?.rating && onFeedback && ( [config?.text_to_speech?.enabled, config?.supportAnnotation, config?.annotation_reply?.enabled, content, noChatInput, isLast, item, onRegenerate, handleCopy, setIsShowReplyModal],
<div className="ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm group-hover:flex"> )
{!localFeedback?.rating && ( })
return (
<> <>
<ActionButton onClick={() => handleFeedback('like')}> <div className={cn('absolute flex justify-end gap-1', hasWorkflowProcess && '-bottom-4 right-2', !positionRight && '-bottom-4 right-2', !hasWorkflowProcess && positionRight && '!top-[9px]', !hasWorkflowProcess && positionRight ? 'left-auto' : '')} style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}>
<RiThumbUpLine className="h-4 w-4" /> {/* 日志展示 */}
</ActionButton> {showPromptLog && !isOpeningStatement && (
<ActionButton onClick={() => handleFeedback('dislike')}> <div className="hidden group-hover:block">
<RiThumbDownLine className="h-4 w-4" /> <Log logItem={item} />
</ActionButton>
</>
)}
</div>
)}
{!isOpeningStatement && config?.supportFeedback && localFeedback?.rating && onFeedback && (
<div className="ml-1 flex items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-sm">
{localFeedback?.rating === 'like' && (
<ActionButton state={ActionButtonState.Active} onClick={() => handleFeedback(null)}>
<RiThumbUpLine className="h-4 w-4" />
</ActionButton>
)}
{localFeedback?.rating === 'dislike' && (
<ActionButton state={ActionButtonState.Destructive} onClick={() => handleFeedback(null)}>
<RiThumbDownLine className="h-4 w-4" />
</ActionButton>
)}
</div> </div>
)} )}
{/* 操作按钮容器 */}
{!isOpeningStatement && <OperationButtons />}
{/* 反馈按钮 */}
{feedbackEnabled && <FeedbackButtons />}
{/* 已点赞按钮 */}
{feedbackActive && <ActiveFeedbackButton />}
</div> </div>
{/* 注释掉的编辑回复模态框 */}
{/* <EditReplyModal {/* <EditReplyModal
isShow={isShowReplyModal} isShow={isShowReplyModal}
onHide={() => setIsShowReplyModal(false)} onHide={() => setIsShowReplyModal(false)}
...@@ -133,13 +165,7 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -133,13 +165,7 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
onAnnotationEdited?.(editedQuery, editedAnswer, index) onAnnotationEdited?.(editedQuery, editedAnswer, index)
} }
onAdded={(annotationId, authorName, editedQuery, editedAnswer) => onAdded={(annotationId, authorName, editedQuery, editedAnswer) =>
onAnnotationAdded?.( onAnnotationAdded?.(annotationId, authorName, editedQuery, editedAnswer, index)
annotationId,
authorName,
editedQuery,
editedAnswer,
index
)
} }
appId={config?.appId || ""} appId={config?.appId || ""}
messageId={id} messageId={id}
...@@ -151,4 +177,7 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm ...@@ -151,4 +177,7 @@ const Operation: FC<OperationProps> = ({ item, isLast, question, index, showProm
) )
} }
export default memo(Operation) // 自定义比较函数,只比较关键 props
const areEqual = (prev: OperationProps, next: OperationProps) => prev.showPromptLog === next.showPromptLog && prev.maxSize === next.maxSize && prev.isLast === next.isLast && prev.contentWidth === next.contentWidth && prev.hasWorkflowProcess === next.hasWorkflowProcess && prev.noChatInput === next.noChatInput
export default memo(Operation, areEqual)
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-06-23 15:51:59 * @LastEditTime: 2025-06-26 10:32:55
* @FilePath: \ai-assistant\app\components\base\chat\chat\answer\suggested-questions.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\answer\suggested-questions.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
...@@ -33,4 +33,8 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => { ...@@ -33,4 +33,8 @@ const SuggestedQuestions: FC<SuggestedQuestionsProps> = ({ item }) => {
) )
} }
export default memo(SuggestedQuestions) const MemoizedSuggestedQuestions = memo(SuggestedQuestions, (prev, next) => {
return prev.item.suggestedQuestions?.length === next.item.suggestedQuestions?.length
})
export default MemoizedSuggestedQuestions
...@@ -17,11 +17,6 @@ import { useToastContext } from '@/app/components/base/toast' ...@@ -17,11 +17,6 @@ import { useToastContext } from '@/app/components/base/toast'
import FeatureBar from '@/app/components/base/features/new-feature-panel/feature-bar' import FeatureBar from '@/app/components/base/features/new-feature-panel/feature-bar'
import type { FileUpload } from '@/app/components/base/features/types' import type { FileUpload } from '@/app/components/base/features/types'
import { TransferMethod } from '@/types/app' import { TransferMethod } from '@/types/app'
import {
// SELF_INPUT,
SEND_BUTTON,
CLEAR_BUTTON,
} from '@/app/components/base/chat/constants'
import { InputMessageType } from '../../types' import { InputMessageType } from '../../types'
type ChatInputAreaProps = { type ChatInputAreaProps = {
...@@ -138,24 +133,26 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF ...@@ -138,24 +133,26 @@ const ChatInputArea = ({ showFeatureBar, showFileUpload, featureBarDisabled, onF
) )
}, [t, notify]) }, [t, notify])
const operation = <Operation ref={holdSpaceRef} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onSend={handleSend} imgUrl={SEND_BUTTON} theme={theme} /> const operation = <Operation ref={holdSpaceRef} fileConfig={visionConfig} speechToTextConfig={speechToTextConfig} onShowVoiceInput={handleShowVoiceInput} onClear={handleClear} onSend={handleSend} theme={theme} />
const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} /> // const clear = <Operation ref={holdSpaceRef} onSend={handleClear} imgUrl={CLEAR_BUTTON} />
const hasQuery = useMemo(() => query.length > 0, [query]) const hasQuery = useMemo(() => query.length > 0, [query])
const maxRow = useMemo(() => {
if (hasQuery) { useEffect(() => {
return undefined if (!hasQuery) {
}
setIsMultipleLine(false) setIsMultipleLine(false)
return 1 }
}, [hasQuery, setIsMultipleLine]) }, [hasQuery, setIsMultipleLine])
const maxRow = useMemo(() => {
return hasQuery ? undefined : 1
}, [hasQuery])
return ( return (
<> <>
<div className={cn('relative z-10 rounded-xl border border-components-chat-input-border bg-[#fff] pb-[9px] shadow-md', isDragActive && 'border border-dashed border-components-option-card-option-selected-border')}> <div className={cn('relative z-10 rounded-xl border border-components-chat-input-border bg-[#fff] pb-[9px] shadow-md', isDragActive && 'border border-dashed border-components-option-card-option-selected-border')}>
<div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]"> <div className="relative max-h-[158px] overflow-y-auto overflow-x-hidden px-[9px] pt-[9px]">
<FileListInChatInput fileConfig={visionConfig!} /> <FileListInChatInput fileConfig={visionConfig!} />
<div ref={wrapperRef} className="flex items-center justify-between"> <div ref={wrapperRef} className="flex items-center justify-between">
<div className="relative flex w-full grow items-center"> <div className="relative flex w-full grow items-center ml-8">
{clear}
<div ref={textValueRef} className="body-lg-regular pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6"> <div ref={textValueRef} className="body-lg-regular pointer-events-none invisible absolute h-auto w-auto whitespace-pre p-1 leading-6">
{query} {query}
</div> </div>
......
import { memo } from "react"; import { memo, use, useMemo } from "react";
import { RiMicLine, RiSendPlane2Fill } from "@remixicon/react"; import { RiMicLine, RiSendPlane2Fill } from "@remixicon/react";
import type { EnableType } from "../../types"; import type { EnableType } from "../../types";
import type { Theme } from "../../embedded-chatbot/theme/theme-context"; import type { Theme } from "../../embedded-chatbot/theme/theme-context";
...@@ -7,7 +7,11 @@ import ActionButton from "@/app/components/base/action-button"; ...@@ -7,7 +7,11 @@ import ActionButton from "@/app/components/base/action-button";
import { FileUploaderInChatInput } from "@/app/components/base/file-uploader"; import { FileUploaderInChatInput } from "@/app/components/base/file-uploader";
import type { FileUpload } from "@/app/components/base/features/types"; import type { FileUpload } from "@/app/components/base/features/types";
import cn from "@/utils/classnames"; import cn from "@/utils/classnames";
import {
// SELF_INPUT,
SEND_BUTTON,
CLEAR_BUTTON,
} from '@/app/components/base/chat/constants'
type OperationProps = { type OperationProps = {
fileConfig?: FileUpload; fileConfig?: FileUpload;
speechToTextConfig?: EnableType; speechToTextConfig?: EnableType;
...@@ -15,18 +19,28 @@ type OperationProps = { ...@@ -15,18 +19,28 @@ type OperationProps = {
onSend: () => void; onSend: () => void;
imgUrl?: string; imgUrl?: string;
theme?: Theme | null; theme?: Theme | null;
onClear: () => void;
}; };
const Operation = ({ const Operation = ({
ref, ref,
onSend, onSend,
imgUrl,
speechToTextConfig, speechToTextConfig,
onShowVoiceInput, onShowVoiceInput,
onClear,
}: OperationProps & { }: OperationProps & {
ref: React.RefObject<HTMLDivElement>; ref: React.RefObject<HTMLDivElement>;
}) => { }) => {
return ( return (
<div className={cn("flex shrink-0 items-center justify-end")}> <div className={cn("flex shrink-0 items-center justify-end")}>
<div className="absolute left-3">
<img
onClick={onClear}
src={CLEAR_BUTTON}
className="size-6 hover:cursor-pointer"
alt="icon"
/>
</div>
<div className="flex items-center pl-1" ref={ref}> <div className="flex items-center pl-1" ref={ref}>
<div className='flex items-center space-x-1 pr-2'> <div className='flex items-center space-x-1 pr-2'>
{/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */} {/* {fileConfig?.enabled && <FileUploaderInChatInput fileConfig={fileConfig} />} */}
...@@ -41,14 +55,12 @@ const Operation = ({ ...@@ -41,14 +55,12 @@ const Operation = ({
) )
} }
</div> </div>
{imgUrl && (
<img <img
onClick={onSend} onClick={onSend}
src={imgUrl} src={SEND_BUTTON}
className="size-6 hover:cursor-pointer" className="size-6 hover:cursor-pointer"
alt="icon" alt="icon"
/> />
)}
</div> </div>
</div> </div>
); );
......
import React, { FC, memo, useEffect, useMemo } from 'react' import React, { FC, memo } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import type { ChatConfig, InputMessageProp, OnSend } from '../types' import type { ChatConfig, OnSend } from '@/app/components/base/chat/types'
import { useChatWithHistoryContext } from '../chat-with-history/context' import type { ThemeBuilder } from '@/app/components/base/chat/embedded-chatbot/theme/theme-context'
import type { ThemeBuilder } from '../embedded-chatbot/theme/theme-context' import type { InputForm } from '@/app/components/base/chat/chat/type'
import type { InputForm } from './type'
import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import TryToAsk from './try-to-ask' import TryToAsk from './try-to-ask'
import Practice from './practice' import Practice from './practice'
import ChatInputArea from './chat-input-area' import ChatInputArea from '../chat-input-area'
import StopResponding from './stopResponding'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
type FooterProps = { type FooterProps = {
chatFooterClassName?: string chatFooterClassName?: string
...@@ -16,7 +14,6 @@ type FooterProps = { ...@@ -16,7 +14,6 @@ type FooterProps = {
isShowPracticeButton: boolean isShowPracticeButton: boolean
suggestedQuestions?: string[] suggestedQuestions?: string[]
onSend: OnSend onSend: OnSend
// isResponding?: boolean
noStopResponding?: boolean noStopResponding?: boolean
onStopResponding?: () => void onStopResponding?: () => void
noChatInput?: boolean noChatInput?: boolean
...@@ -32,12 +29,10 @@ type FooterProps = { ...@@ -32,12 +29,10 @@ type FooterProps = {
config?: ChatConfig config?: ChatConfig
chatFooterRef: React.RefObject<HTMLDivElement> chatFooterRef: React.RefObject<HTMLDivElement>
chatFooterInnerRef: React.RefObject<HTMLDivElement> chatFooterInnerRef: React.RefObject<HTMLDivElement>
handleSend: OnSend
isResponding?: boolean isResponding?: boolean
} }
useEffect const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onClear, inputs, inputsForm, themeBuilder, config, suggestedQuestions, isShowPracticeButton, chatFooterRef, chatFooterInnerRef, isResponding }) => {
const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName, onSend, noStopResponding, onStopResponding, noChatInput, isMobile, inputDisabled, showFeatureBar, showFileUpload, onFeatureBarClick, onClear, inputs, inputsForm, themeBuilder, config, suggestedQuestions, isShowPracticeButton, handleSend, chatFooterRef, chatFooterInnerRef, isResponding }) => {
const { t } = useTranslation() const { t } = useTranslation()
const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend const hasTryToAsk = config?.suggested_questions_after_answer?.enabled && !!suggestedQuestions?.length && onSend
return ( return (
...@@ -45,20 +40,16 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName ...@@ -45,20 +40,16 @@ const Footer: FC<FooterProps> = ({ chatFooterClassName, chatFooterInnerClassName
<div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}> <div ref={chatFooterInnerRef} className={cn('relative', chatFooterInnerClassName)}>
<div className="mb-2 flex items-center justify-between relative h-8"> <div className="mb-2 flex items-center justify-between relative h-8">
{isShowPracticeButton && <Practice question={t('appDebug.feature.practice.text')} onSend={onSend} />} {isShowPracticeButton && <Practice question={t('appDebug.feature.practice.text')} onSend={onSend} />}
{isResponding && !noStopResponding && ( {isResponding && !noStopResponding && <StopResponding onStopResponding={onStopResponding} />}
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={onStopResponding}>
<StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" />
<span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span>
</Button>
</div>
)}
</div> </div>
{hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />} {hasTryToAsk && <TryToAsk suggestedQuestions={suggestedQuestions} onSend={onSend} isMobile={isMobile} />}
{!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={handleSend} onClear={onClear} inputs={inputs} inputsForm={inputsForm} theme={themeBuilder?.theme} isResponding={isResponding} />} {!noChatInput && <ChatInputArea disabled={inputDisabled} showFeatureBar={showFeatureBar} showFileUpload={showFileUpload} featureBarDisabled={isResponding} onFeatureBarClick={onFeatureBarClick} visionConfig={config?.file_upload} speechToTextConfig={config?.speech_to_text} onSend={onSend} onClear={onClear} inputs={inputs} inputsForm={inputsForm} theme={themeBuilder?.theme} isResponding={isResponding} />}
</div> </div>
</div> </div>
) )
} }
const MemoFooter = memo(Footer, (prevProps, nextProps) => {
return prevProps.isResponding === nextProps.isResponding
})
export default memo(Footer) export default MemoFooter
import type { FC } from 'react' import type { FC } from 'react'
import { memo } from 'react' import { memo } from 'react'
import type { OnSend } from '../types' import type { OnSend } from '@/app/components/base/chat/types'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import cn from '@/utils/classnames' import { InputMessageType } from '@/app/components/base/chat/types'
import { InputMessageType } from '../types'
import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons' import { Practice as PracticeIcon } from '@/app/components/base/icons/src/image/icons'
type PracticeProps = { type PracticeProps = {
question: string question: string
...@@ -33,4 +32,6 @@ const Practice: FC<PracticeProps> = ({ question, onSend }) => { ...@@ -33,4 +32,6 @@ const Practice: FC<PracticeProps> = ({ question, onSend }) => {
) )
} }
export default memo(Practice) const PracticeMemo = memo(Practice)
export default PracticeMemo
import { FC, memo } from 'react'
import Button from '@/app/components/base/button'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { useTranslation } from 'react-i18next'
interface StopButtonProps {
onStopResponding?: () => void
}
const StopRespondingButton: FC<StopButtonProps> = ({ onStopResponding }) => {
const { t } = useTranslation()
return (
<div className="absolute left-1/2 top-1/2 transform -translate-x-1/2 -translate-y-1/2">
<Button onClick={onStopResponding}>
<StopCircle className="mr-[5px] h-3.5 w-3.5 text-gray-500" />
<span className="text-xs font-normal text-gray-500">{t('appDebug.operation.stopResponding')}</span>
</Button>
</div>
)
}
const MemoizedStopRespondingButton = memo(StopRespondingButton, (prev, next) => true)
export default MemoizedStopRespondingButton
import type { FC } from 'react' import type { FC } from 'react'
import { memo } from 'react' import { memo } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import type { OnSend } from '../types' import type { OnSend } from '@/app/components/base/chat/types'
import Button from '@/app/components/base/button' import Button from '@/app/components/base/button'
import Divider from '@/app/components/base/divider' import Divider from '@/app/components/base/divider'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { InputMessageType } from '../types' import { InputMessageType } from '@/app/components/base/chat/types'
type TryToAskProps = { type TryToAskProps = {
suggestedQuestions: string[] suggestedQuestions: string[]
onSend: OnSend onSend: OnSend
......
...@@ -2,12 +2,12 @@ ...@@ -2,12 +2,12 @@
* @Author: yangming@didihu.com.cn yangming@didihu.com.cn * @Author: yangming@didihu.com.cn yangming@didihu.com.cn
* @Date: 2025-04-22 09:29:17 * @Date: 2025-04-22 09:29:17
* @LastEditors: limin * @LastEditors: limin
* @LastEditTime: 2025-06-25 21:09:44 * @LastEditTime: 2025-06-26 10:20:23
* @FilePath: \ai-assistant\app\components\base\chat\chat\question.tsx * @FilePath: \ai-assistant\app\components\base\chat\chat\question.tsx
* @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
*/ */
import type { FC, ReactNode } from 'react' import type { FC, ReactNode } from 'react'
import { memo, useMemo } from 'react' import { memo } from 'react'
import type { ChatItem } from '../types' import type { ChatItem } from '../types'
import type { Theme } from '../embedded-chatbot/theme/theme-context' import type { Theme } from '../embedded-chatbot/theme/theme-context'
import { CssTransform } from '../embedded-chatbot/theme/utils' import { CssTransform } from '../embedded-chatbot/theme/utils'
...@@ -22,7 +22,6 @@ type QuestionProps = { ...@@ -22,7 +22,6 @@ type QuestionProps = {
} }
const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => { const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => {
const { content, message_files } = item const { content, message_files } = item
const question= useMemo(() => {
return ( return (
<div className="mb-2 flex justify-end pl-14 last:mb-0"> <div className="mb-2 flex justify-end pl-14 last:mb-0">
<div className="group relative mr-4 max-w-full"> <div className="group relative mr-4 max-w-full">
...@@ -35,8 +34,9 @@ const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => { ...@@ -35,8 +34,9 @@ const Question: FC<QuestionProps> = ({ item, questionIcon, theme }) => {
<div className="h-10 w-10 shrink-0">{questionIcon}</div> <div className="h-10 w-10 shrink-0">{questionIcon}</div>
</div> </div>
) )
},[content, message_files])
return question
} }
const QuestionMemo = memo(Question, (prev, next) => {
export default memo(Question) return prev.item.content === next.item.content &&
prev.item.message_files?.length === next.item.message_files?.length
})
export default QuestionMemo
import { useCallback, useEffect, useRef, useState } from 'react' import { useCallback, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next' import { useTranslation } from 'react-i18next'
import { useParams, usePathname } from 'next/navigation' import { useParams, usePathname } from 'next/navigation'
import { import { RiCloseLine, RiLoader2Line } from '@remixicon/react'
RiCloseLine,
RiLoader2Line,
} from '@remixicon/react'
import Recorder from 'js-audio-recorder' import Recorder from 'js-audio-recorder'
import { useRafInterval } from 'ahooks' import { useRafInterval } from 'ahooks'
import { convertToMp3 } from './utils' import { convertToMp3 } from './utils'
...@@ -12,6 +9,7 @@ import s from './index.module.css' ...@@ -12,6 +9,7 @@ import s from './index.module.css'
import cn from '@/utils/classnames' import cn from '@/utils/classnames'
import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices' import { StopCircle } from '@/app/components/base/icons/src/vender/solid/mediaAndDevices'
import { audioToText } from '@/service/share' import { audioToText } from '@/service/share'
import { set } from 'immer/dist/internal'
type VoiceInputTypes = { type VoiceInputTypes = {
onConverted: (text: string) => void onConverted: (text: string) => void
...@@ -19,18 +17,17 @@ type VoiceInputTypes = { ...@@ -19,18 +17,17 @@ type VoiceInputTypes = {
wordTimestamps?: string wordTimestamps?: string
} }
const VoiceInput = ({ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes) => {
onCancel,
onConverted,
wordTimestamps,
}: VoiceInputTypes) => {
const { t } = useTranslation() const { t } = useTranslation()
const recorder = useRef(new Recorder({ // const recorder = useRef(
sampleBits: 16, // new Recorder({
sampleRate: 16000, // sampleBits: 16,
numChannels: 1, // sampleRate: 16000,
compiling: false, // numChannels: 1,
})) // compiling: false,
// }),
// )
const canvasRef = useRef<HTMLCanvasElement | null>(null) const canvasRef = useRef<HTMLCanvasElement | null>(null)
const ctxRef = useRef<CanvasRenderingContext2D | null>(null) const ctxRef = useRef<CanvasRenderingContext2D | null>(null)
const drawRecordId = useRef<number | null>(null) const drawRecordId = useRef<number | null>(null)
...@@ -42,12 +39,13 @@ const VoiceInput = ({ ...@@ -42,12 +39,13 @@ const VoiceInput = ({
const clearInterval = useRafInterval(() => { const clearInterval = useRafInterval(() => {
setOriginDuration(originDuration + 1) setOriginDuration(originDuration + 1)
}, 1000) }, 1000)
const [recorder, setRecorder] = useState<Recorder | null>(null)
const drawRecord = useCallback(() => { const drawRecord = useCallback(() => {
if (!recorder) return
drawRecordId.current = requestAnimationFrame(drawRecord) drawRecordId.current = requestAnimationFrame(drawRecord)
const canvas = canvasRef.current! const canvas = canvasRef.current!
const ctx = ctxRef.current! const ctx = ctxRef.current!
const dataUnit8Array = recorder.current.getRecordAnalyseData() const dataUnit8Array = recorder.getRecordAnalyseData()
const dataArray = [].slice.call(dataUnit8Array) const dataArray = [].slice.call(dataUnit8Array)
const lineLength = Number.parseInt(`${canvas.width / 3}`) const lineLength = Number.parseInt(`${canvas.width / 3}`)
const gap = Number.parseInt(`${1024 / lineLength}`) const gap = Number.parseInt(`${1024 / lineLength}`)
...@@ -56,37 +54,42 @@ const VoiceInput = ({ ...@@ -56,37 +54,42 @@ const VoiceInput = ({
ctx.beginPath() ctx.beginPath()
let x = 0 let x = 0
for (let i = 0; i < lineLength; i++) { for (let i = 0; i < lineLength; i++) {
let v = dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => { let v =
dataArray.slice(i * gap, i * gap + gap).reduce((prev: number, next: number) => {
return prev + next return prev + next
}, 0) / gap }, 0) / gap
if (v < 128) if (v < 128) v = 128
v = 128 if (v > 178) v = 178
if (v > 178) const y = ((v - 128) / 50) * canvas.height
v = 178
const y = (v - 128) / 50 * canvas.height
ctx.moveTo(x, 16) ctx.moveTo(x, 16)
if (ctx.roundRect) if (ctx.roundRect) ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0])
ctx.roundRect(x, 16 - y, 2, y, [1, 1, 0, 0]) else ctx.rect(x, 16 - y, 2, y)
else
ctx.rect(x, 16 - y, 2, y)
ctx.fill() ctx.fill()
x += 3 x += 3
} }
ctx.closePath() ctx.closePath()
}, []) }, [])
const handleStopRecorder = useCallback(async () => { const handleStopRecorder = useCallback(async () => {
if (!recorder) return
clearInterval() clearInterval()
recorder.stop()
setStartRecord(false) setStartRecord(false)
setStartConvert(true) setStartConvert(true)
recorder.current.stop() setOriginDuration(0)
drawRecordId.current && cancelAnimationFrame(drawRecordId.current) drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
drawRecordId.current = null drawRecordId.current = null
const canvas = canvasRef.current! const canvas = canvasRef.current!
const ctx = ctxRef.current! const ctx = ctxRef.current!
ctx.clearRect(0, 0, canvas.width, canvas.height) ctx.clearRect(0, 0, canvas.width, canvas.height)
const mp3Blob = convertToMp3(recorder.current) const mp3Blob = convertToMp3(recorder)
if (!mp3Blob.size) {
console.error('音频数据为空')
onConverted('')
onCancel()
return
}
const mp3File = new File([mp3Blob], 'temp.mp3', { type: 'audio/mp3' }) const mp3File = new File([mp3Blob], 'temp.mp3', { type: 'audio/mp3' })
const formData = new FormData() const formData = new FormData()
formData.append('file', mp3File) formData.append('file', mp3File)
...@@ -98,34 +101,42 @@ const VoiceInput = ({ ...@@ -98,34 +101,42 @@ const VoiceInput = ({
if (params.token) { if (params.token) {
url = '/audio-to-text' url = '/audio-to-text'
isPublic = true isPublic = true
} } else if (params.appId) {
else if (params.appId) { if (pathname.search('explore/installed') > -1) url = `/installed-apps/${params.appId}/audio-to-text`
if (pathname.search('explore/installed') > -1) else url = `/apps/${params.appId}/audio-to-text`
url = `/installed-apps/${params.appId}/audio-to-text`
else
url = `/apps/${params.appId}/audio-to-text`
} }
try { try {
const audioResponse = await audioToText(url, isPublic, formData) const audioResponse = await audioToText(url, isPublic, formData)
onConverted(audioResponse.text) onConverted(audioResponse.text)
onCancel() onCancel()
} } catch {
catch {
onConverted('') onConverted('')
onCancel() onCancel()
} }
}, [clearInterval, onCancel, onConverted, params.appId, params.token, pathname, wordTimestamps]) }, [clearInterval, onCancel, onConverted, params.appId, params.token, pathname, wordTimestamps])
const handleStartRecord = async () => { const handleStartRecord = async () => {
try { try {
await recorder.current.start() if (recorder) {
recorder.stop()
setRecorder(null)
}
const newRecorder = new Recorder({
sampleBits: 16,
sampleRate: 16000,
numChannels: 1,
compiling: false,
})
await newRecorder.start()
setRecorder(newRecorder)
setStartRecord(true) setStartRecord(true)
setStartConvert(false) setStartConvert(false)
if (canvasRef.current && ctxRef.current) if (canvasRef.current && ctxRef.current)
requestAnimationFrame(() => {
drawRecord() drawRecord()
} })
catch { } catch {
onCancel() onCancel()
} }
} }
...@@ -149,15 +160,29 @@ const VoiceInput = ({ ...@@ -149,15 +160,29 @@ const VoiceInput = ({
} }
} }
} }
if (originDuration >= 600 && startRecord) if (originDuration >= 600 && startRecord) handleStopRecorder()
handleStopRecorder()
useEffect(() => { useEffect(() => {
initCanvas() initCanvas()
handleStartRecord() const startRecording = async () => {
const recorderRef = recorder?.current try {
await handleStartRecord()
} catch (error) {
console.error('自动录音失败:', error)
onCancel()
}
}
startRecording()
// const recorderRef = recorder?.current
return () => { return () => {
recorderRef?.stop() recorder?.stop()
recorder?.destroy()
setRecorder(null)
clearInterval()
if (drawRecordId.current) {
cancelAnimationFrame(drawRecordId.current)
}
} }
}, []) }, [])
...@@ -166,47 +191,23 @@ const VoiceInput = ({ ...@@ -166,47 +191,23 @@ const VoiceInput = ({
return ( return (
<div className={cn(s.wrapper, 'absolute inset-0 rounded-xl')}> <div className={cn(s.wrapper, 'absolute inset-0 rounded-xl')}>
<div className='absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 py-[14px] pl-[14.5px] pr-[6.5px]'> <div className="absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 py-[14px] pl-[14.5px] pr-[6.5px]">
<canvas id='voice-input-record' className='absolute bottom-0 left-0 h-4 w-full' /> <canvas id="voice-input-record" className="absolute bottom-0 left-0 h-4 w-full" />
{ {startConvert && <RiLoader2Line className="mr-2 h-4 w-4 animate-spin text-primary-700" />}
startConvert && <RiLoader2Line className='mr-2 h-4 w-4 animate-spin text-primary-700' /> <div className="grow">
} {startRecord && <div className="text-sm text-gray-500">{t('common.voiceInput.speaking')}</div>}
<div className='grow'> {startConvert && <div className={cn(s.convert, 'text-sm')}>{t('common.voiceInput.converting')}</div>}
{
startRecord && (
<div className='text-sm text-gray-500'>
{t('common.voiceInput.speaking')}
</div>
)
}
{
startConvert && (
<div className={cn(s.convert, 'text-sm')}>
{t('common.voiceInput.converting')}
</div> </div>
) {startRecord && (
} <div className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100" onClick={handleStopRecorder}>
<StopCircle className="h-5 w-5 text-primary-600" />
</div> </div>
{ )}
startRecord && ( {startConvert && (
<div <div className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-gray-200" onClick={onCancel}>
className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100' <RiCloseLine className="h-4 w-4 text-gray-500" />
onClick={handleStopRecorder}
>
<StopCircle className='h-5 w-5 text-primary-600' />
</div> </div>
) )}
}
{
startConvert && (
<div
className='mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-gray-200'
onClick={onCancel}
>
<RiCloseLine className='h-4 w-4 text-gray-500' />
</div>
)
}
<div className={`w-[45px] pl-1 text-xs font-medium ${originDuration > 500 ? 'text-[#F04438]' : 'text-gray-700'}`}>{`0${minutes.toFixed(0)}:${seconds >= 10 ? seconds : `0${seconds}`}`}</div> <div className={`w-[45px] pl-1 text-xs font-medium ${originDuration > 500 ? 'text-[#F04438]' : 'text-gray-700'}`}>{`0${minutes.toFixed(0)}:${seconds >= 10 ? seconds : `0${seconds}`}`}</div>
</div> </div>
</div> </div>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!