Commit 3cdcb57c by liimin

refactor(voice-input): 优化语音输入组件

- 移除 SENTRY_DSN 配置项
- 使用 requestAnimationFrame 替代 setTimeout 调整文本域大小
- 重构 Voice 组件,使用 useCallback 优化性能
- 简化 MessageContext,移除不必要的回调函数
- 优化 VoiceInput 组件,调整录音逻辑和 UI
1 parent 0721eca8
......@@ -16,7 +16,7 @@
# NEXT_PUBLIC_MARKETPLACE_URL_PREFIX=https://marketplace.dify.ai
# SENTRY
NEXT_PUBLIC_SENTRY_DSN=https://90ddfaad2eac44f3b25cd4298ae7af14@sentry.glsx.com.cn/45
# NEXT_PUBLIC_SENTRY_DSN=https://90ddfaad2eac44f3b25cd4298ae7af14@sentry.glsx.com.cn/45
# Disable Next.js Telemetry (https://nextjs.org/telemetry)
# NEXT_TELEMETRY_DISABLED=1
......
......@@ -58,7 +58,7 @@ const TextInput: React.FC<{
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setQuery(e.target.value)
// setTimeout(handleTextareaResize, 0)
requestAnimationFrame(handleTextareaResize)
}
const hasQuery = useMemo(() => query.length > 0, [query])
......
import { FC, memo } from 'react'
import { FC, memo, useCallback } from 'react'
import VoiceInput from '@/app/components/base/voice-input'
import { useMessageContext, useVoiceInputContext } from '@/app/components/base/chat/chat/footer/context'
import {
useMessageContext,
useTextAreaHeightContext,
useVoiceInputContext,
} from '@/app/components/base/chat/chat/footer/context'
const Voice: FC = () => {
const { showVoiceInput, setShowVoiceInput } = useVoiceInputContext()
const { setQuery } = useMessageContext()
const { handleTextareaResize } = useTextAreaHeightContext()
const onConverted = useCallback((text: string) => {
setQuery(text)
requestAnimationFrame(handleTextareaResize)
}, [])
if (!showVoiceInput) return null
return <VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={text => setQuery(text)} />
setQuery('')
return <VoiceInput onCancel={() => setShowVoiceInput(false)} onConverted={onConverted} />
}
export default memo(Voice)
......@@ -6,7 +6,6 @@ import { TransferMethod } from '@/types/app'
import { useTranslation } from 'react-i18next'
import { InputMessageType } from '../../../types'
import { useChatContext, useChatRespondingContext } from '@/app/components/base/chat/chat-with-history/context/index'
import { useTextAreaHeightContext } from './textarea-height-context'
// 定义消息上下文类型
interface MessageContextType {
query: string
......@@ -31,13 +30,11 @@ export const useMessageContext = (): MessageContextType => {
// 消息提供者组件
export const MessageProvider = ({ children }: { children: ReactNode }) => {
const { t } = useTranslation()
const filesStore = useFileStore()
const { notify } = useToastContext()
const [query, setQuery] = useState('')
// const [isMultipleLine, setIsMultipleLine] = useState(false)
const { onSend: sendMessage } = useChatContext()
const { isResponding } = useChatRespondingContext()
const { handleTextareaResize } = useTextAreaHeightContext()
const { notify } = useToastContext()
const filesStore = useFileStore()
const handleSend = useCallback(() => {
if (isResponding) {
notify({
......@@ -69,19 +66,12 @@ export const MessageProvider = ({ children }: { children: ReactNode }) => {
}
}, [query, isResponding, sendMessage, filesStore, notify, t])
const handleSetQuery = useCallback((value: string) => {
setQuery(value)
setTimeout(handleTextareaResize, 0)
}, [])
// 提供上下文值
const value = useMemo(
() => ({
query,
setQuery: handleSetQuery,
setQuery,
handleSend,
// isMultipleLine,
// setIsMultipleLine,
}),
[query, handleSend],
)
......
......@@ -78,10 +78,6 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
const handleStopRecorder = useCallback(async () => {
clearInterval()
// setStartRecord(false)
// setStartConvert(true)
setStatement('converting')
// 修改点3: 安全访问recorder实例
if (recorder.current) {
recorder.current.stop()
drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
......@@ -119,35 +115,23 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
}
}, [clearInterval, onCancel, onConverted, params.appId, params.token, pathname, wordTimestamps])
const handleStop = useCallback(() => {
setStatement('converting')
setTimeout(handleStopRecorder, 0)
}, [handleStopRecorder])
const handleStartRecord = async () => {
try {
// 修改点4: 确保清理之前的录音实例
if (recorder.current) {
// if (recorder.current.isRecording) {
recorder.current.stop()
// }
recorder.current.destroy()
}
// 创建新的录音实例
resetRecorder()
recorder.current = createRecorder()
await recorder.current.start()
// setStartRecord(true)
// setStartConvert(false)
setStatement('recording')
setOriginDuration(0) // 重置录音时间
// 修改点5: 确保canvas正确初始化
initCanvas()
if (canvasRef.current && ctxRef.current) {
setTimeout(() => {
setOriginDuration(0) // 重置录音时间
initCanvas()
drawRecord()
} else {
console.error('Canvas or context not available')
}
}, 0)
} catch (e: any) {
console.error('Recording start error:', e)
alert(`录音启动失败: ${e.message || '请检查麦克风权限'}`)
onCancel()
}
}
......@@ -155,52 +139,44 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
const initCanvas = () => {
const dpr = window.devicePixelRatio || 1
const canvas = document.getElementById('voice-input-record') as HTMLCanvasElement
if (canvas) {
const { width: cssWidth, height: cssHeight } = canvas.getBoundingClientRect()
canvas.width = dpr * cssWidth
canvas.height = dpr * cssHeight
canvasRef.current = canvas
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.scale(dpr, dpr)
ctx.fillStyle = 'rgba(0, 0, 255, 0.6)'
ctxRef.current = ctx
} else {
console.error('Failed to get canvas context')
}
const { width: cssWidth, height: cssHeight } = canvas.getBoundingClientRect()
canvas.width = dpr * cssWidth
canvas.height = dpr * cssHeight
canvasRef.current = canvas
const ctx = canvas.getContext('2d')
if (ctx) {
ctx.scale(dpr, dpr)
ctx.fillStyle = 'rgba(30, 144, 255, 1)'
ctxRef.current = ctx
} else {
console.error('Canvas element not found')
console.error('Failed to get canvas context')
}
}
// 修改点6: 添加录音超时处理
useEffect(() => {
if (originDuration >= 600 && statement === 'recording') {
handleStopRecorder()
handleStop()
}
}, [originDuration, statement, handleStopRecorder])
}, [originDuration, statement, handleStop])
useEffect(() => {
handleStartRecord()
// 修改点7: 清理函数确保释放资源
return () => {
if (recorder.current) {
// if (recorder.current.isRecording) {
recorder.current.stop()
// }
recorder.current.destroy()
recorder.current = null
}
resetRecorder()
drawRecordId.current && cancelAnimationFrame(drawRecordId.current)
clearInterval()
}
}, [])
const resetRecorder = useCallback(() => {
if (recorder.current) {
recorder.current.stop()
recorder.current.destroy()
recorder.current = null
}
}, [])
const minutes = Math.floor(originDuration / 60)
const seconds = originDuration % 60
......@@ -208,7 +184,7 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
<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> */}
<div className="absolute inset-[1.5px] flex items-center overflow-hidden rounded-[10.5px] bg-primary-25 pl-[14.5px] pr-[6.5px]">
<canvas id="voice-input-record" className="absolute bottom-0 left-0 h-3 w-full" />
<canvas id="voice-input-record" className="absolute bottom-0 left-0 h-4 w-full" />
{statement === 'converting' && <RiLoader2Line className="mr-2 h-4 w-4 animate-spin text-primary-700" />}
<div className="grow">
{statement === 'recording' && <div className="text-sm text-gray-500">{t('common.voiceInput.speaking')}</div>}
......@@ -218,8 +194,8 @@ const VoiceInput = ({ onCancel, onConverted, wordTimestamps }: VoiceInputTypes)
</div>
{statement === 'recording' && (
<div
className="mr-1 flex h-8 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100"
onClick={handleStopRecorder}>
className="mr-1 flex h-10 w-8 cursor-pointer items-center justify-center rounded-lg hover:bg-primary-100"
onClick={handleStop}>
<StopCircle className="h-5 w-5 text-primary-600" />
</div>
)}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!