Spaces:
Running

axeronis
fix(ux): phase 7 final mobile polish - toggle, input, duplication, and deletion
abb8c3e
Raw History Blame Contribute Delete
15.1 kB
'use client'
import { cn } from '@/lib/utils'
import { Loader2, Paperclip, Send, Mic, X, Play, Pause } from 'lucide-react'
import { useRef, useState } from 'react'
import { motion, AnimatePresence } from 'framer-motion'
interface MessageInputProps {
value: string
onChange: (value: string) => void
onSubmit: (e: React.FormEvent, file?: File | null, audioBlob?: Blob | null) => void
isSending: boolean
disabled?: boolean
}
export function MessageInput({
value,
onChange,
onSubmit,
isSending,
disabled,
}: MessageInputProps) {
const fileInputRef = useRef<HTMLInputElement>(null)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [isRecording, setIsRecording] = useState(false)
const [pendingAudio, setPendingAudio] = useState<Blob | null>(null)
const [isPlayingPreview, setIsPlayingPreview] = useState(false)
const mediaRecorderRef = useRef<MediaRecorder | null>(null)
const streamRef = useRef<MediaStream | null>(null)
const chunksRef = useRef<Blob[]>([])
const audioPreviewRef = useRef<HTMLAudioElement | null>(null)
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
handleSubmit(e as unknown as React.FormEvent)
}
}
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (isRecording) {
handleSendVoice(e)
return
}
onSubmit(e, selectedFile, pendingAudio)
setSelectedFile(null)
setPendingAudio(null)
}
const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
if (e.target.files && e.target.files[0]) {
setSelectedFile(e.target.files[0])
setPendingAudio(null) // Clear audio if file selected
}
}
const isCancelledRef = useRef(false)
// Voice Recording Logic with Promise-based handling (to avoid race conditions)
const stopRecordingPromise = () => {
return new Promise<Blob | null>((resolve) => {
if (!mediaRecorderRef.current || !isRecording) {
resolve(null)
return
}
const mediaRecorder = mediaRecorderRef.current
const chunks: Blob[] = []
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) chunks.push(e.data)
}
mediaRecorder.onstop = () => {
if (isCancelledRef.current) {
isCancelledRef.current = false
resolve(null)
} else {
const blob = new Blob(chunks, { type: 'audio/webm' })
resolve(blob)
}
streamRef.current?.getTracks().forEach(track => track.stop())
streamRef.current = null
}
mediaRecorder.stop()
setIsRecording(false)
})
}
const startRecording = async () => {
isCancelledRef.current = false
try {
const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
streamRef.current = stream
const mediaRecorder = new MediaRecorder(stream)
mediaRecorderRef.current = mediaRecorder
chunksRef.current = []
// We handle data in the stop promise mostly, but this is backup
mediaRecorder.ondataavailable = (e) => {
if (e.data.size > 0) chunksRef.current.push(e.data)
}
// Normal stop (saving to pending)
mediaRecorder.onstop = () => {
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop())
streamRef.current = null
}
}
mediaRecorder.start()
setIsRecording(true)
} catch (err) {
console.error('Error accessing microphone:', err)
alert('Не удалось получить доступ к микрофону')
}
}
const handleSendVoice = async (e: React.BaseSyntheticEvent) => {
e.preventDefault()
e.stopPropagation()
if (!isRecording) return
isCancelledRef.current = false
const audioBlob = await stopRecordingPromise()
if (audioBlob) {
onSubmit(e as any, null, audioBlob)
}
}
const cancelRecording = () => {
if (mediaRecorderRef.current && isRecording) {
isCancelledRef.current = true
mediaRecorderRef.current.stop()
setIsRecording(false)
}
streamRef.current?.getTracks().forEach(track => track.stop())
streamRef.current = null
chunksRef.current = [] // Clear chunks
}
const clearPendingAudio = () => {
setPendingAudio(null)
if (audioPreviewRef.current) {
audioPreviewRef.current.pause()
audioPreviewRef.current = null
}
setIsPlayingPreview(false)
}
const toggleAudioPreview = () => {
if (!pendingAudio) return
if (!audioPreviewRef.current) {
audioPreviewRef.current = new Audio(URL.createObjectURL(pendingAudio))
audioPreviewRef.current.onended = () => setIsPlayingPreview(false)
}
if (isPlayingPreview) {
audioPreviewRef.current.pause()
setIsPlayingPreview(false)
} else {
audioPreviewRef.current.play()
setIsPlayingPreview(true)
}
}
return (
// Adjusted padding: pb-6 (safe area) + bottom nav is distinct
<div className="px-2 sm:px-3 pb-6 md:pb-6 pt-2 bg-[#050510]/60 backdrop-blur-xl border-t border-white/5 flex-shrink-0 relative z-30">
<div className="max-w-4xl mx-auto relative">
{/* File Preview */}
{selectedFile && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="mb-2 p-2 bg-[#050510]/80 backdrop-blur-xl rounded-xl border border-white/10 flex items-center gap-2 w-fit max-w-[calc(100%-20px)] shadow-lg"
>
<Paperclip className="w-4 h-4 text-indigo-400 shrink-0" />
<span className="text-xs text-white truncate">{selectedFile.name}</span>
<button onClick={() => setSelectedFile(null)} className="p-1 hover:bg-white/10 rounded-full">
<X className="w-3 h-3 text-slate-400" />
</button>
</motion.div>
)}
{/* Audio Preview */}
{pendingAudio && !isRecording && (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className="mb-2 p-2 bg-[#050510]/80 backdrop-blur-xl rounded-xl border border-indigo-500/30 flex items-center gap-2 w-fit shadow-lg"
>
<button
onClick={toggleAudioPreview}
className="w-8 h-8 rounded-full bg-indigo-500/20 flex items-center justify-center text-indigo-400 hover:bg-indigo-500/30"
>
{isPlayingPreview ? <Pause className="w-4 h-4" /> : <Play className="w-4 h-4 ml-0.5" />}
</button>
<span className="text-xs text-indigo-300 font-medium">🎤 Готовое сообщение</span>
<button onClick={clearPendingAudio} className="p-1 hover:bg-white/10 rounded-full">
<X className="w-3 h-3 text-slate-400" />
</button>
</motion.div>
)}
{/* Audio Recording UI */}
<AnimatePresence>
{isRecording && (
<motion.div
initial={{ opacity: 0, scale: 0.95 }}
animate={{ opacity: 1, scale: 1 }}
exit={{ opacity: 0, scale: 0.95 }}
className="absolute inset-0 bg-[#050510]/95 backdrop-blur-2xl rounded-2xl border border-red-500/30 flex items-center justify-between px-4 z-40 shadow-2xl"
>
<div className="flex items-center gap-3 text-red-400">
<div className="flex gap-1 items-end h-4">
<div className="w-1 bg-red-500 rounded-full animate-[voice-wave_1s_infinite_0s]" style={{ height: '60%' }} />
<div className="w-1 bg-red-500 rounded-full animate-[voice-wave_1s_infinite_0.2s]" style={{ height: '100%' }} />
<div className="w-1 bg-red-500 rounded-full animate-[voice-wave_1s_infinite_0.4s]" style={{ height: '40%' }} />
<div className="w-1 bg-red-500 rounded-full animate-[voice-wave_1s_infinite_0.1s]" style={{ height: '80%' }} />
</div>
<span className="text-sm font-bold tracking-tight">ЗАПИСЬ...</span>
</div>
<div className="flex items-center gap-3">
<button
type="button"
onClick={cancelRecording}
className="p-2.5 bg-white/5 text-slate-400 rounded-full hover:bg-white/10 hover:text-white transition-all active:scale-90"
title="Отменить"
>
<X className="w-5 h-5" />
</button>
{/* Send Button inside Recording UI */}
<button
type="button"
onClick={handleSendVoice}
className="p-2.5 bg-red-500/20 text-red-500 rounded-full hover:bg-red-500/30 transition-all active:scale-90 shadow-[0_0_15px_rgba(239,68,68,0.2)]"
title="Готово"
>
<Send className="w-5 h-5" />
</button>
</div>
</motion.div>
)}
</AnimatePresence>
<form
onSubmit={handleSubmit}
className="flex items-center gap-1.5 px-0.5 transition-all"
>
<input
type="file"
ref={fileInputRef}
onChange={handleFileSelect}
className="hidden"
accept="image/*,.pdf,.txt,.doc,.docx"
/>
<div className="flex items-center">
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className={cn(
"p-2.5 rounded-full transition-all active:scale-90",
selectedFile ? "text-indigo-400 bg-indigo-500/10" : "text-slate-400/60 hover:text-white hover:bg-white/5"
)}
>
<Paperclip className="w-5 h-5" />
</button>
<button
type="button"
onMouseDown={(e) => { e.preventDefault(); startRecording(); }}
onMouseUp={handleSendVoice}
onTouchStart={(e) => { e.preventDefault(); startRecording(); }}
onTouchEnd={handleSendVoice}
className={cn(
"p-2.5 rounded-full transition-all active:scale-95 touch-none select-none",
isRecording ? "text-red-500 bg-red-500/10" : "text-slate-400/60 hover:text-white hover:bg-white/5"
)}
disabled={!!selectedFile}
>
<Mic className="w-5 h-5" />
</button>
</div>
<textarea
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Написать..."
className="flex-1 bg-white/5 border border-white/10 rounded-[22px] focus:ring-1 focus:ring-indigo-500/30 focus:border-indigo-500/30 focus:bg-white/10 resize-none max-h-32 py-2.5 px-4 text-[16px] leading-relaxed text-white placeholder:text-slate-600 overflow-y-auto transition-all shadow-inner appearance-none"
rows={1}
style={{
minHeight: '44px',
display: 'flex',
alignItems: 'center'
}}
disabled={disabled || isRecording}
/>
<button
type="submit"
disabled={(!value.trim() && !selectedFile && !pendingAudio) || isSending || disabled}
className={cn(
"p-2.5 rounded-full transition-all duration-300 flex items-center justify-center",
((value.trim() || selectedFile || pendingAudio) && !isSending && !disabled)
? "text-indigo-400 bg-indigo-500/10 shadow-[0_0_15px_rgba(99,102,241,0.1)] active:scale-90"
: "text-slate-700 pointer-events-none"
)}
>
{isSending ? (
<Loader2 className="w-5 h-5 animate-spin" />
) : (
<Send className={cn(
"w-5 h-5",
((value.trim() || selectedFile || pendingAudio) && !isSending && !disabled) && "fill-indigo-400/10"
)} />
)}
</button>
</form>
<div className="hidden md:block text-center mt-2">
<p className="text-[10px] text-slate-400 font-medium">
Enter для отправки • Shift + Enter для переноса
</p>
</div>
</div>
</div>
)
}