Spaces:
Running

File size: 11,870 Bytes
526e04d
 
 
1ad4362
615c63b
d9f3520
526e04d
 
 
 
615c63b
526e04d
 
 
 
 
 
 
 
 
 
 
615c63b
 
 
1ad4362
 
615c63b
db2dc5e
615c63b
1ad4362
615c63b
526e04d
 
 
615c63b
 
 
 
 
 
 
1ad4362
615c63b
 
1ad4362
615c63b
1ad4362
615c63b
 
 
 
 
1ad4362
615c63b
 
 
 
 
 
db2dc5e
615c63b
 
 
 
 
 
 
 
 
 
 
1ad4362
 
db2dc5e
1ad4362
db2dc5e
 
 
 
615c63b
 
 
 
 
 
 
 
 
 
 
 
db2dc5e
 
 
 
 
 
 
1ad4362
615c63b
 
526e04d
1ad4362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
526e04d
 
d33ea59
9121435
526e04d
615c63b
 
 
 
 
 
 
 
 
 
 
1ad4362
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615c63b
 
db2dc5e
615c63b
 
db2dc5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
615c63b
 
 
 
526e04d
615c63b
d9f3520
526e04d
615c63b
 
 
 
 
 
 
 
d9f3520
55839d5
 
 
 
d9f3520
 
55839d5
 
 
 
526e04d
55839d5
 
 
 
d9f3520
 
55839d5
 
 
 
 
 
615c63b
526e04d
 
 
 
9a5b4ec
d9f3520
526e04d
d9f3520
615c63b
526e04d
 
 
 
782696b
526e04d
d9f3520
782696b
ca630f9
d9f3520
526e04d
 
 
 
 
d9f3520
 
 
 
 
 
526e04d
 
 
8bf69ca
526e04d
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
'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) {
            stopRecording()
            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 startRecording = async () => {
        try {
            const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
            streamRef.current = stream
            const mediaRecorder = new MediaRecorder(stream)
            mediaRecorderRef.current = mediaRecorder
            chunksRef.current = []

            mediaRecorder.ondataavailable = (e) => {
                if (e.data.size > 0) {
                    chunksRef.current.push(e.data)
                }
            }

            mediaRecorder.onstop = () => {
                // Save to pending instead of sending
                if (chunksRef.current.length > 0) {
                    const blob = new Blob(chunksRef.current, { type: 'audio/webm' })
                    setPendingAudio(blob)
                }
                // Cleanup stream
                streamRef.current?.getTracks().forEach(track => track.stop())
                streamRef.current = null
            }

            mediaRecorder.start()
            setIsRecording(true)
        } catch (err) {
            console.error('Error accessing microphone:', err)
            alert('Не удалось получить доступ к микрофону')
        }
    }

    const stopRecording = () => {
        if (mediaRecorderRef.current && isRecording) {
            mediaRecorderRef.current.stop()
            setIsRecording(false)
        }
    }

    const cancelRecording = () => {
        if (mediaRecorderRef.current && isRecording) {
            chunksRef.current = []
            mediaRecorderRef.current.stop()
            setIsRecording(false)
        }
        // Also cleanup stream immediately
        streamRef.current?.getTracks().forEach(track => track.stop())
        streamRef.current = null
    }

    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 (
        <div className="px-3 pb-3 pt-2 bg-[#0D0E18]/80 backdrop-blur-xl flex-shrink-0 sticky bottom-0 left-0 right-0 z-30 border-t border-white/10">
            <div className="max-w-4xl mx-auto relative">
                {/* File Preview */}
                {selectedFile && (
                    <div className="mb-2 p-2 bg-surface-elevated rounded-lg border border-white/10 flex items-center gap-2 w-fit">
                        <Paperclip className="w-4 h-4 text-indigo-400" />
                        <span className="text-xs text-white max-w-[200px] 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>
                    </div>
                )}

                {/* Audio Preview */}
                {pendingAudio && !isRecording && (
                    <div className="mb-2 p-2 bg-surface-elevated rounded-lg border border-indigo-500/30 flex items-center gap-2 w-fit">
                        <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">🎤 Голосовое сообщение</span>
                        <button onClick={clearPendingAudio} className="p-1 hover:bg-white/10 rounded-full">
                            <X className="w-3 h-3 text-slate-400" />
                        </button>
                    </div>
                )}

                {/* Audio Recording UI */}
                {isRecording && (
                    <div className="absolute inset-0 bg-surface-elevated rounded-2xl border border-red-500/50 flex items-center justify-between px-4 z-10">
                        <div className="flex items-center gap-2 text-red-400">
                            <div className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
                            <span className="text-sm font-medium">Запись...</span>
                        </div>
                        <div className="flex items-center gap-2">
                            {/* Cancel Button */}
                            <button
                                type="button"
                                onClick={cancelRecording}
                                className="p-2 bg-slate-500/20 text-slate-400 rounded-full hover:bg-slate-500/30 transition-colors"
                                title="Отменить запись"
                            >
                                <X className="w-5 h-5" />
                            </button>
                            {/* Send Button */}
                            <button
                                type="button"
                                onClick={stopRecording}
                                className="p-2 bg-red-500/20 text-red-500 rounded-full hover:bg-red-500/30 transition-colors"
                                title="Отправить голосовое"
                            >
                                <Send className="w-5 h-5" />
                            </button>
                        </div>
                    </div>
                )}

                <form
                    onSubmit={handleSubmit}
                    className="flex items-center gap-2 px-1.5 py-1 transition-all"
                >
                    <input
                        type="file"
                        ref={fileInputRef}
                        onChange={handleFileSelect}
                        className="hidden"
                        accept="image/*,.pdf,.txt,.doc,.docx"
                    />

                    <div className="flex items-center gap-0.5">
                        <button
                            type="button"
                            onClick={() => fileInputRef.current?.click()}
                            className={cn(
                                "p-2 rounded-full transition-all active:scale-90",
                                selectedFile ? "text-indigo-400 bg-indigo-500/10" : "text-slate-400/80 hover:text-white"
                            )}
                        >
                            <Paperclip className="w-5 h-5" />
                        </button>

                        <button
                            type="button"
                            onClick={startRecording}
                            className={cn(
                                "p-2 rounded-full transition-all active:scale-90",
                                isRecording ? "text-red-500 bg-red-500/10 animate-pulse" : "text-slate-400/80 hover:text-white"
                            )}
                            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/5 rounded-2xl focus:ring-1 focus:ring-white/10 resize-none max-h-32 py-3 px-4 text-[16px] leading-tight text-white placeholder:text-slate-500/60 overflow-y-auto transition-all"
                        rows={1}
                        style={{ minHeight: '48px' }}
                        disabled={disabled || isRecording}
                    />

                    <button
                        type="submit"
                        disabled={(!value.trim() && !selectedFile) || isSending || disabled}
                        className={cn(
                            "p-2.5 rounded-xl transition-all duration-500 relative flex items-center justify-center",
                            ((value.trim() || selectedFile) && !isSending && !disabled)
                                ? "text-white"
                                : "text-slate-600/50 opacity-50 grayscale"
                        )}
                    >
                        {isSending ? (
                            <Loader2 className="w-5 h-5 animate-spin" />
                        ) : (
                            <Send className={cn(
                                "w-5 h-5 transition-all duration-500",
                                ((value.trim() || selectedFile) && !isSending && !disabled)
                                    ? "scale-110 [filter:drop-shadow(0_0_8px_rgba(99,102,241,0.8))]"
                                    : "scale-100"
                            )} />
                        )}
                    </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>
    )
}